<template>
  <a-modal
    :visible="value"
    title="新增票种"
    @ok="handleOk"
    width="60%"
    @cancel="handleCancel"
  >
    <a-alert
      banner
      type="error"
      v-if="product.length===0"
    >
      <template slot="message">
        暂无可用价格码，请先至
        <router-link to="/ticketSetting/priceCode">
          价格码管理<b>（点此跳转）</b>
        </router-link>，添加或激活价格码，否则无法创建新票种
      </template>
    </a-alert>
    <a-alert
      banner
      v-else
      type="warning"
      message="请仔细选择价格码，票种绑定价格码后，不可再次编辑"
    >
    </a-alert>

    <a-form :form="form">
      <div class="block-title">
        景点和渠道
      </div>
      <a-form-item
        label="绑定景点"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-select
          mode="multiple"
          show-search
          :filter-option="filterOption"
          v-model="bindScenic"
        >
          <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>

      <div class="block-title">
        基础信息
      </div>
      <a-form-item
        label="票种名称"
        v-bind="formItemLayout"
      >
        <a-input
          v-decorator="[
            'name',
            {
              rules: [{ required: true, message: '请输入' }]
            }
          ]"
        ></a-input>
      </a-form-item>
      <a-form-item
        label="价格"
        v-bind="formItemLayout"
      >
        <a-input-number
          disabled
          :precision="2"
          :min="0"
          :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
          :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
          v-decorator="[
            'price',
            {
              initialValue:0
            }
          ]"
        />
      </a-form-item>

      <a-form-item
        label="价格码"
        v-bind="formItemLayout"
      >
        <a-select
          style="width: 100%"
          v-decorator="[
            '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="[
            'player_need_realname',
            {
              valuePropName: 'checked',
              initialValue:(formData.player_need_realname===1)
            }
          ]"
        />
      </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>
      <div class="block-title">
        预约设置
      </div>
      <a-form-item
        label="是否支持门票预约"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-switch
          checked-children="是"
          un-checked-children="否"
          disabled
          @change="formData.is_reservation=$event"
          v-decorator="[
            'is_reservation',
            {
              valuePropName: 'checked',
              initialValue:(formData.is_reservation===1)
            }
          ]"
        />
      </a-form-item>
      <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="售票日期范围"
        v-bind="formItemLayout"
      >
        <a-range-picker
          v-decorator="[
            'sellDate',
            {
              initialValue:[moment(),moment().add('year',10)],
              rules: [{ required: true, message: '请选择销售日期' }]
            }
          ]"
        />
      </a-form-item>
      <a-form-item
        label="使用日期范围"
        v-bind="formItemLayout"
      >
        <a-range-picker
          v-decorator="[
            'useDate',
            {
              initialValue:[moment(),moment().add('year',10)],
              rules: [{ required: true, message: '请选择使用日期' }]
            }
          ]"
        />
      </a-form-item>

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

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

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

      <a-form-item
        label="是否必填预约人手机号"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-switch
          checked-children="是"
          un-checked-children="否"
          @change="formData.is_write_reservation_phone=$event"
          v-decorator="[
            'is_write_reservation_phone',
            {
              valuePropName: 'checked',
              initialValue:(formData.is_write_reservation_phone===1)
            }
          ]"
        />
      </a-form-item>
      <a-form-item
        label="是否必填游客姓名"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-switch
          checked-children="是"
          un-checked-children="否"
          @change="formData.is_write_player_name=$event"
          v-decorator="[
            'is_write_player_name',
            {
              valuePropName: 'checked',
              initialValue:(formData.is_write_player_name===1)
            }
          ]"
        />
      </a-form-item>
      <a-form-item
        label="是否必填游客证件"
        v-bind="formItemLayout2"
        style="width:100%"
      >
        <a-switch
          checked-children="是"
          un-checked-children="否"
          @change="formData.is_write_player_identity=$event"
          v-decorator="[
            'is_write_player_identity',
            {
              valuePropName: 'checked',
              initialValue:(formData.is_write_player_identity===1)
            }
          ]"
        />
      </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-form>
  </a-modal>
</template>

<script>
import { addTicketType, setTicketScenic, setTicketChannel } from '@/api/ticketSetting/ticket'
import ticketMixin from './ticketMixin.js'
import Editor from '@/components/Editor/index.vue'
export default {
  mixins: [ticketMixin],
  data () {
    return {
      bindScenic: [],
      limitIdentities: [],
      blacklistIdentities: [],
      bindChannel: [],
      purchase_content: '',
      description_content: '',
      withdrawal_content: '',
      other_content: '',
      formData: {
        need_realname: 0,
        player_need_realname: 1,
        is_restricted_sales: 0,
        is_reservation: 1,
        is_write_player_identity: 1,
        is_write_player_name: 1,
        is_write_reservation_phone: 1,
        purchase_separate: 'NONE',
        refund_strategy: 'FIXED'
      }
    }
  },
  components: {
    Editor
  },
  props: {
    scenicList: {
      type: Array,
      default: () => []
    },
    salesChannel: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    ticketTypeList () {
      return this.$store.state.app.ticketTypeList
    }
  },
  methods: {
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    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('绑定渠道成功')
      })
    },
    handleOk (e) {
      e.preventDefault()
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (values.book_max < values.book_min) {
            this.$message.error('最小起订数不能大于最大限订数')
            return
          }
          const params = this.formatParams(values)
          params.pictures = values.pictures ? values.pictures.fileList.map(item => {
            const info = item.response
            return {
              size: info.size - 0,
              url: info.link
            }
          }) : []
          params.purchase_notice = this.purchase_content
          params.description = this.description_content
          params.limit_identities = this.limitIdentities
          params.blacklist_identities = this.blacklistIdentities
          params.withdrawal_notice = this.withdrawal_content
          params.other_notice = this.other_content
          addTicketType(params).then(res => {
            this.$message.success('添加成功')
            this.id = res.extraInfo
            this.handleScenicChange()
            this.handleChannelChange()

            this.$emit('update')

            this.handleCancel()
          })
        }
      })
    },
    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 = ''
    }
  }
}
</script>

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