<template>
  <!-- width="60%" -->
  <a-modal
    :visible="value"
    :title="editType?'复制票种':'编辑票种'"
    @ok="handleOk"
    width="70%"
    @cancel="handleCancel"
  >
    <a-spin :spinning="loading">
      <div>
        <a-form
          :form="form"
          v-if="formData"
        >
          <div class="block-title">
            绑定景点和渠道
          </div>
          <a-form-item
            label="已绑定景点"
            v-bind="formItemLayout2"
            style="width:100%"
          >
            <a-select
              mode="multiple"
              v-model="bindScenic"
              show-search
              :filter-option="filterOption"
            >
              <a-select-option
                v-for="scenic in scenicList"
                :key="scenic.id"
                :value="scenic.id"
              >
                {{ scenic.name }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
            label="已绑定渠道"
            v-bind="formItemLayout2"
            style="width:100%"
          >
            <a-select
              mode="multiple"
              v-model="bindChannel"
              show-search
              :filter-option="filterOption"
            >
              <a-select-option
                v-for="channel in salesChannel"
                :key="channel.id"
                :value="channel.id"
              >
                {{ channel.description }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <template v-if="bindScenic && bindChannel && bindScenic.length && bindChannel.length&&!['YINXIANGMAZU'].includes(project_name)">
            <div class="block-title">
              票种绑定
            </div>

            <!--
            <a-form-item
              label="是否绑定其他票种"
              v-bind="formItemLayout"
            >
              <a-switch
                checked-children="是"
                un-checked-children="否"
                @change="formData.is_bind_ticket_type=$event"
                v-decorator="[
                  'is_bind_ticket_type',
                  {
                    valuePropName: 'checked',
                    initialValue:(formData.is_bind_ticket_type===1)
                  }
                ]"
              />
            </a-form-item>
             -->

            <a-form-item
              label="是否绑定其他票种"
              v-bind="formItemLayout"
            >
              <a-select
                v-model="formData.is_bind_ticket_type"
                @change="formData.is_bind_ticket_type=$event"
              >
                <a-select-option
                  :key="0"
                  :value="0"
                >
                  否
                </a-select-option>
                <a-select-option
                  :key="1"
                  :value="1"
                >
                  是（绑定但不自动匹配）
                </a-select-option>
                <a-select-option
                  :key="2"
                  :value="2"
                >
                  是（绑定并自动匹配）
                </a-select-option>
              </a-select>
            </a-form-item>

            <!-- v-decorator="[
                'match_type',
                {
                  rules: [{ required: formData.is_bind_ticket_type === 2, message: '请选择绑定类型' }]
                }
              ]" -->
            <!-- match_type枚举值：ID_CARD_AGE根据身份证年龄，ID_CARD_DISTRICT根据身份证地区 -->
            <a-form-item
              label="匹配类型"
              v-bind="formItemLayout"
              v-if="formData.is_bind_ticket_type === 2"
            >
              <a-select
                v-model="formData.match_type"
              >
                <a-select-option
                  :key="0"
                  value="ID_CARD_AGE"
                >
                  根据身份证年龄
                </a-select-option>
                <a-select-option
                  :key="1"
                  value="ID_CARD_DISTRICT"
                >
                  根据身份证地区
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item
              label="主票"
              v-bind="formItemLayout"
            >
              {{ formData.name }}
            </a-form-item>

            <a-form-item
              label="选择绑定票"
              v-bind="formItemLayout2"
              v-if="formData.is_bind_ticket_type"
              style="width:100%"
            >
              <a-select
                mode="multiple"
                show-search
                v-model="bindTicketData"
              >
                <a-select-option
                  v-for="item in ticketListbindOptions"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </template>

          <!-- https://1x.antdv.com/components/form-cn#components-form-demo-dynamic-form-item 动态增减表单项 -->
          <template v-if="formData.is_bind_ticket_type">
            <div
              v-if="formData.ticketTypeBindInfoList"
              :key="index"
              v-for="(domain, index) in formData.ticketTypeBindInfoList">

              <!-- 子字段 domain.main_ticket_type_id -->
              <!-- 子字段 domain.main_ticket_type_num -->
              <a-form-item
                label="主票数量"
                v-bind="formItemLayout"
                style="width:22%"
              >
                <a-input-number v-model="domain.main_ticket_type_num" :min="1" :bordered="false" size="small" />
              </a-form-item>

              <!-- 子字段 domain.bind_ticket_type_id -->
              <a-form-item
                label="从票"
                v-bind="formItemLayout"
                style="width:22%"
              >
                {{ ticketListbindOptions && ticketListbindOptions.find(el => el.id === domain.bind_ticket_type_id)?.name }}
              </a-form-item>

              <!-- 子字段 domain.bind_ticket_type_num -->
              <a-form-item
                label="从票数量"
                style="width:22%"
                v-bind="formItemLayout"
              >
                <a-input-number v-model="domain.bind_ticket_type_num" :min="0" size="small"/>
              </a-form-item>

              <!-- 子字段 domain.relation-->
              <a-form-item
                label="关系"
                style="width:22%"
                v-bind="formItemLayout"
              >
                <a-select
                  v-model="domain.relation"
                >
                  <a-select-option key="0" :value="0">
                    等于
                  </a-select-option>
                  <a-select-option key="1" :value="1">
                    大于等于
                  </a-select-option>
                </a-select>
              </a-form-item>

              <!-- 子字段 domain.is_match_default -->
              <a-form-item
                label="默认"
                style="width:8%;min-width: 100px"
                v-bind="formItemLayout"
                v-if="formData.is_bind_ticket_type && formData.is_bind_ticket_type === 2"
              >
                <a-select
                  v-model="domain.is_match_default"
                >
                  <a-select-option key="0" :value="0">
                    否
                  </a-select-option>
                  <a-select-option key="1" :value="1">
                    是
                  </a-select-option>
                </a-select>
              </a-form-item>

            </div>
          </template>

          <div class="block-title">
            基础信息
          </div>
          <a-form-item
            label="票种名称"
            v-bind="formItemLayout"
          >
            <a-input
              v-decorator="[
                'name',
                {
                  initialValue:formData.name,
                  rules: [{ required: true, message: '请输入' }]
                }
              ]"
            ></a-input>
          </a-form-item>

          <a-form-item
            label="票种分类"
            v-bind="formItemLayout"
          >
            <a-select
              style="width: 100%"
              v-decorator="[
                'category',
                {
                  rules: [{ required: true, message: '请选择' }],
                  initialValue:formData.category.id
                }
              ]"
            >
              <a-select-option :value="0">
                暂无
              </a-select-option>
              <a-select-option
                v-for="(i,index) in ticketTypeList"
                :value="i.id"
                :key="index"
              >
                {{ i.name }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
            label="显示二维码"
            @change="formData.show_qrcode=$event"
            v-bind="formItemLayout"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              v-decorator="[
                'show_qrcode',
                {
                  valuePropName: 'checked',
                  initialValue:(formData.show_qrcode===1)
                }
              ]"
            />
          </a-form-item>

          <a-form-item
            label="原价"
            v-bind="formItemLayout"
          >
            <a-input-number
              :step="0.01"
              :precision="2"
              :min="0"
              :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
              v-decorator="[
                'price_original',
                {
                  initialValue:formData.price_original
                }
              ]"
            />（仅供显示）
          </a-form-item>

          <a-form-item
            label="价格"
            v-bind="formItemLayout"
          >
            <a-input-number
              :step="0.01"
              :precision="2"
              :min="0"
              :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
              v-decorator="[
                'price',
                {
                  initialValue:formData.price,
                  rules: [{ required: true, message: '请选择' }]
                }
              ]"
            />
          </a-form-item>

          <a-form-item
            label="价格码"
            v-bind="formItemLayout"
          >
            <a-select
              style="width: 100%"
              disabled
              v-decorator="[
                'ticket_product_id',
                {
                  initialValue:formData.ticket_product_id,
                  rules: [{ required: true, message: '请选择' }]
                }
              ]"
            >
              <a-select-option
                v-for="(i,index) in product"
                :value="i.ticket_product_id"
                :key="index"
              >
                {{ i.ticket_product_id }} - {{ i.description }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
            label="购买人实名认证"
            v-bind="formItemLayout"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              v-decorator="[
                'need_realname',
                {
                  valuePropName: 'checked',
                  initialValue:(formData.need_realname===1)
                }
              ]"
            />
          </a-form-item>
          <a-form-item
            v-if="['demo', 'YINXIANGMAZU'].includes(project)"
            label="是否为销售票"
            v-bind="formItemLayout"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              @change="formData.is_sales_ticket=$event"
              v-decorator="[
                'is_sales_ticket',
                {
                  valuePropName: 'checked',
                  initialValue:(formData.is_sales_ticket===1)
                }
              ]"
            />
          </a-form-item>
          <a-form-item
            label="游客实名认证"
            v-bind="formItemLayout"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              v-decorator="[
                'player_need_realname',
                {
                  valuePropName: 'checked',
                  initialValue:(formData.player_need_realname===1)
                }
              ]"
            />
          </a-form-item>

          <a-form-item
            label="是否是兑换票"
            v-bind="formItemLayout"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              @change="formData.is_convertible=$event"
              v-decorator="[
                'is_convertible',
                {
                  valuePropName: 'checked',
                  initialValue:(formData.is_convertible===1)
                }
              ]"
            />
          </a-form-item>

          <a-form-item
            label="佣金"
            v-bind="formItemLayout"
          >
            <a-input-number
              :step="0.01"
              :precision="2"
              :min="0"
              :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
              v-decorator="[
                'commission',
                {
                  initialValue:formData.commission,
                  rules: [{ required: true, message: '输入' }]
                }
              ]"
            />
          </a-form-item>

          <a-form-item
            label="购票限制策略"
            v-bind="formItemLayout"
          >
            <a-select
              v-decorator="[
                'purchase_separate',
                {
                  initialValue:formData.purchase_separate
                }
              ]">
              <a-select-option key="NONE">无</a-select-option>
              <a-select-option key="OTHER">只可与其他票种一起购买</a-select-option>
              <a-select-option key="SAME_DATE">只可与其他票种同日期一起购买</a-select-option>
              <a-select-option key="SAME_DATE_AND_BATCH">只可与其他票种同日期同场次一起购买</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
            label="票种是否显示"
            v-bind="formItemLayout"
          >
            <a-select
              v-model="formData.is_mobile_show"
              @change="formData.is_mobile_show=$event"
            >
              <a-select-option
                :key="0"
                :value="0"
              >
                否
              </a-select-option>
              <a-select-option
                :key="1"
                :value="1"
              >
                是
              </a-select-option>
            </a-select>
          </a-form-item>

          <div class="block-title">
            销售限制
          </div>
          <a-form-item
            label="售票日期范围"
            v-bind="formItemLayout"
          >
            <a-range-picker
              v-decorator="[
                'sellDate',
                {
                  initialValue:[moment(formData.sell_startdate),moment(formData.sell_enddate)],
                  rules: [{ required: true, message: '请选择销售日期' }]
                }
              ]"
            />
          </a-form-item>
          <a-form-item
            label="使用日期范围"
            v-bind="formItemLayout"
          >
            <a-range-picker
              v-decorator="[
                'useDate',
                {
                  initialValue:[moment(formData.use_startdate),moment(formData.use_enddate)],
                  rules: [{ required: true, message: '请选择使用日期' }]
                }
              ]"
            />
          </a-form-item>

          <a-form-item
            label="可售开始时间"
            v-bind="formItemLayout"
          >
            <a-time-picker
              v-decorator="[
                `sale_time_start`,
                {
                  initialValue: moment(formData.sale_time_start,'HH:mm:ss'),
                  rules: [{ required: true, message: '请选择时间' }]
                }
              ]"
            />
          </a-form-item>

          <a-form-item
            label="可售截止时间"
            v-bind="formItemLayout"
          >
            <a-time-picker
              v-decorator="[
                `sale_time_end`,
                {
                  initialValue: moment(formData.sale_time_end,'HH:mm:ss'),
                  rules: [{ required: true, message: '请选择时间' }]
                }
              ]"
            />
          </a-form-item>

          <a-form-item
            label="最小起订数"
            v-bind="formItemLayout"
          >
            <a-input-number
              :min="0"
              v-decorator="[
                'book_min',
                {
                  initialValue:formData.book_min,
                  rules: [{ required: true, message: '请输入' }]
                }
              ]"
            >
            </a-input-number>
          </a-form-item>

          <a-form-item
            label="最大限订数"
            v-bind="formItemLayout"
          >
            <a-input-number
              :min="0"
              v-decorator="[
                'book_max',
                {
                  initialValue:formData.book_max,
                  rules: [{ required: true, message: '请输入' }]
                }
              ]"
            >
            </a-input-number>
          </a-form-item>

          <a-form-item
            label="可使用天数"
            v-bind="formItemLayout"
          >
            <a-input-number
              :min="0"
              v-decorator="[
                'use_valid_days',
                {
                  initialValue:formData.use_valid_days,
                  rules: [{ required: true, message: '请输入' }]
                }
              ]"
            >
            </a-input-number>
          </a-form-item>

          <a-alert type="warning">
            <div slot="message"><b class="red">【白名单】</b>：以下列数字开头的<b class="red">游客身份证</b>才可购买。<b class="red">打开游客实名认证,才可生效</b></div>
          </a-alert>
          <a-form-item
            style="width:100%"
            label="身份证号白名单"
            v-bind="formItemLayout2"
          >
            <a-tag
              :key="tag"
              v-for="tag in limitIdentities"
              closable
              :disable-transitions="false"
              @close="handleClose(tag,'limitIdentities')">
              {{ tag }}
            </a-tag>
            <a-input
              type="text"
              class="input-new-tag"
              placeholder="2~6位数字"
              v-if="limitIdentities.inputVisible"
              v-model="limitIdentities.inputValue"
              ref="limitIdentitiesInput"
              size="small"
              :min-length="2"
              :max-length="6"
              @keyup.enter.native="handleInputConfirm('limitIdentities')"
              @blur="handleInputConfirm('limitIdentities')"
            ></a-input>
            <a-button v-else type="primary" size="small" @click="showInput('limitIdentities')">添加</a-button>
          </a-form-item>

          <a-alert type="warning">
            <div slot="message"><b class="red">【黑名单】</b>：以下列数字开头的<b class="red">游客身份证</b>不可购买。<b class="red">打开游客实名认证,才可生效</b></div>
          </a-alert>
          <a-form-item
            style="width:100%"
            label="身份证号黑名单"
            v-bind="formItemLayout2"
          >
            <a-tag
              :key="tag"
              v-for="tag in blacklistIdentities"
              closable
              :disable-transitions="false"
              @close="handleClose(tag,'blacklistIdentities')">
              {{ tag }}
            </a-tag>
            <a-input
              type="text"
              class="input-new-tag"
              placeholder="2~6位数字"
              v-if="blacklistIdentities.inputVisible"
              v-model="blacklistIdentities.inputValue"
              ref="blacklistIdentitiesInput"
              size="small"
              :min-length="2"
              :max-length="6"
              @keyup.enter.native="handleInputConfirm('blacklistIdentities')"
              @blur="handleInputConfirm('blacklistIdentities')"
            ></a-input>
            <a-button v-else type="primary" size="small" @click="showInput('blacklistIdentities')">添加</a-button>
          </a-form-item>
          <!-- <a-alert type="warning">
            <div slot="message"><b class="red">【灰名单】</b>：以下列数字开头的<b class="red">游客身份证</b>购买时会弹出提示，不影响正常购票。<b class="red">打开游客实名认证,才可生效</b></div>
          </a-alert>
          <a-form-item
            style="width:100%"
            label="身份证号灰名单提示"
            v-bind="formItemLayout2"
          >
            <GrayList v-model="greylistIdentities" :greyList="greyList"></GrayList>
          </a-form-item> -->
          <div class="block-title">
            销售数量设置
          </div>
          <a-form-item
            label="是否限制销售数量"
            v-bind="formItemLayout2"
            style="width:100%"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              @change="formData.is_restricted_sales=$event"
              v-decorator="[
                'is_restricted_sales',
                {
                  valuePropName: 'checked',
                  initialValue:(formData.is_restricted_sales===1)
                }
              ]"
            />
          </a-form-item>

          <a-form-item
            v-if="formData.is_restricted_sales"
            label="每天可销售数量"
            v-bind="formItemLayout"
          >
            <a-input-number
              :min="0"
              v-decorator="[
                'sales_volume',
                {
                  initialValue:formData.sales_volume,
                  rules: [{ required: true, message: '请输入' }]
                }
              ]"
            >
            </a-input-number> （不限制填 0）
          </a-form-item>

          <a-form-item
            v-if="formData.is_restricted_sales"
            label="总库存"
            v-bind="formItemLayout"
          >
            <a-input-number
              :min="0"
              v-decorator="[
                'total_sales_limit',
                {
                  initialValue:formData.total_sales_limit,
                  rules: [{ required: true, message: '请输入' }]
                }
              ]"
            >
            </a-input-number> （不限制填 0）
          </a-form-item>
          <a-form-item
            label="是否加入限购"
            style="width:100%"
            v-bind="formItemLayout2"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              @change="formData.is_order_limit=$event"
              v-decorator="[
                'is_order_limit',
                {
                  valuePropName: 'checked',
                  initialValue:(formData.is_order_limit===1)
                }
              ]"
            />
          </a-form-item>
          <a-form-item
            label="选择限购组"
            v-if="formData.is_order_limit"
            v-bind="formItemLayout"
          >
            <a-select
              v-decorator="[
                'order_limit_group',
                {
                  initialValue:formData.order_limit_group || null,
                  rules: [{ required: true, message: '请选择限购组' }]
                }
              ]"
            >
              <a-select-option
                v-for="(i,index) in limitGroupList"
                :value="i.id"
                :key="index"
              >
                {{ i.name }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-alert type="warning">
            <div slot="message"><b class="red">【灰名单】</b>：购买时会弹出提示，不影响正常购票。<b class="red">打开游客实名认证,才可生效</b></div>
          </a-alert>
          <a-form-item
            label="是否开启灰名单提示"
            style="width:100%"
            v-bind="formItemLayout2"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              @change="formData.is_grey_list=$event"
              v-decorator="[
                'is_grey_list',
                {
                  valuePropName: 'checked',
                  initialValue:formData.is_grey_list
                }
              ]"
            />
          </a-form-item>
          <a-form-item
            label="选择灰名单模板"
            v-if="formData.is_grey_list"
            v-bind="formItemLayout"
          >
            <a-input
              v-show="false"
              v-decorator="[
                'grey_list_id',
                {
                  initialValue:formData.grey_list_id,
                  rules: [{ required: true, message: '请选择灰名单模板' }]
                }
              ]"
            ></a-input>

            <GreySelector ref="editor" v-model="formData.grey_list_id"></GreySelector>
          </a-form-item>

          <div class="block-title">
            年龄设置
          </div>
          <a-form-item
            label="年龄限制"
            v-bind="formItemLayout2"
            style="width:100%"
          >
            <a-button
              class="addBtn"
              type="primary"
              @click="addAge"
              size="small"
            >添加</a-button>
            （需开启游客实名才能生效）
            <br>
            <a-table
              :data-source="formData.age_limits"
              :columns="columns"
              :pagination="false"
              v-decorator="[
                'age_limits',
                {
                  initialValue:formData.age_limits,
                }
              ]">
              <span slot="ageStart" slot-scope="text, record">
                <a-input-number v-model="record.ageStart" :min="0" :max="120" />
              </span>
              <span slot="ageEnd" slot-scope="text, record">
                <a-input-number v-model="record.ageEnd" :min="0" :max="120" />
              </span>
              <span slot="action" slot-scope="text, record,index">
                <a-button size="small" @click="delAge(index)" type="danger">删除</a-button>
              </span>
            </a-table>
          </a-form-item>
          <div class="block-title">
            票种详情介绍 <span style="font-size:13px;color:red"> （上传图片后，请将图片宽高设置为100%）</span>
          </div>
          <a-form-item
            label="票种标签"
            v-bind="formItemLayout2"
            style="width:100%"
          >
            <a-select
              mode="multiple"
              style="width: 100%"
              v-decorator="[
                'tags',
                {
                  initialValue:formData.tags.map(i=>i.id)
                }
              ]"
            >
              <a-select-option
                v-for="(i,index) in tags"
                :value="i.id"
                :key="index"
              >
                {{ i.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="购票须知"
            v-bind="formItemLayout2"
            style="width:100%"
          >
            <a-input
              v-show="false"
              v-decorator="[
                'purchase_notice',
                {
                  initialValue:formData.purchase_notice,
                }
              ]"
            ></a-input>

            <Editor ref="editor" v-model="formData.purchase_notice"></Editor>
          </a-form-item>
          <a-form-item
            label="使用须知"
            v-bind="formItemLayout2"
            style="width:100%"
          >
            <a-input
              v-show="false"
              v-decorator="[
                'description',
                {
                  initialValue:formData.description,
                }
              ]"
            ></a-input>

            <Editor ref="editor" v-model="formData.description"></Editor>

          </a-form-item>
          <a-form-item
            label="退改须知"
            v-bind="formItemLayout2"
            style="width:100%"
          >
            <a-input
              v-show="false"
              v-decorator="[
                'withdrawal_notice',
                {
                  initialValue:formData.withdrawal_notice,
                }
              ]"
            ></a-input>

            <Editor ref="editor" v-model="formData.withdrawal_notice"></Editor>
          </a-form-item>
          <a-form-item
            label="其他须知"
            v-bind="formItemLayout2"
            style="width:100%"
          >
            <a-input
              v-show="false"
              v-decorator="[
                'other_notice',
                {
                  initialValue:formData.other_notice,
                }
              ]"
            ></a-input>

            <Editor ref="editor" v-model="formData.other_notice"></Editor>
          </a-form-item>

          <div class="block-title">
            购票协议
          </div>
          <a-form-item
            label="是否显示票种购票协议"
            v-bind="formItemLayout"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              @change="formData.is_use_purchase_protocol=$event"
              v-decorator="[
                'is_use_purchase_protocol',
                {
                  valuePropName: 'checked',
                  initialValue:(formData.is_use_purchase_protocol===1)
                }
              ]"
            />
          </a-form-item>
          <a-form-item
            label="购票协议"
            v-bind="formItemLayout2"
            style="width:100%"
          >
            <a-input
              v-show="false"
              v-decorator="[
                'purchase_protocol',
                {
                  initialValue:formData.purchase_protocol,
                }
              ]"
            ></a-input>

            <Editor ref="editor" v-model="formData.purchase_protocol"></Editor>

          </a-form-item>
        </a-form>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { addTicketType, setTicketTypeById, getTicketTypeById, getTicketScenic, setTicketScenic, getTicketChannel, setTicketChannel, getTicketTypeWithIds } from '@/api/ticketSetting/ticket'
import ticketMixin from './ticketMixin.js'
import Editor from '@/components/Editor/index.vue'
import GreySelector from '@/components/GreySelector'

const columns = [
  {
    title: '起始年龄',
    dataIndex: 'ageStart',
    key: 'ageStart',
    scopedSlots: { customRender: 'ageStart' }
  },
  {
    title: '截至年龄',
    dataIndex: 'ageEnd',
    key: 'ageEnd',
    scopedSlots: { customRender: 'ageEnd' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    scopedSlots: { customRender: 'action' }
  }

]
export default {
  computed: {
    ticketTypeList () {
      return this.$store.state.app.ticketTypeList
    },
    limitGroupList () {
      return this.$store.state.app.limitGroupList
    },
    greyList () {
      return this.$store.state.app.greyList
    },
    greyListMap () {
      // 生成灰名单id对象
      const greyListMap = {}
      this.greyList.forEach(i => {
        greyListMap[i.id] = i
      })
      return greyListMap
    }
  },
  mixins: [ticketMixin],
  components: {
    Editor,
    GreySelector
  },
  props: {
    scenicList: {
      type: Array,
      default: () => []
    },
    salesChannel: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      project_name: localStorage.mgt_project,
      id: '',
      editType: '',
      columns,
      greyValue: undefined,
      greylistIdentities: [],
      loading: false,
      formData: null,
      bindScenic: [],
      bindChannel: [],
      ageLimits: [],
      limitIdentities: [],
      blacklistIdentities: [],
      ticketListbindOptions: [], // 绑定从票种的选项
      bindTicketData: [] // 绑定从票种选择v-model
    }
  },
  methods: {
    async show (id, type) {
      this.id = id
      console.log('%c [ type ]-1076', 'font-size:13px; background:pink; color:#bf2c9f;', type)
      this.editType = type || ''
      // if (!val) return
      this.loading = true
      await getTicketScenic(id).then(res => {
        const scenicList = res.extraInfo.list.filter(s => {
          return this.scenicList.find(i => {
            return i.id === s.id
          })
        })
        this.bindScenic = scenicList.map(i => i.id)
      })

      await getTicketChannel(id).then(res => {
        this.bindChannel = res.extraInfo.list.map(i => i.id)
      })

      getTicketTypeById(id).then(res => {
        this.formData = res.extraInfo
        this.$set(this.formData, 'match_type', this.formData.match_type ? this.formData.match_type : '')
        this.$set(this.formData, 'is_bind_ticket_type', this.formData.is_bind_ticket_type ? this.formData.is_bind_ticket_type : 0)
        // 手动设置formData的ticketTypeBindInfoList字段
        this.$set(this.formData, 'ticketTypeBindInfoList', this.formData.ticketTypeBindInfoList || [])
        // 手动设置bindTicketData
        if (this.formData.ticketTypeBindInfoList && this.formData.ticketTypeBindInfoList.length) {
          // 从票种数据里设置多选里的从票种们
          this.bindTicketData = this.formData.ticketTypeBindInfoList.map(element => element.bind_ticket_type_id)
        }
        this.limitIdentities = this.formData.limit_identities || []
        this.blacklistIdentities = this.formData.blacklist_identities || []

        // this.ageLimits = this.formData.age_limits || []
        // 设置默认策略
        this.formData.refund_strategy = this.formData.refund_strategy || 'FIXED'
        this.formData.grey_list_id = this.formData.grey_list_id || undefined
        this.formData.is_grey_list = !!this.formData.is_grey_list
        this.loading = false
        this.imageList = this.formData.pictures.map((i, index) => {
          return {
            uid: index + '',
            name: '图' + index,
            url: i.url,
            thumbUrl: i.url,
            size: i.size
          }
        })
        this.$nextTick(() => {
          this.form.getFieldDecorator('is_refund', { initialValue: !!this.formData.is_refund })
          this.form.getFieldDecorator('is_book_today', { initialValue: !!this.formData.is_book_today })
          this.form.getFieldDecorator('show_qrcode', { initialValue: !!this.formData.show_qrcode })
          this.form.getFieldDecorator('is_restricted_sales', { initialValue: !!this.formData.is_restricted_sales })
          this.form.getFieldDecorator('is_sales_ticket', { initialValue: !!this.formData.is_sales_ticket })
        })
      })
    },
    // 获取绑定从票种的选项
    async fetchTicketListbindOptions () {
      const params = {
        pageNum: 1,
        pageSize: 999,
        type: 'BATCH',
        is_reservation: this.formData.is_reservation, // 是否支持门票预约
        channel_ids: this.bindChannel,
        scenic_ids: this.bindScenic
      }
      const res = await getTicketTypeWithIds(params)
      if (+res.resCode === 200) {
        this.ticketListbindOptions = res.extraInfo.list
      }
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    addAge () {
      this.formData.age_limits.push({
        ageStart: '',
        ageEnd: ''
      })
    },
    delAge (index) {
      this.formData.age_limits.splice(index, 1)
    },
    getFileList (obj) {
      if (obj && obj.fileList) {
        return obj.fileList.map(item => {
          const info = item.response
          if (info) {
            return {
              size: info.size - 0,
              url: info.link
            }
          } else {
            return {
              size: item.size,
              url: item.url
            }
          }
        })
      }

      if (Array.isArray(obj)) {
        return obj.map(item => {
          return {
            size: item.size,
            url: item.url
          }
        })
      }

      return []
    },
    handleOk (e) {
      e.preventDefault()
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (values.book_max < values.book_min) {
            this.$message.error('最小起订数不能大于最大限订数')
            return
          }
          // 赋值values的ticketTypeBindInfoList
          values.ticketTypeBindInfoList = this.formData.ticketTypeBindInfoList
          values.match_type = this.formData.match_type
          values.is_bind_ticket_type = this.formData.is_bind_ticket_type
          const params = this.formatParams(values)
          // 设置is_bind_ticket_type和match_type
          params.is_bind_ticket_type = this.formData.is_bind_ticket_type
          params.is_mobile_show = this.formData.is_mobile_show
          if (+params.is_bind_ticket_type === 2) {
            params.match_type = this.formData.match_type
          }
          // 校验

          if (+params.is_bind_ticket_type === 2) {
            // 匹配类型校验
            if (!params.match_type || !params.match_type?.length) {
              this.$message.error('请输入匹配类型')
              return
            }

            // is_match_default
            if (!this.checkMatchDefault(params.ticketTypeBindInfoList)) {
              this.$message.error('请选择唯一的默认绑定票种')
              return
            }
          }
          params.pictures = this.getFileList(values.pictures)
          params.limit_identities = this.limitIdentities
          params.age_limits = this.formData.age_limits
          params.is_sales_ticket = this.formData.is_sales_ticket ? 1 : 0
          params.blacklist_identities = this.blacklistIdentities

          params.order_limit_group = params.order_limit_group || 0
          if (this.editType === '') {
            setTicketTypeById(this.formData.id, params).then(res => {
              this.$message.success('修改成功')
              this.handleScenicChange()
              this.handleChannelChange()

              this.$emit('update')

              this.handleCancel()
            })
          } if (this.editType === 'copy') {
            addTicketType(params).then(res => {
              this.$message.success('添加成功')
              this.id = res.extraInfo
              this.handleScenicChange()
              this.handleChannelChange()
              this.handleCancel()
              setTimeout(() => {
                this.$emit('update')
              }, 500)
            })
          }
        }
      })
    },
    checkMatchDefault (list) {
      const matchDefaultCount = list.filter(item => +item.is_match_default === 1)?.length
      return matchDefaultCount === 1
    },
    handleScenicChange () {
      const params = {
        scenics: this.bindScenic.length > 0 ? this.bindScenic : null
      }
      setTicketScenic(this.id, params).then(res => {
        this.$message.success('绑定景点成功')
      })
    },
    handleChannelChange () {
      const params = {
        channels: this.bindChannel.length > 0 ? this.bindChannel : null
      }
      setTicketChannel(this.id, params).then(res => {
        this.$message.success('绑定渠道成功')
      })
    },

    handleClose (tag, prop) {
      this[prop].splice(this[prop].indexOf(tag), 1)
    },

    showInput (prop) {
      this.$set(this[prop], 'inputVisible', true)

      this.$nextTick(_ => {
        this.$refs[`${prop}Input`].$refs.input.focus()
      })
    },

    handleInputConfirm (prop) {
      const inputValue = this[prop].inputValue
      if (inputValue) {
        if (this[prop].indexOf(inputValue) < 0) {
          this[prop].push(inputValue)
        } else {
          this.$message.error('已重复')
        }
      }
      this[prop].inputVisible = false
      this[prop].inputValue = ''
    }
  },
  watch: {
    bindTicketData (val) {
      // 绑定票种改变时，进行push或splice操作
      // 更新ticketTypeBindInfoList数组中的元素
      this.formData.ticketTypeBindInfoList = this.formData.ticketTypeBindInfoList.filter(element => val.includes(element.bind_ticket_type_id))

      val.forEach((id) => {
      // 检查是否已存在相同bind_ticket_type_id的元素
        const existingElement = this.formData.ticketTypeBindInfoList.find(element => element.bind_ticket_type_id === id)

        // 如果不存在相同bind_ticket_type_id的元素，则新增一个元素
        if (!existingElement) {
          const newElement = {
            bind_ticket_type_id: id, // 从票种的id和下拉多选保持一致
            bind_ticket_type_num: 0, // 默认从票种绑定0张，避免误操作
            main_ticket_type_id: this.id, // 主票种id
            main_ticket_type_num: 1, // 主票至少一个
            is_match_default: 0, // 是否是绑定的默认票种，bind_ticket_type_id为2时才有效
            relation: 0
          }
          this.formData.ticketTypeBindInfoList.push(newElement)
        }
      })
    },
    async 'formData.is_bind_ticket_type' (val) {
      const isEnableBind = !!val // 是否需要绑定票
      console.log('是否绑定票', isEnableBind)
      // 若需要绑定票，请求从票种列表
      if (isEnableBind) {
        await this.fetchTicketListbindOptions()
      }
    }
    // async value (val) {
    //   if (!val) return
    //   this.loading = true
    //   await getTicketScenic(this.id).then(res => {
    //     const scenicList = res.extraInfo.list.filter(s => {
    //       return this.scenicList.find(i => {
    //         return i.id === s.id
    //       })
    //     })
    //     this.bindScenic = scenicList.map(i => i.id)
    //   })

    //   await getTicketChannel(this.id).then(res => {
    //     this.bindChannel = res.extraInfo.list.map(i => i.id)
    //   })

    //   getTicketTypeById(this.id).then(res => {
    //     this.formData = res.extraInfo
    //     this.$set(this.formData, 'match_type', this.formData.match_type ? this.formData.match_type : '')
    //     this.$set(this.formData, 'is_bind_ticket_type', this.formData.is_bind_ticket_type ? this.formData.is_bind_ticket_type : 0)
    //     // 手动设置formData的ticketTypeBindInfoList字段
    //     this.$set(this.formData, 'ticketTypeBindInfoList', this.formData.ticketTypeBindInfoList || [])
    //     // 手动设置bindTicketData
    //     if (this.formData.ticketTypeBindInfoList && this.formData.ticketTypeBindInfoList.length) {
    //       // 从票种数据里设置多选里的从票种们
    //       this.bindTicketData = this.formData.ticketTypeBindInfoList.map(element => element.bind_ticket_type_id)
    //     }
    //     this.limitIdentities = this.formData.limit_identities || []
    //     this.blacklistIdentities = this.formData.blacklist_identities || []

    //     this.ageLimits = this.formData.age_limits || []
    //     // 设置默认策略
    //     this.formData.refund_strategy = this.formData.refund_strategy || 'FIXED'
    //     this.formData.grey_list_id = this.formData.grey_list_id || undefined
    //     this.formData.is_grey_list = !!this.formData.is_grey_list
    //     this.loading = false
    //     this.imageList = this.formData.pictures.map((i, index) => {
    //       return {
    //         uid: index + '',
    //         name: '图' + index,
    //         url: i.url,
    //         thumbUrl: i.url,
    //         size: i.size
    //       }
    //     })
    //     this.$nextTick(() => {
    //       this.form.getFieldDecorator('is_refund', { initialValue: !!this.formData.is_refund })
    //       this.form.getFieldDecorator('is_book_today', { initialValue: !!this.formData.is_book_today })
    //       this.form.getFieldDecorator('show_qrcode', { initialValue: !!this.formData.show_qrcode })
    //       this.form.getFieldDecorator('is_restricted_sales', { initialValue: !!this.formData.is_restricted_sales })
    //     })
    //   })
    // }
  }
}
</script>

<style scoped>
.ant-form-item{
  width: 50%; display: inline-block;
}
</style>
