<template>
  <div>
    <el-card>
      <div
        slot="header"
        class="card-title">
        <span>订单信息</span>
      </div>
      <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="buyerName">
          <el-input
            v-model="form.buyerName"></el-input>
        </el-form-item>
        <el-form-item
          can-be-empty
          :verify="verifyPhone"
          label="手机号码"
          prop="buyerPhone">
          <el-input
            v-model="form.buyerPhone"></el-input>
        </el-form-item>
        <el-form-item
          label="证件类型"
          prop="buyerIdentifyType">
          <el-select
            v-model="form.buyerIdentifyType"
            placeholder="请选择">
            <el-option
              v-for="(item,key) in papersType"
              :key="key"
              :label="item"
              :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          key="id1"
          :verify="verifyId"
          can-be-empty
          v-if="form.buyerIdentifyType==='ID_CARD'"
          label="证件号码"
          prop="buyerIdentify">
          <ReaderInput
            type="ID"
            @change="form.buyerName=$event.Name"
            v-model="form.buyerIdentify"></ReaderInput>
        </el-form-item>
        <el-form-item
          v-else
          key="id2"
          label="证件号码"
          prop="buyerIdentify">
          <el-input v-model="form.buyerIdentify"></el-input>
        </el-form-item>
        <el-form-item
          label="顾客信息"
        >
          <el-input
            v-model="form.buyerName"></el-input>
        </el-form-item>
        <el-form-item
          label="座位票种"
          prop="buyerIdentifyType">
          <el-select
            v-model="form.buyerIdentifyType"
            placeholder="请选择价格方案">
            <el-option
              v-for="(item,key) in papersType"
              :key="key"
              :label="item"
              :value="key">
            </el-option>
          </el-select>
        </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-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 { papersType, checkWayList } from '@/assets/staticData'
import { getTicketTypeInfo } from '@/api/ticketType'
import { setTourist } from '@/pages/common'

import TouristList from '../common/TouristList'
import ReaderInput from '@/components/ReaderInput'
import moment from 'moment'

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)
    }
  },
  data () {
    return {
      loading: false,
      keyControl: 2, // 键盘控制：1,2,3标识选中顺序
      isFocus: false, // 当前组件是否选中
      papersType,
      checkWayList,
      playEndDate: '',
      currentPrice: 0,
      touristList: [{
        idKey: randomString(),
        guestName: '',
        guestPhone: '',
        guestIdentify: '',
        lock: false // 是否可编辑
      }],
      form: {
        buyerIdentify: '',
        buyerName: '',
        buyerIdentifyType: '',
        buyerPhone: '',
        groupIndividual: 1,
        count: 1,
        payChannel: '现金',
        payDateBegin: new Date(moment().startOf('day').valueOf()),
        playDateEnd: '',
        price: 0,
        checkWay: this.$localStore.get('checkWay') || 1,
        actualMoney: 0 // 实付金额，不需要传给后台
      },
      dateOption: {
        // 日历禁用日期
        disabledDate () {
          return false
        }
      }
    }
  },
  methods: {
    verifyId,
    verifyPhone,
    randomString,
    setFocus () {
      this.$refs.ticketCount.focus()
      this.$refs.ticketCount.select()
    },
    resetForm () {
      this.touristList = [{
        idKey: randomString(),
        guestName: '',
        guestPhone: '',
        guestIdentify: '',
        lock: false // 是否可编辑
      }]
      this.$refs.form.resetFields()
    },
    setEndDate () {
      let endDate = moment(this.form.payDateBegin).add(this.currentTicket.useDays - 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()
    },
    addToOrder (callback) {
      if (this.loading) return

      // 校验当前票种与价格是否一致
      if (this.priceObj.id !== this.currentTicket.id) {
        this.setPrice()
        return
      }

      this.form.count = this.form.count || 1

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

          this.syncTouristList()

          let { payDateBegin, playDateEnd } = this.form

          let { id, name, check_count } = 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: check_count,
              price: this.currentPrice,
              guestName: item.guestName,
              guestPhone: item.guestPhone,
              guestIdentify: item.guestIdentify,
              face: {
                face_img: item.face
              },
              payDateBegin: this.currentTicket.isNeedPlaytime ? payDateBegin : null,
              playDateEnd: this.currentTicket.isNeedPlaytime ? playDateEnd : null
            }
          })

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

          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,
              payDateBegin: this.currentTicket.isNeedPlaytime ? payDateBegin : null,
              tickets
            })
          }

          // 重置游客数量
          this.touristList = [{
            idKey: randomString(),
            guestName: '',
            guestPhone: '',
            guestIdentify: '',
            lock: false // 是否可编辑
          }]

          this.form.count = 1

          if (callback && typeof callback === 'function') {
            callback()
          }
        }
      })
    },
    setPrice () {
      getTicketTypeInfo({
        id: this.currentTicket.id,
        start: moment(this.form.payDateBegin).format('YYYY-MM-DD'),
        end: moment(this.form.payDateBegin).format('YYYY-MM-DD')
      }).then(res => {
        this.priceObj = res?.data

        this.currentPrice = res?.data.prices[0] ? res?.data.prices[0].price : 0
      }).finally(() => {
        this.loading = false
      })
    }
  },
  watch: {
    currentTicket (val) {
      if (!val) return
      // 设置初始日期
      if (moment(val.useDateStart).isAfter(new Date())) {
        this.form.payDateBegin = val.useDateStart
      } else {
        this.form.payDateBegin = 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.loading = true
      this.timer && clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.setPrice()
      }, 300)
    },
    'form.payDateBegin' (val) {
      if (val) {
        this.setEndDate()
        this.loading = true
        this.timer && clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.setPrice()
        }, 300)
      }
    }
  }
}
</script>

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