<template>
  <el-form
    inline
    :model="form"
    ref="form"
    class="form-wrap"
    label-width="150px"
  >
    <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
        v-if="form.category===3 || form.category===5"
        verify
        label="会员类型"
        prop="member_type_id"
      >
        <el-select
          filterable
          v-model="form.member_type_id"
          @change="handleMemberChange">
          <el-option
            v-for="item in memberTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        verify
        :label="form.category===3 || form.category===5?'会员名称':'票种名称'"
        prop="name"
      >
        <el-input v-model="form.name"></el-input>
      </el-form-item>

      <el-form-item
        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="price"
      >
        <el-input-number
          controls-position="right"
          v-model="form.price"
          :min="0"
          :step="0.01"
          :precision="2"
        ></el-input-number>
      </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
        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
        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
        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
        label="使用日期"
        prop="useDateStart"
      >
        <el-date-picker
          :editable="false"
          :clearable="false"
          :picker-options="pickerOptions"
          v-model="form.useDateStart"
          type="date"
          placeholder="开始日期"
        >
        </el-date-picker>
        <span>至</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
        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:#304d79">是否必须同意预定协议才可以购买</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
        label="售卖时间"
        prop="saleDateStart"
      >
        <el-date-picker
          :editable="false"
          :clearable="false"
          :picker-options="pickerOptions"
          v-model="form.saleDateStart"
          type="date"
          placeholder="开始日期"
        >
        </el-date-picker>
        <span>至</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
        label="核销凭证"
        prop="checkType"
      >
        <el-checkbox-group v-model="form.checkType">
          <el-checkbox
            label="二维码"
            value="qrcode" />
          <el-checkbox
            label="证件号"
            value="idcard" />
          <el-checkbox
            label="人脸"
            value="face" />
        </el-checkbox-group>
      </el-form-item>

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

      <el-form-item
        label="核销语音"
        prop="checkVoice"
      >
        <el-input v-model="form.checkVoice">
        </el-input>
      </el-form-item>

      <el-form-item
        verify
        label="星期检票规则"
        prop="useDayOfWeek"
      >
        <el-checkbox-group v-model="form.useDayOfWeek">
          <el-checkbox :label="0">
            星期一
          </el-checkbox>
          <el-checkbox :label="1">
            星期二
          </el-checkbox>
          <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-group>
      </el-form-item>

      <el-form-item
        label="票种绑定的销售渠道"
        prop="ticketTypeSourceList"
      >
        <el-checkbox-group v-model="form.ticketTypeSourceList">
          <el-checkbox
            label="窗口"
            value="window" />
          <el-checkbox
            label="自助机"
            value="term" />
        </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>

      <el-form-item
        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>

      <div class="block-title">
        添加适用景点
      </div>
      <!-- 非会员预售类型 -->
      <div v-if="form.category!==3 && form.category!==5">
        <div class="btn-wrap-left">
          <el-button
            plain
            class="add-btn"
            type="primary"
            @click="handleAdd">
            添加单个
          </el-button>
        </div>
        <div class="tableBox">
          <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="0"
                  :precision="2"
                  v-model="scope.row.part_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="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="tableBox">
          <el-table
            border
            stripe
            :data="form.multiplesingleScenicList">
            <el-table-column
              label="适用景点">
              <template slot-scope="scope">
                <el-select
                  @change="handleChange(scope.row)"
                  v-model="scope.row.scenic_ids"
                  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="0"
                  :precision="2"
                  v-model="scope.row.part_price"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column
              min-width="90"
              class-name="align-item"
              label="操作">
              <template slot-scope="scope">
                <div style="display:flex">
                  <span
                    class="el-button el-button--primary el-button--small"
                    @click="assign(scope.row)">
                    分配次数
                  </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>

    <div class="dialog-btn-wrap">
      <el-button
        @click="reset"
        v-if="dialogType==='add'">
        重置
      </el-button>
      <el-button
        @click="handleClose"
        v-if="dialogType==='edit'">
        关闭
      </el-button>
      <el-button
        @click="submit"
        type="primary">
        保存
      </el-button>
    </div>

    <!-- 会员类型选择 -->
    <MemberType
      ref="memberType"
      v-model="form.memberType"></MemberType>

    <el-dialog
      append-to-body
      title="分配次数"
      :visible.sync="dialogVisible"
    >
      <div style="margin-top:10px;margin-bottom:10px;text-align:center">
        分配后再修改景点,分配结果将全部重置
      </div>
      <el-table :data="currentRecord.check_scenic_limit_times_arr">
        <el-table-column
          label="适用景点">
          <template slot-scope="scope">
            {{ scenicList.find(v=>v.id===currentRecord.scenic_ids[scope.$index]).name }}
          </template>
        </el-table-column>
        <el-table-column
          label="次数（-1 表示不限制）">
          <template slot-scope="scope">
            <el-input-number v-model="currentRecord.check_scenic_limit_times_arr[scope.$index]">
            </el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <span
        slot="footer"
        class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="saveAssign">确 定</el-button>
      </span>
    </el-dialog>
  </el-form>
</template>

<script>
import { addTicket, updateTicket, queueList } from '@/api/ticketType'
import { getLabelName } from '@/utils'
import moment from 'moment'
import MemberType from './MemberType'
import Vue from 'vue'

const defaultForm = {
  category: 'ticket', // 大类
  name: '', // 名称
  isSale: 1, // 在售状态 0为禁售 1为在售 默认为1
  price: 0, // 窗口价格
  onlinePrice: 0, // 线上价格
  highPrice: 0, // 虚拟高价(划线价格)
  useDays: 1, // 使用天数 默认为1天 如果是年卡次卡 且会员卡的时长类型是按天数的 该值代表会员卡的时长天数 比如365 该值必须大于1 否则该值为0
  validityUseDays: 0, // 期票模式下第一种情况 自购买日起X天内可使用 X必须大于0
  isUseDateLimit: 0, // 是否限制使用日期 0为不限 1为限制 默认为0 如果限制 必须指定使用日期 期票模式下且不是购买日情况下必须指定
  useDateStart: '', // 使用日期开始
  useDateEnd: '', // 使用日期结束
  isRealName: 0, // 是否需要实名认证 0为不需要 1为需要 默认为0
  realNameType: 1, // 在实名制购票下 1 【一证一人】：购买两张票需要两张实名。2【一证多人】：购买多张只需要一人实名
  buyProtocol: '', // 预定协议 富文本
  isAgreeProtocol: 0, // 是否必须同意预定协议才可以购买 开启为1 默认为0
  isSaleDateLimit: 0, // 是否限制售卖日期 0为不限 1为限制 默认为0 如果限制 必须指定售卖时间
  saleDateStart: '', // 售卖时间开始
  saleDateEnd: '', // 售卖时间结束
  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 证件号 face 人脸 多选用逗号分隔,示例值(qrcode,idcard)
  checkRule: ['1'], // 核销规则 1人工，检票设备核销 2取票即核销 3购买即核销 多选用逗号分隔,示例值(1,2)
  checkVoice: '', // 核销语音 如果为空 默认播报票种名称
  useDayOfWeek: [0, 1, 2, 3, 4, 5, 6], // 指定周几可以用 逗号分隔 1表示周日，2表示周一 依次类推,示例值(1,2,3,4,5,6,7)
  isAllowCancel: 1, // 是否允许取消订单 0为不允许 1为允许 默认为1
  isNeedPrint: 0, // 是否必须换票使用 默认为0 不限 否则需要门票取票打印后才可以核销
  outOfDateDeal: 1, // 过期操作 1人工处理 2自动核销 默认为1,示例值(1)
  memberActiveType: 1, // 激活方式：【1:购买即激活】 该年卡购买了就开始递减天数。【2:首次使用激活】：第一次用了之后才开始递减时间,示例值(1)
  singleScenicList: [], // 包含项目-单个景点数组
  groupScenicList: [], // 包含项目-组合景点数组 二维数组结构
  ticketTypeSourceList: [] // 票种绑定的销售渠道 窗口:window ; 自助机:term,示例值([window])
}
export default {
  components: {
    MemberType
  },
  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 {
      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
    }
  },
  watch: {
    visible (val) {
      this.reset()
      if (val) {
        if (this.dialogType === 'edit' && this.ticketItem) {
          this.form = JSON.parse(JSON.stringify(this.ticketItem))

          if (this.form.member_type_id) {
            this.form.memberType = {
              id: this.form.member_type_id,
              name: this.form.member_type_name,
              capital: this.form.price
            }
          }

          this.form.useDayOfWeek = JSON.parse('[' + this.form.useDayOfWeek + ']')
          if (!this.form.date_check_rules) {
            this.form.date_check_rules = []
          } else if (typeof this.form.date_check_rules === 'string') {
            this.form.date_check_rules = JSON.parse(this.form.date_check_rules)
          }
          // 新建和编辑的时候 传scenic_ids 编辑回显时 通过combined_time字段重新组装成scenic_ids的结构
          // 使multiplesingleScenicList响应式 确保数据变=>视图变
          Vue.set(this.form, 'multiplesingleScenicList', [])
          this.form.singleScenicList.forEach(v => {
            if (v.combined_time) return this.form.multiplesingleScenicList.push(v) // 带combined_time 全放到multiplesingleScenicList
          })
          this.form.singleScenicList = this.form.singleScenicList.filter(v => !v.combined_time) // 不带combined_time 全放到singleScenicList 不用再操作
          let containerList = this.form.multiplesingleScenicList
          let containerListCopy = containerList
          this.form.multiplesingleScenicList = []
          for (var i = 0; i < containerList.length; i++) {
            const tempArr = containerListCopy.filter(v => v.combined_time === containerList[i].combined_time)
            // 同一combined_time的组装至rowTemp中 再放进multiplesingleScenicList里
            let rowTemp = {
              scenic_ids: tempArr.map(v => v.scenicId),
              checkLimitTimes: containerList[i].checkLimitTimes,
              check_scenic_limit_times_arr: tempArr.map(v => v.check_scenic_limit_times) || Array(tempArr.length).fill(-1)
            }
            tempArr.length && this.form.multiplesingleScenicList.push(rowTemp)
            // 放完后 把备份数组中 该combined_time的数据剔除 防止重复
            containerListCopy = containerListCopy.filter(v => v.combined_time !== containerList[i].combined_time)
          }
        }
        // 复制票种功能
        if (this.dialogType === 'add' && this.ticketItem) {
          // '创建票种失败，名称或助记符重复' 需要在此之前去掉名称和助记符，待复制时用户填入
          this.codeCopyFromVisibleEdit() // 执行与edit一样的操作，要确保传过来的ticketItem把ID信息去了
        }
        if (typeof this.form.required_field === 'string') {
          this.form.required_field = JSON.parse(this.form.required_field)
        } else {
          this.form.required_field = []
        }
      }
      if (val && this.form && this.form.discount_rule) {
        // 初始化满减
        let result = this.parseDiscountRule(this.form.discount_rule)
        this.man = result ? result.man : this.man
        this.jian = result ? result.jian : this.jian
      }
      if (this.projectName === 'hangzhousuodao') {
        this.getQueue()
      }
    },
    // 'form.memberType' (val) {
    //   console.log(val)
    //   this.form.name = val && val.name
    //   this.form.price = val && val.capital
    // },
    'form.category' (val) {
      // 预售会员，价格不可编辑；名字自动填入会员类型名
      if (val !== 3 && val !== 5) {
        // this.form.name = ''
        // this.form.price = 0
        this.form.memberType = null
      }
    },
    // 满x减y
    'man': function (newVal, oldVal) {
      this.updateDiscountRule()
    },
    'jian': function (newVal, oldVal) {
      this.updateDiscountRule()
    }
  },
  methods: {
    updateDiscountRule: function () {
      let man = parseInt(this.man)
      let jian = parseInt(this.jian)
      let form = this.form
      form.discount_rule = '满' + 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.$parent.handleClose()
    },
    reset () {
      this.$refs.form.resetFields()
      this.form = JSON.parse(JSON.stringify(defaultForm))
      this.form.singleScenicList = []
      this.form.multiplesingleScenicList = []
    },
    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.multiplesingleScenicList.push({
          scenic_ids: [],
          checkLimitTimes: 1
        })
      } else {
        this.form.singleScenicList.push({
          scenic: {
            id: '',
            name: ''
          },
          scenicId: '',
          checkLimitTimes: 1
        })
      }
    },
    // 删除 适用景点-检票次数
    delScenic (index, type) {
      if (type === 'multiple') {
        this.form.multiplesingleScenicList.splice(index, 1)
      } else {
        this.form.singleScenicList.splice(index, 1)
      }
    },
    isScenicValid () {
      if (this.form.singleScenicList.length === 0 && this.form.multiplesingleScenicList.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.multiplesingleScenicList.some(item => !item.scenic_ids.length)) {
        this.$message.error('适用景点信息错误')
        return false
      } else {
        return true
      }
    },
    submit () {
      this.$refs.form.validate(valid => {
        // 会员不检查景点

        if (valid) {
          // if (moment(this.form.sell_startdate).isAfter(this.form.sell_enddate)) {
          //   this.$message.error('起售时间不可晚于停售时间')
          //   return
          // }

          // // 会员不判断使用时间
          // if (this.form.category !== 3 && this.form.category !== 5) {
          //   if (moment(this.form.use_startdate).isAfter(this.form.use_enddate)) {
          //     this.$message.error('游玩开始时间不可晚于游玩截止时间')
          //     return
          //   }
          //   if (moment(this.form.sell_enddate).isAfter(this.form.use_enddate)) {
          //     this.$message.error('停售时间不可晚于游玩截止时间')
          //     return
          //   }
          //   if (moment(this.form.sell_startdate).isAfter(this.form.use_startdate)) {
          //     this.$message.error('起售时间不可晚于游玩开始时间')
          //     return
          //   }
          // }

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

          // this.form.sell_startdate = this.formatStartTime(this.form.sell_startdate)
          // this.form.sell_enddate = this.formatEndTime(this.form.sell_enddate)
          // this.form.use_startdate = this.formatStartTime(this.form.use_startdate)
          // this.form.use_enddate = this.formatEndTime(this.form.use_enddate)
          // this.form.singleScenicList = this.form.singleScenicList.concat(this.form.multiplesingleScenicList)
          // this.form.required_field = JSON.stringify(this.form.required_field)
          // form.useDayOfWeek.join is not a function"
          this.form.useDayOfWeek = this.form.useDayOfWeek?.join(',')
          this.form.checkRule = this.form.checkRule.join(',')
          this.form.checkType = this.form.checkType.join(',')

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

      addTicket(this.form).then(res => {
        if (res.code !== '200') {
          this.$message.success(res.data.msg || '添加失败')
          return
        }
        this.$message.success('添加成功')
        this.reset()
        this.handleClose()
        this.$emit('updateList')
      })
    },
    updateTicket () {
      updateTicket(this.form).then(res => {
        if (res.code !== '200') {
          this.$message.success(res.data.msg || '保存失败')
          return
        }
        this.$message.success('保存成功')
        this.reset()
        this.handleClose()
        this.$emit('updateList')
      })
    },
    assign (record) {
      if (!record.scenic_ids.length) return this.$message.error('请先选择景点')
      if (!record.check_scenic_limit_times_arr) {
        record.check_scenic_limit_times_arr = []
        record.scenic_ids.forEach(v => {
          record.check_scenic_limit_times_arr.push(-1)
        })
      }
      this.originRecord = record
      this.currentRecord = JSON.parse(JSON.stringify(record))
      this.dialogVisible = true
    },
    saveAssign () {
      this.originRecord.check_scenic_limit_times_arr = this.currentRecord.check_scenic_limit_times_arr
      this.dialogVisible = false
    },
    handleChange (record) {
      record.check_scenic_limit_times_arr = []
      record.scenic_ids.forEach(v => {
        record.check_scenic_limit_times_arr.push(-1)
      })
    },
    handleCloseTag (tag) {
      this.form.date_check_rules.splice(this.form.date_check_rules.indexOf(tag), 1)
    },

    showInput () {
      this.inputVisible = true
    },

    handleInputConfirm () {
      let inputValue = this.inputValue
      if (inputValue.length) {
        this.form.date_check_rules.push({ use_startdate: inputValue[0], use_enddate: 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 () {
      this.form = JSON.parse(JSON.stringify(this.ticketItem))

      if (this.form.member_type_id) {
        this.form.memberType = {
          id: this.form.member_type_id,
          name: this.form.member_type_name,
          capital: this.form.price
        }
      }

      this.form.useDayOfWeek = JSON.parse('[' + this.form.useDayOfWeek + ']')
      if (!this.form.date_check_rules) {
        this.form.date_check_rules = []
      } else if (typeof this.form.date_check_rules === 'string') {
        this.form.date_check_rules = JSON.parse(this.form.date_check_rules)
      }
      // 新建和编辑的时候 传scenic_ids 编辑回显时 通过combined_time字段重新组装成scenic_ids的结构
      // 使multiplesingleScenicList响应式 确保数据变=>视图变
      Vue.set(this.form, 'multiplesingleScenicList', [])
      this.form.singleScenicList.forEach(v => {
        if (v.combined_time) return this.form.multiplesingleScenicList.push(v) // 带combined_time 全放到multiplesingleScenicList
      })
      this.form.singleScenicList = this.form.singleScenicList.filter(v => !v.combined_time) // 不带combined_time 全放到singleScenicList 不用再操作
      let containerList = this.form.multiplesingleScenicList
      let containerListCopy = containerList
      this.form.multiplesingleScenicList = []
      for (var i = 0; i < containerList.length; i++) {
        const tempArr = containerListCopy.filter(v => v.combined_time === containerList[i].combined_time)
        // 同一combined_time的组装至rowTemp中 再放进multiplesingleScenicList里
        let rowTemp = {
          scenic_ids: tempArr.map(v => v.scenicId),
          checkLimitTimes: containerList[i].checkLimitTimes,
          check_scenic_limit_times_arr: tempArr.map(v => v.check_scenic_limit_times) || Array(tempArr.length).fill(-1)
        }
        tempArr.length && this.form.multiplesingleScenicList.push(rowTemp)
        // 放完后 把备份数组中 该combined_time的数据剔除 防止重复
        containerListCopy = containerListCopy.filter(v => v.combined_time !== containerList[i].combined_time)
      }
    }
  }
}
</script>
<style scoped lang="scss">
.tableBox{
    width:900px;
    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>
