<template>
  <el-dialog
    :visible.sync="visible"
    :title="dialogType === 'add' ? '新增票种' : '编辑票种'"
    width="85%"
    append-to-body
    @close="handleClose"
  >
    <el-scrollbar
      :style="{ height: 'calc(100vh - 160px)' }"
      class="dialog-scroll">
      <el-form
        inline
        :model="form"
        ref="form"
        class="form-wrap"
        label-width="160px"
      >
        <div
          class="dialog-info1"
          style="padding-bottom: 0;">
          <div class="block-title">
            基本属性
          </div>
          <el-form-item
            verify
            label="票种分类"
            prop="category">
            <el-select
              value-key="id"
              v-model="form.category"
              placeholder="请选择">
              <el-option
                v-for="item in ticketCategory"
                :key="item.id"
                :value="item.id"
                :label="item.name">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            verify
            label="票种名称"
            prop="name"
          >
            <el-input v-model="form.name"></el-input>
          </el-form-item>

          <el-form-item
            verify
            label="在售状态"
            prop="isSale"
          >
            <el-switch
              v-model="form.isSale"
              :active-value="1"
              :inactive-value="0"
              active-text="在售"
              inactive-text="禁售">
            </el-switch>
          </el-form-item>

          <!-- 新增开票状态 -->
          <el-form-item
            verify
            label="开票状态"
            prop="isSupportInvoice"
          >
            <el-switch
              v-model="form.isSupportInvoice"
              :active-value="1"
              :inactive-value="0"
              active-text="支持开票"
              inactive-text="不支持开票">
            </el-switch>
          </el-form-item>

          <el-form-item
            verify
            label="销售价格"
            prop="price"
          >
            <el-input v-model="form.price"></el-input>
          </el-form-item>

          <!-- <el-form-item
            label="线上价格"
            prop="onlinePrice"
          >
            <el-input-number
              controls-position="right"
              v-model="form.onlinePrice"
              :min="0"
              :step="0.01"
              :precision="2"
            ></el-input-number>
          </el-form-item>

          <el-form-item
            label="虚拟高价"
            prop="highPrice"
          >
            <el-input-number
              controls-position="right"
              v-model="form.highPrice"
              :min="0"
              :step="0.01"
              :precision="2"
            ></el-input-number>
          </el-form-item> -->


          <el-form-item
            verify
            label="多日票类型"
            prop="useDaysDelayType"
          >
            <el-radio
              v-model="form.useDaysDelayType"
              :label="1">
              按照游玩时间延长
            </el-radio>
            <el-radio
              v-model="form.useDaysDelayType"
              :label="2">
              按照首次核销时间延长
            </el-radio>
          </el-form-item>

          <el-form-item
            v-if="form.category !== 'member'"
            verify
            label="日期类型"
            prop="useDateType"
          >
            <el-radio
              v-model="form.useDateType"
              :label="1">
              日历票
            </el-radio>
            <el-radio
              v-model="form.useDateType"
              :label="2">
              期票，时间期限内有效
            </el-radio>
          </el-form-item>

          <!-- <el-form-item
            v-if="form.useDateType === 2"
            label="消费日期"
            prop="validityUseDays"
          >
            自购买起
            <el-input-number
              controls-position="right"
              v-model="form.validityUseDays"
              :min="0"
              :step="1"
            ></el-input-number>
            天内可用
          </el-form-item> -->

          <!-- <el-form-item
            label="是否限制使用日期"
            prop="isUseDateLimit"
          >
            <el-switch
              v-model="form.isUseDateLimit"
              :active-value="1"
              :inactive-value="0"
              active-text="限制"
              inactive-text="不限">
            </el-switch>
          </el-form-item> -->
          <el-form-item
            v-if="form.category === 'member'"
            verify
            label="会员时长类型"
            prop="memberUseDateType"
          >
            <el-radio
              v-model="form.memberUseDateType"
              :label="1">
              【按天】：购买后多少天的有效期
            </el-radio>
            <el-radio
              v-model="form.memberUseDateType"
              :label="2">
              【按照使用日期】：固定某个时间期内可以用
            </el-radio>
          </el-form-item>

          <el-form-item
            v-if="!(form.category === 'member' && form.memberUseDateType === 2)"
            verify
            label="使用天数"
            prop="useDays"
          >
            <el-input-number
              controls-position="right"
              v-model="form.useDays"
              :min="0"
              :step="1"
            ></el-input-number>
          </el-form-item>

          <el-form-item
            v-if="!(form.category === 'member' && form.memberUseDateType === 1)"
            verify
            label="使用日期"
            prop="useDateStart"
          >
            <el-date-picker
              :editable="false"
              :clearable="false"
              :picker-options="pickerOptions"
              v-model="form.useDateStart"
              type="date"
              placeholder="开始日期"
            >
            </el-date-picker>
            <span style="margin:0 10px">至</span>
            <el-date-picker
              :editable="false"
              :clearable="false"
              :picker-options="pickerOptions"
              v-model="form.useDateEnd"
              type="date"
              placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item
            v-if="form.category === 'member'"
            verify
            label="激活方式"
            prop="memberActiveType"
          >
            <el-radio
              v-model="form.memberActiveType"
              :label="1">
              【购买即激活】 该年卡购买了就开始递减天数
            </el-radio>
            <el-radio
              v-model="form.memberActiveType"
              :label="2">
              【首次使用激活】：第一次用了之后才开始递减时间,示例值
            </el-radio>
          </el-form-item>

          <!-- <el-form-item
            label="是否实名制购票"
            prop="isRealName"
          >
            <el-switch
              v-model="form.isRealName"
              :active-value="1"
              :inactive-value="0"
              active-text="限制"
              inactive-text="不限">
            </el-switch>
          </el-form-item>

          <el-form-item
            label="实名要求"
            prop="realNameType"
          >
            <el-radio
              v-model="form.realNameType"
              :label="1">
              一证一人
            </el-radio>
            <el-radio
              v-model="form.realNameType"
              :label="2">
              一证多人
            </el-radio>
          </el-form-item>

          <el-form-item
            label="预订协议"
            prop="buyProtocol"
          >
            <el-input v-model="form.buyProtocol"></el-input>
            <el-checkbox
              v-model="form.isAgreeProtocol">
              <span style="color:#0075ff">是否必须同意预定协议才可以购买</span>
            </el-checkbox>
          </el-form-item> -->

          <!-- <el-form-item
            label="是否限制售卖日期"
            prop="isSaleDateLimit"
          >
            <el-switch
              v-model="form.isSaleDateLimit"
              :active-value="1"
              :inactive-value="0"
              active-text="限制"
              inactive-text="不限">
            </el-switch>
          </el-form-item> -->

          <el-form-item
            v-if="form.isSaleDateLimit === 1"
            verify
            label="售卖时间"
            prop="saleDateStart"
          >
            <el-date-picker
              :editable="false"
              :clearable="false"
              :picker-options="pickerOptions"
              v-model="form.saleDateStart"
              type="date"
              placeholder="开始日期"
            >
            </el-date-picker>
            <span style="margin:0 10px">至</span>
            <el-date-picker
              :editable="false"
              :clearable="false"
              :picker-options="pickerOptions"
              v-model="form.saleDateEnd"
              type="date"
              placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>

          <!-- <el-form-item
            label="是否限制预售范围"
            prop="isSalePreLimit"
          >
            <el-switch
              v-model="form.isSalePreLimit"
              :active-value="1"
              :inactive-value="0"
              active-text="限制"
              inactive-text="不限">
            </el-switch>
          </el-form-item>

          <el-form-item
            label="预售范围"
            prop="saleMaxPreDays"
          >
            <div class="item">
              最大预售
              <el-input-number
                controls-position="right"
                v-model="form.saleMaxPreDays"
                :min="0"
                :step="1"
              ></el-input-number>
              天以内的
            </div>
            <div class="item">
              最小需提前
              <el-input-number
                controls-position="right"
                v-model="form.saleMinPreDays"
                :min="0"
                :step="1"
              ></el-input-number>
              天预定(0 代表可订当日)
            </div>
          </el-form-item>

          <el-form-item
            label="是否限制下单数量"
            prop="isSaleNumsLimit"
          >
            <el-switch
              v-model="form.isSaleNumsLimit"
              :active-value="1"
              :inactive-value="0"
              active-text="限制"
              inactive-text="不限">
            </el-switch>
          </el-form-item>

          <el-form-item
            label="起订数"
            prop="saleMinNums"
          >
            <div class="item">
              单订单最小起订数
              <el-input-number
                controls-position="right"
                v-model="form.saleMinNums"
                :min="0"
                :step="1"
              ></el-input-number>
            </div>
            <div class="item">
              单订单最大起订数
              <el-input-number
                controls-position="right"
                v-model="form.saleMaxNums"
                :min="0"
                :step="1"
              ></el-input-number>
            </div>
          </el-form-item> -->

          <el-form-item
            verify
            label="核销凭证"
            prop="checkType"
          >
            <el-checkbox-group v-model="form.checkType">
              <el-checkbox
                label="qrcode">
                二维码
              </el-checkbox>
              <el-checkbox
                label="idcard">
                证件号
              </el-checkbox>
              <el-checkbox
                label="face">
                人脸
              </el-checkbox>
              <el-checkbox
                label="card">
                IC卡
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item
            verify
            label="核销规则"
            prop="checkRule"
          >
            <el-checkbox-group v-model="form.checkRule">
              <el-checkbox
                label="1">
                人工，检票设备核销
              </el-checkbox>
              <el-checkbox
                label="2">
                取票即核销
              </el-checkbox>
              <el-checkbox
                label="3">
                购买即核销
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item
            verify
            label="批量核销"
            prop="batchCheckRule"
          >
            <el-radio
              v-model="form.batchCheckRule"
              label="single">
              单次核销
            </el-radio>
            <el-radio
              v-model="form.batchCheckRule"
              label="batch">
              当票可以使用多次时，一次核销完成
            </el-radio>
          </el-form-item>

          <el-form-item
            label="核销语音"
            prop="checkVoice"
          >
            <el-input v-model="form.checkVoice">
            </el-input>
            <el-tag type="warning" style="margin-left: 10px;">如果为空 默认播报票种名称</el-tag>
          </el-form-item>

          <el-form-item
            verify
            label="星期检票规则"
            prop="useDayOfWeek"
          >
            <el-checkbox-group v-model="form.useDayOfWeek">
              <el-checkbox label="2">
                星期一
              </el-checkbox>
              <el-checkbox label="3">
                星期二
              </el-checkbox>
              <el-checkbox label="4">
                星期三
              </el-checkbox>
              <el-checkbox label="5">
                星期四
              </el-checkbox>
              <el-checkbox label="6">
                星期五
              </el-checkbox>
              <el-checkbox label="7">
                星期六
              </el-checkbox>
              <el-checkbox label="1">
                星期日
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item
            verify
            label="票种绑定的销售渠道"
            prop="source"
          >
            <el-checkbox-group v-model="form.source">
              <el-checkbox
                label="window">
                窗口
              </el-checkbox>
              <el-checkbox
                label="term">
                自助机
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item
            verify
            label="是否可以退订"
            prop="isAllowCancel"
          >
            <el-switch
              v-model="form.isAllowCancel"
              :active-value="1"
              :inactive-value="0"
              active-text="可以"
              inactive-text="不可以">
            </el-switch>
          </el-form-item>

          <el-form-item
            verify
            label="是否必须换票使用"
            prop="isNeedPrint"
          >
            <el-switch
              v-model="form.isNeedPrint"
              :active-value="1"
              :inactive-value="0"
              active-text="需要"
              inactive-text="不限">
            </el-switch>
          </el-form-item>

          <el-form-item
            verify
            label="过期操作"
            prop="outOfDateDeal"
          >
            <el-radio
              v-model="form.outOfDateDeal"
              :label="1">
              人工处理
            </el-radio>
            <el-radio
              v-model="form.outOfDateDeal"
              :label="2">
              自动核销
            </el-radio>
          </el-form-item>

          <template v-if="form.category === 'batch' && dialogType !== 'add'">
            <div class="block-title">
              时间场次
            </div>
            <div>
              <div class="btn-wrap-left">
                <!-- <el-button
                  plain
                  class="add-btn"
                  type="primary"
                  @click="handleAddBachConfig">
                  增加
                </el-button> -->
              </div>
              <div class="table-box">
                <el-tag type="warning">场次时间默认不限制为-1</el-tag>
                <el-table
                  border
                  stripe
                  :data="form.batchConfigList">
                  <el-table-column
                    label="场次名称"
                    prop="name">
                    <!-- <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.name"
                        style="width: 95%"></el-input>
                    </template> -->
                  </el-table-column>
                  <el-table-column
                    label="开始时间"
                    prop="startTime">
                    <!-- <template slot-scope="scope">
                      <el-time-picker
                        arrow-control
                        style="width: 95%"
                        v-model="scope.row.startTime"
                        format="HH:mm:ss"
                        value-format="HH:mm:ss"
                        placeholder="开始时间">
                      </el-time-picker>
                    </template> -->
                  </el-table-column>
                  <el-table-column
                    label="结束时间"
                    prop="endTime">
                    <!-- <template slot-scope="scope">
                      <el-time-picker
                        arrow-control
                        v-model="scope.row.endTime"
                        style="width: 95%"
                        format="HH:mm:ss"
                        value-format="HH:mm:ss"
                        placeholder="结束时间">
                      </el-time-picker>
                    </template> -->
                  </el-table-column>
                  <el-table-column
                    label="开场后X分钟停止售票"
                    prop="saleStopMinutes">
                    <!-- <template slot-scope="scope">
                      <el-input-number
                        controls-position="right"
                        style="width: 95%"
                        :min="-1"
                        :precision="0"
                        v-model="scope.row.saleStopMinutes"
                      ></el-input-number>
                    </template> -->
                  </el-table-column>
                  <el-table-column
                    label="开场前X分钟停止退票"
                    prop="cancelStopBeforeStartMinutes"
                    min-width="90">
                    <!-- <template slot-scope="scope">
                      <el-input-number
                        controls-position="right"
                        style="width: 95%"
                        :min="-1"
                        :precision="0"
                        v-model="scope.row.cancelStopBeforeStartMinutes"
                      ></el-input-number>
                    </template> -->
                  </el-table-column>
                  <el-table-column
                    label="开场后X分钟停止退票"
                    prop="cancelStopAfterStartMinutes"
                    min-width="90">
                    <!-- <template slot-scope="scope">
                      <el-input-number
                        controls-position="right"
                        style="width: 95%"
                        :min="-1"
                        :precision="0"
                        v-model="scope.row.cancelStopAfterStartMinutes"
                      ></el-input-number>
                    </template> -->
                  </el-table-column>
                  <el-table-column
                    label="开场前X分钟允许检票入场"
                    prop="preCheckMinutes"
                    min-width="90">
                    <!-- <template slot-scope="scope">
                      <el-input-number
                        controls-position="right"
                        style="width: 95%"
                        :min="-1"
                        :precision="0"
                        v-model="scope.row.preCheckMinutes"
                      ></el-input-number>
                    </template> -->
                  </el-table-column>
                  <el-table-column
                    label="开场后X分钟停止检票"
                    prop="stopCheckMinutes"
                    min-width="90">
                    <!-- <template slot-scope="scope">
                      <el-input-number
                        controls-position="right"
                        style="width: 95%"
                        :min="-1"
                        :precision="0"
                        v-model="scope.row.stopCheckMinutes"
                      ></el-input-number>
                    </template> -->
                  </el-table-column>
                  <el-table-column
                    label="无座位时的最大数量"
                    prop="maxSaleNums"
                    min-width="90">
                    <!-- <template slot-scope="scope">
                      <el-input-number
                        controls-position="right"
                        style="width: 95%"
                        :min="-1"
                        :precision="0"
                        v-model="scope.row.maxSaleNums"
                      ></el-input-number>
                    </template> -->
                  </el-table-column>
                  <!-- <el-table-column
                    width="110"
                    class-name="align-item"
                    label="操作">
                    <template slot-scope="scope">
                      <span
                        class="el-button el-button--primary el-button--small"
                        @click="deleteBachConfig(scope.$index, scope.row)">
                        <i class="el-icon-delete"></i>
                        删除
                      </span>
                    </template>
                  </el-table-column> -->
                </el-table>
              </div>
            </div>
          </template>

          <div class="block-title">
            添加适用景点
          </div>
          <div>
            <el-tag type="warning" style="margin-left: 10px;">景点检票次数不限制为-1</el-tag>

            <div class="btn-wrap-left">
              <el-button
                plain
                class="add-btn"
                type="primary"
                @click="handleAdd">
                添加单个
              </el-button>
            </div>
            <div class="table-box">
              <el-table
                border
                stripe
                :data="form.singleScenicList">
                <el-table-column
                  label="适用景点">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.scenicId">
                      <el-option
                        v-for="item in scenicList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="检票次数"
                  min-width="90">
                  <template slot-scope="scope">
                    <el-input-number
                      controls-position="right"
                      :min="-1"
                      :precision="0"
                      v-model="scope.row.checkLimitTimes"
                    ></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column
                  label="单日限制检票次数"
                  min-width="90">
                  <template slot-scope="scope">
                    <el-input-number
                      controls-position="right"
                      :min="-1"
                      :precision="0"
                      v-model="scope.row.singleDayLimitTimes"
                    ></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column
                  width="90"
                  class-name="align-item"
                  label="操作">
                  <template slot-scope="scope">
                    <span
                      class="el-button el-button--primary el-button--small"
                      @click="delScenic(scope.$index)">
                      <i class="el-icon-delete"></i>
                      删除
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="btn-wrap-left">
              <el-button
                plain
                class="add-btn"
                type="primary"
                @click="handleAdd('multiple')">
                添加群组
              </el-button>
            </div>
            <div class="table-box">
              <el-table
                border
                stripe
                :data="form.groupScenicList">
                <el-table-column
                  label="适用景点">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.scenicId"
                      multiple>
                      <el-option
                        v-for="item in scenicList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="检票次数总和"
                  min-width="90">
                  <template slot-scope="scope">
                    <el-input-number
                      controls-position="right"
                      :min="-1"
                      :precision="0"
                      v-model="scope.row.checkLimitTimes"
                    ></el-input-number>
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  label="单景点检票次数"
                  min-width="90">
                  <template slot-scope="scope">
                    <el-input-number
                      controls-position="right"
                      :min="-1"
                      :precision="0"
                      v-model="scope.row.scenicLimitTimes"
                    ></el-input-number>
                  </template>
                </el-table-column> -->
                <el-table-column
                  width="210"
                  class-name="align-item"
                  label="操作">
                  <template slot-scope="scope">
                    <div style="display:flex">
                      <span
                        class="el-button el-button--primary el-button--small"
                        @click="setSceneTimes(scope.$index, scope.row)">
                        <i class="el-icon-edit-outline"></i>
                        分配次数
                      </span>
                      <span
                        class="el-button el-button--primary el-button--small"
                        @click="delScenic(scope.$index, 'multiple')">
                        <i class="el-icon-delete"></i>
                        删除
                      </span>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <div class="block-title">
            添加工商银行子商户
          </div>
          <div>
            <div class="btn-wrap-left">
              <el-button
                plain
                class="add-btn"
                type="primary"
                @click="handleAddGhSubMerchant">
                添加
              </el-button>
            </div>
            <div class="table-box">
              <el-table
                border
                stripe
                :data="form.payGonghangTicketTypeMerchantList">
                <el-table-column
                  label="工行子商户">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.gonghangMerchantId">
                      <el-option
                        v-for="item in ghSubMerchantList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="分账比例"
                  min-width="90">
                  <template slot-scope="scope">
                    <el-input-number
                      controls-position="right"
                      :min="0"
                      :max="100"
                      v-model="scope.row.splitRatio"
                    ></el-input-number>
                    <span class="unit" style="margin-left: 20px; font-size: 16px;">{{ scope.row.splitRatio * 100 }}%</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="固定金额"
                  min-width="90">
                  <template slot-scope="scope">
                    <el-input-number
                      controls-position="right"
                      :min="0"
                      v-model="scope.row.fixedAmount"
                    ></el-input-number>
                    <Tip msg="避免小数点情况 优先按照固定金额计算分账金额否则按照分账比例" style="margin-left: 10px;"></Tip>
                  </template>
                </el-table-column>
                <el-table-column
                  width="90"
                  class-name="align-item"
                  label="操作">
                  <template slot-scope="scope">
                    <span
                      class="el-button el-button--primary el-button--small"
                      @click="delGhSubMerchant(scope.$index)">
                      <i class="el-icon-delete"></i>
                      删除
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <div class="block-title">
            添加发票销售方
          </div>
          <div>
            <div class="btn-wrap-left">
              <el-button
                plain
                class="add-btn"
                type="primary"
                @click="handleAddInvoiceSeller">
                添加
              </el-button>
            </div>
            <div class="table-box">
              <el-table
                border
                stripe
                :data="form.ticketTypeInvoiceSellerList">
                <el-table-column
                  label="销售方">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.invoiceSellerId">
                      <el-option
                        v-for="item in invoiceSellerList"
                        :key="item.id"
                        :label="item.invoiceSellerName"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="分账比例"
                  min-width="90">
                  <template slot-scope="scope">
                    <el-input-number
                      controls-position="right"
                      :min="0"
                      :max="1"
                      v-model="scope.row.splitRatio"
                    ></el-input-number>
                    <span class="unit" style="margin-left: 20px; font-size: 16px;">{{ scope.row.splitRatio * 100 }}%</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="固定金额"
                  min-width="90">
                  <template slot-scope="scope">
                    <el-input-number
                      controls-position="right"
                      :min="0"
                      v-model="scope.row.fixedAmount"
                    ></el-input-number>
                    <Tip msg="避免小数点情况 优先按照固定金额计算分账金额否则按照分账比例" style="margin-left: 10px;"></Tip>
                  </template>
                </el-table-column>
                <el-table-column
                  width="90"
                  class-name="align-item"
                  label="操作">
                  <template slot-scope="scope">
                    <span
                      class="el-button el-button--primary el-button--small"
                      @click="delInvoiceSeller(scope.$index)">
                      <i class="el-icon-delete"></i>
                      删除
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <div class="block-title">
            添加分账子景点
          </div>
          <div>
            <div class="btn-wrap-left">
              <el-button
                plain
                class="add-btn"
                type="primary"
                @click="handleAddScenicSplit">
                添加
              </el-button>
            </div>
            <div class="table-box">
              <el-table
                border
                stripe
                :data="form.ticketTypeScenicSplitRequests">
                <el-table-column
                  label="适用景点">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.scenicId">
                      <el-option
                        v-for="item in scenicList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="应分金额"
                  min-width="90">
                  <template slot-scope="scope">
                    <el-input-number
                      controls-position="right"
                      :min="0"
                      v-model="scope.row.price"
                    ></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column
                  width="90"
                  class-name="align-item"
                  label="操作">
                  <template slot-scope="scope">
                    <span
                      class="el-button el-button--primary el-button--small"
                      @click="delScenicSplit(scope.$index)">
                      <i class="el-icon-delete"></i>
                      删除
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <div class="dialog-btn-wrap">
          <el-button
            @click="handleClose">
            取消
          </el-button>
          <el-button
            @click="reset"
            v-if="dialogType === 'add'">
            重置
          </el-button>
          <el-button
            @click="submit"
            type="primary">
            保存
          </el-button>
        </div>
      </el-form>
    </el-scrollbar>
    <el-dialog
      :visible.sync="setTimeVisible"
      title="分配次数"
      append-to-body
      @close="handleGroupTimeClose">
      <div class="table-box">
        <el-table
          border
          stripe
          :data="currGroupScenicInfo">
          <el-table-column
            label="景点">
            <template slot-scope="scope">
              {{ scope.row.scenicName }}
            </template>
          </el-table-column>
          <el-table-column
            label="单个景点的检票次数"
            min-width="90">
            <template slot-scope="scope">
              <el-input-number
                controls-position="right"
                :min="-1"
                :precision="0"
                v-model="scope.row.scenicLimitTimes"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            label="单日限制检票次数"
            min-width="90">
            <template slot-scope="scope">
              <el-input-number
                controls-position="right"
                :min="-1"
                :precision="0"
                v-model="scope.row.singleDayLimitTimes"
              ></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div
        slot="footer"
        class="dialog-btn-wrap">
        <el-button
          @click="handleGroupTimeClose">
          取消
        </el-button>
        <el-button
          @click="handleGroupTimeSubmit"
          type="primary">
          确定
        </el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { addTicket, updateTicket, queueList, batchUpdateTicketBatch, delTicketBatch } from '@/api/ticketType'
import { getGhSubMerchantList } from '@/api/payChannel'
import { getInvoiceSellerList } from '@/api/invoice'
import { getLabelName } from '@/utils'
import { cloneDeep } from 'lodash'
import moment from 'moment'

const defaultForm = {
  category: 'ticket', // 大类
  name: '', // 名称
  isSale: 1, // 在售状态 0为禁售 1为在售 默认为1
  isSupportInvoice:1, // 是否支持发票 0为不支持 1为支持 默认为1
  price: '', // 窗口价格
  onlinePrice: 0, // 线上价格
  highPrice: 0, // 虚拟高价(划线价格)
  memberUseDateType: 1, // 会员时长类型 1【按天】：购买后多少天的有效期 由票种字段use_days生效 。2【按照使用日期】：固定某个时间期内可以用
  memberActiveType: 1, // 激活方式：【1:购买即激活】 该年卡购买了就开始递减天数。【2:首次使用激活】：第一次用了之后才开始递减时间,示例值(1)
  useDays: 1, // 使用天数 默认为1天 如果是年卡次卡 且会员卡的时长类型是按天数的 该值代表会员卡的时长天数 比如365 该值必须大于1 否则该值为0
  // validityUseDays: 0, // 期票模式下第一种情况 自购买日起X天内可使用 X必须大于0
  // isUseDateLimit: 1, // 是否限制使用日期 0为不限 1为限制 默认为0 如果限制 必须指定使用日期 期票模式下且不是购买日情况下必须指定
  useDateStart: moment().format('YYYY-MM-DD'), // 使用日期开始
  useDateEnd: moment().add(10, 'years').format('YYYY-MM-DD'), // 使用日期结束
  isRealName: 0, // 是否需要实名认证 0为不需要 1为需要 默认为0
  realNameType: 1, // 在实名制购票下 1 【一证一人】：购买两张票需要两张实名。2【一证多人】：购买多张只需要一人实名
  buyProtocol: '', // 预定协议 富文本
  isAgreeProtocol: 0, // 是否必须同意预定协议才可以购买 开启为1 默认为0
  isSaleDateLimit: 1, // 是否限制售卖日期 0为不限 1为限制 默认为0 如果限制 必须指定售卖时间
  saleDateStart: moment().format('YYYY-MM-DD'), // 售卖时间开始
  saleDateEnd: moment().add(10, 'years').format('YYYY-MM-DD'), // 售卖时间结束
  isSalePreLimit: 0, // 是否限制预售范围 0为不限 1为限制 默认为0 如果限制 必须指定预售范围
  saleMaxPreDays: 365, // 预售范围 最大预售X天以内的 默认为365 代表可预定一整年
  saleMinPreDays: 0, // 预售范围 最小需提前X天预定 默认为0 代表可订当日
  isSaleNumsLimit: 0, // 是否限制下单数量 0为不限 1为限制 默认为0 如果限制 必须指定下单数量
  saleMinNums: 0, // 单订单最小起订数
  saleMaxNums: 0, // 单订单最大起订数
  checkType: ['qrcode', 'idcard'], // 核销凭证 qrcode 二维码 idcard 证件号 face 人脸 多选用逗号分隔,示例值(qrcode,idcard)
  checkRule: ['1'], // 核销规则 1人工，检票设备核销 2取票即核销 3购买即核销 多选用逗号分隔,示例值(1,2)
  batchCheckRule: 'single', // 批量核销规则  single-代表单次核销 batch-代表当票可以使用多次时，一次核销完
  checkVoice: '', // 核销语音 如果为空 默认播报票种名称
  useDayOfWeek: ['1', '2', '3', '4', '5', '6', '7'], // 指定周几可以用 逗号分隔 1表示周日，2表示周一 依次类推,示例值(1,2,3,4,5,6,7)
  isAllowCancel: 1, // 是否允许取消订单 0为不允许 1为允许 默认为1
  isNeedPrint: 0, // 是否必须换票使用 默认为0 不限 否则需要门票取票打印后才可以核销
  outOfDateDeal: 1, // 过期操作 1人工处理 2自动核销 默认为1,示例值(1)
  singleScenicList: [], // 包含项目-单个景点数组
  groupScenicList: [], // 包含项目-组合景点数组 二维数组结构
  batchConfigList: [], // 批次配置数组
  ticketTypeScenicList: [], // 票种绑定的景点数组
  source: ['window', 'term'], // 票种绑定的销售渠道 窗口:window ; 自助机:term,示例值([window])
  useDateType: 1, // 使用日期类型 1日历票 2期票 默认为1
  useDaysDelayType:1, // 使用日期截止类型 1按使用日期截止 2按使用天数截止 默认为1
  payGonghangTicketTypeMerchantList: [], // 工行子商户列表
  ticketTypeInvoiceSellerList: [], // 发票销售方列表
  ticketTypeScenicSplitRequests: [] // 子分账景点
}

export default {
  computed: {
    scenicName () {
      return this.$localStore.get('scenicName') || this.$store.state.user.scenicName
    },
    ticketCategory () {
      return this.$store.state.app.ticketCategory
    }
  },
  props: {
    memberTypeList: {
      type: Array,
      default: () => []
    },
    // ticketItem: {
    //   type: Object,
    //   default: () => {}
    // },
    // dialogType: {
    //   type: String,
    //   default: ''
    // },
    scenicList: {
      type: Array,
      default: () => []
    },
    ticketTagList: {
      type: Array,
      default: () => []
    },
    invoiceSeller: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      ticketItem: {},
      dialogType: 'add',
      projectName: process.env.VUE_APP_PROJECT,
      visible: false,
      pickerOptions: {
        disabledDate: (theTime) => {
          let startTime = moment().format('YYYY-MM-DD') + ' 00:00:00'
          return moment(theTime).isBefore(startTime)
        }
      },
      dialogVisible: false,
      originRecord: {},
      currentRecord: {},
      man: 0, // 满x
      jian: 0, // 减y
      queueList: [],
      inputVisible: false,
      inputValue: [],
      form: defaultForm,
      batchConfig: {
        name: '', // 批次名称
        startTime: '', // 批次开始时间
        endTime: '', // 批次结束时间
        saleStopMinutes: -1, // 售卖截止时间
        cancelStopBeforeStartMinutes: -1, // 取消截止时间
        cancelStopAfterStartMinutes: -1, // 取消截止时间
        preCheckMinutes: -1, // 预检时间
        stopCheckMinutes: -1, // 停止检票时间
        maxSaleNums: -1 // 最大售卖数量
      },
      setTimeVisible: false,
      groupIndex: -1,
      currGroupScenicInfo: [],
      groupScenicMap: new Map(),
      ghSubMerchantList: [], // 工行子商户列表
      invoiceSellerList: [] // 发票销售方列表
    }
  },
  watch: {
    // 'form.memberType' (val) {
    //   console.log(val)
    //   this.form.name = val && val.name
    //   this.form.price = val && val.capital
    // },
    'form.category' (val) {
      if (val === 'member') {
        this.form.useDays = 365
      } else {
        this.form.useDays = 1
      }
    },
    // 满x减y
    'man': function (newVal, oldVal) {
      this.updateDiscountRule()
    },
    'jian': function (newVal, oldVal) {
      this.updateDiscountRule()
    }
  },
  methods: {
    show (ticketItem, type) {
      // this.reset()
      this.ticketItem = ticketItem
      this.dialogType = type
      if (ticketItem) {
        this.form = cloneDeep(ticketItem)
        this.form.source = ticketItem.source || []
        this.form.useDayOfWeek = this.form.useDayOfWeek.split(',')
        this.form.checkType = this.form.checkType.split(',')
        this.form.checkRule = this.form.checkRule.split(',')

        if (!this.form.source) {
          this.form.source = []
        }

        if (!this.form.ticketTypeScenicList) {
          this.form.ticketTypeScenicList = []
        }

        if (!this.form.singleScenicList) {
          this.form.singleScenicList = []
        }

        if (!this.form.groupScenicList) {
          this.form.groupScenicList = []
        }

        if (!this.form.batchConfigList) {
          this.form.batchConfigList = []
        }

        if (!this.form.payGonghangTicketTypeMerchantList) {
          this.form.payGonghangTicketTypeMerchantList = []
        }

        if (!this.form.ticketTypeInvoiceSellerList) {
          this.form.ticketTypeInvoiceSellerList = []
        }

        if (!this.form.ticketTypeScenicSplitRequests) {
          this.form.ticketTypeScenicSplitRequests = []
        }

        let groupFlag = ''
        let groupIndex = 0
        this.form.ticketTypeScenicList.forEach(item => {
          if (!item.groupFlag) {
            this.form.singleScenicList.push({
              scenicId: item.scenicId,
              checkLimitTimes: item.checkLimitTimes,
              singleDayLimitTimes: item.singleDayLimitTimes
            })
          } else {
            if (groupFlag !== item.groupFlag) {
              groupFlag = item.groupFlag
              groupIndex += 1
              this.form.groupScenicList.push({
                scenicId: [item.scenicId],
                checkLimitTimes: item.checkLimitTimes,
                scenicLimitTimes: item.scenicLimitTimes,
                singleDayLimitTimes: item.singleDayLimitTimes
              })
            } else {
              this.form.groupScenicList[groupIndex - 1].scenicId.push(item.scenicId)
            }
          }
        })
      }
      // 复制票种功能
      if (this.dialogType === 'add' && this.ticketItem) {
        // '创建票种失败，名称或助记符重复' 需要在此之前去掉名称和助记符，待复制时用户填入
        this.codeCopyFromVisibleEdit() // 执行与edit一样的操作，要确保传过来的ticketItem把ID信息去了
      }
      if (typeof this.form.requiredField === 'string') {
        this.form.requiredField = JSON.parse(this.form.requiredField)
      } else {
        this.form.requiredField = []
      }
      if (this.form && this.form.discountRule) {
        // 初始化满减
        let result = this.parseDiscountRule(this.form.discountRule)
        this.man = result ? result.man : this.man
        this.jian = result ? result.jian : this.jian
      }
      if (this.projectName === 'hangzhousuodao') {
        this.getQueue()
      }

      this.getGhSubMerchantList()
      this.getInvoiceSellerList()

      this.visible = true
    },
    async getGhSubMerchantList () {
      // 获取工行子商户列表
      const res = await getGhSubMerchantList()
      this.ghSubMerchantList = res.data || []
    },
    async getInvoiceSellerList () {
      // 获取发票销售方列表
      const res = await getInvoiceSellerList()
      this.invoiceSellerList = res.data || []
    },
    updateDiscountRule: function () {
      let man = parseInt(this.man)
      let jian = parseInt(this.jian)
      let form = this.form
      form.discountRule = '满' + man + '减' + jian
    },
    // 从满10减1这种字符串里提取出10和1
    parseDiscountRule (discountRule) {
      let pattern = /满(\d+)减(\d+)/ // 定义正则表达式
      let match = discountRule.match(pattern) // 使用 match() 方法匹配字符串
      if (match) {
        let man = parseInt(match[1]) // 第一个括号中的数字为满减条件
        let jian = parseInt(match[2]) // 第二个括号中的数字为满减金额
        return { man, jian }
      }
      return null // 如果匹配失败，则返回 null
    },
    getLabelName,
    // isScenicDisabled (id) {
    //   return this.form.singleScenicList.some(s => s.scenicId === id)
    // },
    handleClose () {
      this.visible = false
      this.reset()
      this.$emit('updateList')
    },
    reset () {
      this.$refs.form.resetFields()
      this.form = { ...defaultForm }
      this.form.singleScenicList = []
      this.form.groupScenicList = []
    },
    handleMemberChange (e) {
      let target = this.memberTypeList.find(i => i.id === e)
      this.form.price = target.capital
      this.form.name = target.name
    },
    // 增加 适用景点-检票次数
    handleAdd (type) {
      if (type === 'multiple') {
        this.form.groupScenicList.push({
          scenicId: [],
          checkLimitTimes: 1,
          singleDayLimitTimes: -1,
          scenicLimitTimes: -1
        })
      } else {
        this.form.singleScenicList.push({
          scenicId: '',
          checkLimitTimes: 1,
          singleDayLimitTimes: -1,
          scenicLimitTimes: -1
        })
      }
    },
    handleAddGhSubMerchant () {
      this.form.payGonghangTicketTypeMerchantList.push({
        gonghangMerchantId: '',
        splitRatio: 0,
        fixedAmount: ''
      })
    },
    delGhSubMerchant (index) {
      this.form.payGonghangTicketTypeMerchantList.splice(index, 1)
    },
    handleAddInvoiceSeller () {
      this.form.ticketTypeInvoiceSellerList.push({
        invoiceSellerId: '',
        splitRatio: 0,
        fixedAmount: ''
      })
    },
    delInvoiceSeller (index) {
      this.form.ticketTypeInvoiceSellerList.splice(index, 1)
    },
    handleAddScenicSplit () {
      this.form.ticketTypeScenicSplitRequests.push({
        scenicId: '',
        price: 0
      })
    },
    delScenicSplit (index) {
      this.form.ticketTypeScenicSplitRequests.splice(index, 1)
    },
    setSceneTimes (idx, item) {
      if (!item || !item.scenicId || !item.scenicId.length) {
        return this.$message.error('请先添加适用景点')
      }

      this.groupIndex = idx
      const groupScenic = this.groupScenicMap.get(idx)

      if (groupScenic) {
        this.currGroupScenicInfo = groupScenic
      } else {
        this.currGroupScenicInfo = []
        item.scenicId.forEach(id => {
          const scene = this.scenicList.find((scene) => scene.id === id)

          if (scene) {
            this.currGroupScenicInfo.push({
              scenicId: scene.id,
              scenicName: scene.name,
              scenicLimitTimes: -1,
              singleDayLimitTimes: -1,
              checkLimitTimes: item.checkLimitTimes
            })
          }
        })
      }

      this.setTimeVisible = true
    },
    handleGroupTimeClose () {
      this.currGroupScenicInfo = []
      this.setTimeVisible = false
    },
    handleGroupTimeSubmit () {
      this.groupScenicMap.set(this.groupIndex, this.currGroupScenicInfo)
      this.currGroupScenicInfo = []
      this.setTimeVisible = false
    },
    // 删除 适用景点-检票次数
    delScenic (index, type) {
      if (type === 'multiple') {
        this.form.groupScenicList.splice(index, 1)
      } else {
        this.form.singleScenicList.splice(index, 1)
      }
    },
    isScenicValid () {
      if (this.form.singleScenicList.length === 0 && this.form.groupScenicList.length === 0) {
        this.$message.error('请添加适用景点')
        return false
      } else if (this.form.singleScenicList.some(item => !item.scenicId)) {
        this.$message.error('适用景点信息错误')
        return false
      } else if (this.form.groupScenicList.some(item => !item.scenicId.length)) {
        this.$message.error('适用景点信息错误')
        return false
      } else {
        return true
      }
    },
    handleAddBachConfig () {
      this.form.batchConfigList.push({ ...this.batchConfig })
    },
    deleteBachConfig (index, row) {
      if (row.id) {
        this.$confirm('确定删除场次时间配置?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delTicketBatch([row.id]).then(res => {
            if (res.code === '200') {
              this.$message.success('删除成功')
              this.form.batchConfigList.splice(index, 1)
            }
          })
        }).catch(() => {})
      } else {
        this.form.batchConfigList.splice(index, 1)
      }
    },
    async saveAllBatchConfig () {
      const ticketTypeId = this.form.id
      if (!ticketTypeId) {
        return
      }

      batchUpdateTicketBatch(ticketTypeId, this.form.batchConfigList).then(res => {
        if (res.code !== '200') {
          this.$message.error('场次保存失败')
        }
      })
    },
    setGroupScenicConfig () {
      const gsList = []
      const { groupScenicList } = this.form

      for (let i = 0; i < groupScenicList.length; i++) {
        const item = groupScenicList[i]
        const sList = this.groupScenicMap.get(i) || item.scenicId.map(scenicId => {
          return {
            scenicId,
            checkLimitTimes: item.checkLimitTimes,
            singleDayLimitTimes: item.singleDayLimitTimes || -1,
            scenicLimitTimes: item.scenicLimitTimes || -1
          }
        })
        gsList.push(sList)
      }

      this.form.groupScenicList = gsList
    },
    async submit () {
      this.$refs.form.validate(valid => {
        // 会员不检查景点
        const {
          price,
          useDateStart,
          useDateEnd,
          isSaleDateLimit,
          saleDateStart,
          saleDateEnd
        } = this.form

        if (valid) {
          if (isNaN(Number(price)) || price < 0) {
            this.$message.error('请填写销售价格')
            return
          }

          if (moment(useDateStart).isAfter(useDateEnd)) {
            this.$message.error('游玩开始时间不可晚于游玩截止时间')
            return
          }

          if (isSaleDateLimit === 1 && moment(saleDateStart).isAfter(saleDateEnd)) {
            this.$message.error('起售时间不可晚于停售时间')
            return
          }

          if (moment(useDateStart).isAfter(useDateEnd)) {
            this.$message.error('游玩开始时间不可晚于游玩截止时间')
            return
          }

          if (isSaleDateLimit === 1 && moment(saleDateEnd).isAfter(useDateEnd)) {
            this.$message.error('停售时间不可晚于游玩截止时间')
            return
          }

          if (isSaleDateLimit === 1 && moment(saleDateStart).isAfter(useDateStart)) {
            this.$message.error('起售时间不可晚于游玩开始时间')
            return
          }

          // if (category === 'batch') {
          //   if (batchConfigList.length === 0) {
          //     this.$message.error('请添加场次时间')
          //     return
          //   }

          //   if (batchConfigList.some(item => !item.name)) {
          //     this.$message.error('场次名称不能为空')
          //     return
          //   }

          //   if (batchConfigList.some(item => !item.startTime)) {
          //     this.$message.error('场次开始时间不能为空')
          //     return
          //   }

          //   if (batchConfigList.some(item => !item.endTime)) {
          //     this.$message.error('场次结束时间不能为空')
          //     return
          //   }
          // }

          if (!this.isScenicValid()) {
            return
          }

          // this.saveAllBatchConfig()

          // if (moment('2019-01-21 ' + this.form.useDateStart).isAfter('2019-01-21 ' + this.form.useDateEnd)) {
          //   this.$message.error('当日游玩开始时间不可晚于结束时间')
          //   return
          // }

          // this.form.saleDateStart = this.formatStartTime(this.form.saleDateStart)
          // this.form.saleDateEnd = this.formatEndTime(this.form.saleDateEnd)
          // this.form.useDateStart = this.formatStartTime(this.form.useDateStart)
          // this.form.useDateEnd = this.formatEndTime(this.form.useDateEnd)
          // this.form.requiredField = JSON.stringify(this.form.requiredField)
          // form.useDayOfWeek.join is not a function"
          this.form.price = Number(price)
          this.form.useDayOfWeek = this.form.useDayOfWeek?.join(',')
          this.form.checkRule = this.form.checkRule.join(',')
          this.form.checkType = this.form.checkType.join(',')

          this.setGroupScenicConfig()

          switch (this.dialogType) {
            case 'add':
              this.addTicket()
              break
            case 'edit':
              this.updateTicket()
              break
          }
        } else {
          console.log('error submit!!')
          this.$message.error('请补充表单内容')
          return false
        }
      })
    },
    addTicket () {
      this.form.creator = this.$store.state.user.name

      addTicket(this.form).then(res => {
        if (res.code !== '200') {
          this.$message.error(res.msg || '添加失败')
        } else {
          this.$message.success('添加成功')
          this.reset()
          this.handleClose()
          this.$emit('updateList')
        }
      })
    },
    updateTicket () {
      updateTicket(this.form).then(res => {
        if (res.code !== '200') {
          this.$message.error(res.msg || '保存失败')
        } else {
          this.$message.success('保存成功')
          this.reset()
          this.handleClose()
          this.$emit('updateList')
        }
      })
    },
    showInput () {
      this.inputVisible = true
    },

    handleInputConfirm () {
      let inputValue = this.inputValue
      if (inputValue.length) {
        this.form.dateCheckRules.push({ useDateStart: inputValue[0], useDateEnd: inputValue[1] })
      }
      this.inputVisible = false
      this.inputValue = []
    },
    getQueue () {
      queueList({ pageNum: 1, pageSize: 9999 }).then(res => {
        this.queueList = res?.data.list
      })
    },
    formatStartTime (time) {
      return moment(time).hour(0).minute(0).second(0).toDate()
    },
    formatEndTime (time) {
      return moment(time).hour(23).minute(59).second(59).toDate()
    },
    // 从visible的edit那边抄过来的大段代码
    codeCopyFromVisibleEdit () {
      delete this.form.id
    }
  }
}
</script>
<style lang="scss">
.el-dialog {
  margin-top: 5vh !important;

  .form-wrap .el-input {
    width: auto !important;
  }
}
.el-scrollbar__wrap {
  overflow-x: hidden;
}
</style>
<style scoped lang="scss">
.table-box{
    width: calc(100% - 40px);
    margin-top: 0;
  }

.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
