<template>
  <div>
    <el-card>
      <template slot="header">
        <div
          class="card-title"
          v-if="currentTicket">
          <span>当前票种：<b>{{ currentTicket.name || '无' }}</b></span>

          <div>{{ form.playDateBegin | formatDate }} 票价：<span class="price"><b>{{ currentPrice }}</b> 元</span></div>
        </div>
        <span
          v-else
          style="color:red">请选择门票</span>
      </template>

      <el-form
        v-loading="loading"
        class="sale-form-wrap"
        ref="form"
        :model="form"
        :inline="true"
        label-width="100px">
        <el-form-item
          verify
          can-be-empty
          label="顾客姓名"
          prop="guestName">
          <el-input
            v-model="form.guestName"></el-input>
        </el-form-item>
        <el-form-item
          can-be-empty
          :verify="verifyPhone"
          label="顾客电话"
          prop="guestPhone">
          <el-input
            v-model="form.guestPhone"></el-input>
        </el-form-item>
        <el-form-item
          label="证件类型"
          prop="guestIdentifyType">
          <el-select
            :disabled="identify_lockCheckStyle"
            v-model="form.guestIdentifyType"
            placeholder="请选择">
            <el-option
              v-for="(item, idx) in papersType"
              :key="`id-${idx}`"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-checkbox
            style="margin-left:10px"
            v-model="identify_lockCheckStyle">
            锁定
          </el-checkbox>
        </el-form-item>
        <el-form-item
          key="id1"
          :verify="form.guestIdentifyType === 0 ? verifyId : ''"
          can-be-empty
          v-if="form.guestIdentifyType === 0 || form.guestIdentifyType === 'YONGJIUJULIU'"
          label="证件号码"
          prop="guestIdentify">
          <ReaderInput
            type="ID"
            @change="form.guestName = $event.Name,Certificate=$event"
            v-model="form.guestIdentify"></ReaderInput>
        </el-form-item>
        <el-form-item
          v-else
          key="id2"
          label="证件号码"
          prop="guestIdentify">
          <el-input v-model="form.guestIdentify"></el-input>
        </el-form-item>
        <el-form-item
          v-if="Certificate.Nation"
          label="国家"
        >
          {{ Certificate.Nation }}
        </el-form-item>
        <el-form-item
          v-if="Certificate.Sex"
          label="性别"
        >
          {{ Certificate.Sex }}
        </el-form-item>
        <el-form-item
          v-if="Certificate.ValidDate"
          label="有效截止日期"
        >
          {{ Certificate.ValidDate }}
        </el-form-item>
        <el-form-item
          v-if="currentTicket && currentTicket.isUseDateLimit"
          verify
          prop="playDateBegin"
          label="游玩日期">
          <el-date-picker
            :clearable="false"
            :editable="false"
            :picker-options="dateOption"
            v-model="form.playDateBegin"
            type="date"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          v-if="currentTicket && currentTicket.isUseDateLimit"
          label="结束日期">
          <el-input
            disabled
            v-model="playEndDate"
          ></el-input>
        </el-form-item>
        <el-form-item
          verify
          number
          label="购买数量"
          prop="count"
        >
          <el-input-number
            ref="ticketCount"
            name="ticket-count"
            v-model.number="form.count"
            :min="1"
            :max="10000"
            :precision="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="检票方式"
          prop="checkWay">
          <el-select
            v-model="form.checkWay"
            :disabled="retail_lockCheckStyle">
            <el-option
              v-for="item in checkWayList"
              :key="item.val"
              :value="item.val"
              :label="item.name"
            ></el-option>
          </el-select>
          <el-checkbox
            style="margin-left:10px"
            v-model="retail_lockCheckStyle">
            锁定
          </el-checkbox>
        </el-form-item>
        <!-- <el-form-item
          label="价格方案">
          <el-select
            v-model="currentPlan"
            v-if="pricePlan.length">
            <el-option
              v-for="item in pricePlan"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <!-- v-if="form.checkWay === 3 || form.checkWay === 4" -->
        <el-form-item
          label="游客信息"
        >
          <div
            v-if="currentTicket"
            class="input-space"
          >
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="showTouristList"
            >
              编辑查看
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <div class="btn-wrap">
        <el-button
          @click="resetForm"
          style="margin-right:20px">
          重置表单
        </el-button>
        <el-button
          type="primary"
          @click="addToOrder">
          加入订单
        </el-button>
      </div>
    </el-card>

    <!-- 游客列表 -->
    <TouristList
      :check-ticket-no="form.checkWay === 5"
      :check-face="form.checkWay === 4"
      :check-id="form.checkWay === 3"
      :tourist-list="touristList"
      :update-tourist="updateTourist"
      ref="touristList"></TouristList>
  </div>
</template>

<script>
import { randomString } from '@/utils'
import { verifyId, verifyPhone } from '@/utils/validate'
import { checkWayList } from '@/assets/staticData'
import { getTicketPricePlanList } from '@/api/ticketPricePlan'
import { setTourist } from '@/pages/common'
import TouristList from '../common/TouristList'
import ReaderInput from '@/components/ReaderInput'
import moment from 'moment'
import { IDENTIFY_TYPES } from '@/const'

export default {
  props: {
    currentTicket: {
      type: Object,
      default: () => null
    },
    orderItems: {
      type: Array,
      default: () => []
    }
  },
  components: {
    TouristList,
    ReaderInput
  },
  computed: {
    totalPrice () {
      if (!this.currentTicket) {
        return 0
      }
      return this.$NP.times(this.currentPrice, this.form.count)
    },
    scenicName () {
      return this.$store.state.user.scenicName
    }
  },
  data () {
    return {
      loading: false,
      keyControl: 2, // 键盘控制：1,2,3标识选中顺序
      isFocus: false, // 当前组件是否选中
      papersType: IDENTIFY_TYPES,
      checkWayList,
      pricePlan: [],
      playEndDate: '',
      currentPrice: 0,
      currentPlan: null,
      retail_lockCheckStyle: this.$localStore.get('retail_lockCheckStyle') || false,
      identify_lockCheckStyle: this.$localStore.get('identify_lockCheckStyle') || false,

      touristList: [{
        batchConfigId: randomString(),
        guestName: '',
        guestPhone: '',
        guestIdentify: '',
        guestIdentifyType: 0,
        ticketTypeId: 0,
        checkNum: 1,
        price: 0,
        seatId: 0,
        playDateBegin: new Date(moment().startOf('day').valueOf()),
        lock: false // 是否可编辑
      }],
      form: {
        guestIdentify: '',
        guestName: '',
        guestIdentifyType: 0,
        guestPhone: '',
        groupIndividual: 1,
        count: this.$localStore.get('initNum') === '空' ? undefined : 1,
        payChannel: '现金',
        playDateBegin: new Date(moment().startOf('day').valueOf()),
        playDateEnd: '',
        price: 0,
        checkWay: this.$localStore.get('retail_checkWay') || 1,
        actualMoney: 0 // 实付金额，不需要传给后台
      },
      Certificate: {
      },
      dateOption: {
        // 日历禁用日期
        disabledDate () {
          return false
        }
      }
    }
  },
  created () {
    // this.getTicketPricePlanList()
  },
  methods: {
    verifyId,
    verifyPhone,
    randomString,
    getTicketPricePlanList () {
      getTicketPricePlanList({ keyWords1: 1, pageNum: 0, pageSize: 0 }).then(res => {
        this.pricePlan = res.list

        this.pricePlan.unshift({
          id: null,
          name: '无'
        })
      })
    },
    setFocus () {
      this.$refs.ticketCount.focus()
      this.$refs.ticketCount.select()
    },
    resetForm () {
      this.touristList = [{
        batchConfigId: randomString(),
        guestName: '',
        guestPhone: '',
        guestIdentify: '',
        guestIdentifyType: 0,
        lock: false // 是否可编辑
      }]
      this.$refs.form.resetFields()

      this.form.checkWay = this.$localStore.get('retail_checkWay') || 1

      this.Certificate = {}
    },
    setEndDate () {
      let endDate = moment(this.form.playDateBegin).add(this.currentTicket.use_valid_days - 1, 'days').endOf('day').valueOf()
      this.form.playDateEnd = new Date(endDate)
      this.playEndDate = moment(endDate).format('YYYY-MM-DD')
    },
    // 更新游客列表
    updateTourist (data) {
      this.form.count = data.length
      this.touristList = data
    },
    // 同步游客数据与游客数
    syncTouristList () {
      let num = this.form.count - this.touristList.length
      setTourist(this.touristList, num)
    },
    // 显示游客弹窗
    showTouristList () {
      this.syncTouristList()
      this.$refs.touristList.show()
    },
    isPlayToday () {
      const isBefore = moment(this.form.playDateBegin).isBefore(moment().format('YYYY-MM-DD'))
      const isAfter = moment(this.form.playDateBegin).isAfter(moment().format('YYYY-MM-DD'))
      return !(isBefore || isAfter)
    },
    addToOrder (callback) {
      if (!this.isPlayToday()) {
      // 客户端下单的时候游玩日期不是当天，提示一下
        this.$message.warning('友情提示：您下单的游玩日期不是今天！')
      }

      if (!this.currentTicket) {
        return this.$message.error('请选择门票')
      }

      if (this.loading) return

      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$localStore.set('checkWay', this.form.checkWay)

          this.syncTouristList()

          let { guestName, guestIdentify, guestIdentifyType, guestPhone, playDateBegin, playDateEnd } = this.form

          let { id, name, checkCount } = this.currentTicket

          let price = this.currentPrice

          if (this.form.checkWay === 3) {
            // 是否存在未填写的内容
            let blankData = this.touristList.find(item => {
              return !item.guestName || !item.guestIdentify
            })
            if (blankData) {
              this.$message.error('游客信息不完整，请编辑查看')
              return
            }
          }

          if (this.form.checkWay === 4) {
            // 是否存在未填写的内容
            let blankData = this.touristList.find(item => {
              return !item.face
            })
            if (blankData) {
              this.$message.error('游客人脸信息不完整，请编辑查看')
              return
            }
          }

          let tickets = this.touristList.map(item => {
            return {
              ticketTypeId: id,
              checkNum: checkCount,
              price: this.currentPrice,
              guestName,
              guestPhone,
              guestIdentify,
              guestIdentifyType,
              ticketNo: item.ticketNo,
              face: item.face,
              pricePlanId: this.currentPlan || 0,
              playDateBegin: this.currentTicket.isUseDateLimit ? moment(playDateBegin).format('YYYY-MM-DD') : moment(playDateBegin).format('YYYY-MM-DD'),
              playDateEnd: this.currentTicket.isUseDateLimit ? moment(playDateEnd).format('YYYY-MM-DD') : moment(playDateEnd).format('YYYY-MM-DD')
            }
          })

          // 合并游玩日期相同的票种数据
          const existItem = this.orderItems.find(i => {
            let dateIsEque
            if (this.currentTicket.isUseDateLimit) {
              dateIsEque = JSON.stringify(i.playDateBegin) === JSON.stringify(playDateBegin)
            } else {
              dateIsEque = true
            }
            // 日期对象不全等
            return i.id === this.currentTicket.id && dateIsEque && i.price === this.currentPrice
          })

          if (existItem) {
            existItem.tickets = existItem.tickets.concat(tickets)
            existItem.count = existItem.tickets.length
            existItem.total = this.$NP.plus(existItem.total, this.totalPrice)
          } else {
            this.orderItems.push({
              keyId: randomString(), // 唯一标识
              id, // 票种Id
              ticketName: name,
              count: tickets.length,
              price,
              total: this.totalPrice,
              playDateBegin: this.currentTicket.isUseDateLimit ? playDateBegin : playDateBegin,
              currentTicket: { ...this.currentTicket, pricePlanId: this.currentPlan, price, playDateBegin, playDateEnd },
              tickets
            })
          }

          // 重置游客数量
          this.touristList = [{
            batchConfigId: randomString(),
            guestName: '',
            guestPhone: '',
            guestIdentify: '',
            guestIdentifyType: 0,
            playDateBegin: new Date(moment().startOf('day').valueOf()),
            lock: false // 是否可编辑
          }]

          this.form.count = this.$localStore.get('initNum') === '空' ? undefined : 1

          if (callback && typeof callback === 'function') {
            callback()
          }

          this.$nextTick(() => {
            this.$refs.form.clearValidate()
          })
        }
      })
    },
    setPrice () {
      if (!this.currentTicket) {
        this.currentPrice = 0
        return
      }
      this.currentPrice = this.currentTicket.price
    },
    defaultPapersType () {
      if (process.env.VUE_APP_PROJECT === 'zql') {
        return 0
      } else if (this.$localStore.get('retail_identify')) {
        return this.$localStore.get('retail_identify')
      } else {
        return ''
      }
    }

  },
  watch: {
    currentTicket (val) {
      if (!val) return

      this.resetForm()

      // 设置初始日期
      if (moment(val.useDateStart).isAfter(new Date())) {
        this.form.playDateBegin = val.useDateStart
      } else {
        this.form.playDateBegin = new Date(moment().startOf('day').valueOf())
      }
      // 设置不可选日期
      this.dateOption.disabledDate = (date) => {
        let beforeToday = moment().subtract(1, 'days').isAfter(date)
        let beforeStart = moment(val.useDateStart).isAfter(date)
        let afterEnd = moment(val.useDateEnd).isBefore(date)
        return beforeToday || beforeStart || afterEnd
      }

      this.timer && clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.setPrice()
      }, 300)
    },
    retail_lockCheckStyle (val) {
      if (val) {
        this.$localStore.set('retail_checkWay', this.form.checkWay)
      }
      this.$localStore.set('retail_lockCheckStyle', val)
    },
    identify_lockCheckStyle (val) {
      if (val) {
        this.$localStore.set('retail_identify', this.form.buyerIdentifyType)
      }
      this.$localStore.set('identify_lockCheckStyle', val)
    },
    'form.playDateBegin' (val) {
      if (val) {
        this.setEndDate()
        this.currentPlan = null
        this.timer && clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.setPrice()
        }, 300)
      }
    },
    currentPlan () {
      this.setPrice()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-input,.el-select,.el-date-editor,.el-date-editor.el-input,.el-input-number {
  width: 200px;
}

</style>
