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

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

      <el-form
        v-show="preOrderInfo && preOrderInfo.id"
        v-loading="loading"
        class="sale-form-wrap"
        ref="form"
        :model="form"
        :inline="true"
        label-width="120px">
        <el-form-item
          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>

      <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>

    <!-- 游客列表 -->
    <!-- 游客列表需要在清空订单时再点击一次上方的已审核订单，以同步游客数据 syncTouristList -->
    <div v-if="false">
      {{ touristList.length }}
      {{ touristList }}
    </div>
    <TouristList
      :check-face="form.checkWay === 4"
      :check-id="form.checkWay === 3"
      :tourist-list="touristList"
      :update-tourist="updateTourist"
      :pre-order-id="preOrderInfo.id"
      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 { setTourist } from './index.js'
/*
import TouristList from '../common/TouristList'
*/
import TouristList from './TouristList' // 会设置_travellerType字段

import ReaderInput from '@/components/ReaderInput'

import moment from 'moment'

export default {
  props: {
    currentTicket: {
      type: Object,
      default: () => null
    },
    orderItems: {
      type: Array,
      default: () => []
    },
    preOrderInfo: {
      type: Object,
      default: () => null
    }
  },
  components: {
    TouristList,
    ReaderInput
  },
  computed: {
    // 获取tickets数组里的学生类型人数，而不是student_num字段
    getRealStudentNum () {
      return -1
    },
    // 获取tickets数组里的教师类型人数，而不是teacher_num字段
    getRealTeacherNum () {
      return -1
    },
    totalPrice () {
      if (!this.currentTicket) {
        return 0
      }
      return this.$NP.times(this.currentPrice, this.form.count)
    },
    agencyList () {
      return this.$store.state.app.agencyList
    }
  },
  data () {
    return {
      loading: false,
      papersType,
      checkWayList,
      playEndDate: '',
      agencyInfo: {}, // 传入确认框中的旅行社名称和导游名称
      guideList: [],
      touristList: [{
        idKey: randomString(),
        guestName: '',
        guestPhone: '',
        guestIdentify: '',
        guestIdentifyType: 'ID_CARD',
        lock: false // 是否可编辑
        // _travellerType: 1
      }],
      currentPrice: 0,
      form: {
        preOrderId: '',
        buyerName: '',
        buyerPhone: '',
        buyerIdentifyType: '',
        buyerIdentify: '',
        payChannel: '',
        ticketTypeId: 0,
        ticketTypeName: '',
        checkWay: 1
      },
      dateOption: {
        // 日历禁用日期
        disabledDate () {
          return false
        }
      }
    }
  },
  methods: {
    verifyId,
    verifyPhone,
    randomString,
    // 获取旅行社列表
    getGuideList (agencyId) {
    },
    setFocus () {
      this.$refs.ticketCount.focus()
      this.$refs.ticketCount.select()
    },
    resetForm () {
      this.touristList = [{
        idKey: randomString(),
        guestName: '',
        guestPhone: '',
        guestIdentify: '',
        guestIdentifyType: 'ID_CARD',
        lock: false // 是否可编辑
      }]
      this.$refs.form.resetFields()
    },
    setEndDate () {
      // if (!this.currentTicket) return

      // 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 () {
      console.log('this.form.count', this.form.count, 'this.touristList.length', this.touristList.length)
      let num = this.form.count - this.touristList.length
      console.log('syn', this.touristList)
      setTourist(this.touristList, num)
    },
    /*
    // 显示游客弹窗
    showTouristList () {
      this.syncTouristList()
      this.touristVisible = true
      this.$refs.touristList.show()
    },
    */
    // 显示游客弹窗
    async showTouristList () {
      this.syncTouristList()
      this.touristVisible = true
      await this.$refs.touristList.show()
    },
    // this.touristData = this.touristData.map(tourist => ({
    //       ...tourist,
    //       travellerType: extraInfo.travellers.find(traveller => tourist.guestIdentify && tourist.guestIdentify.length && traveller.idNum === tourist.guestIdentify)?.travellerType || 0
    //     }))
    addToOrder (callback) {
      if (!this.priceObj || !this.priceObj?.id) {
        // this.$message.error('请重新获取票种价格')
        this.setPrice()
        return
      }

      // console.log('this.priceObj.id', this.priceObj?.id, this.currentTicket?.id)
      if (!this.currentTicket) {
        return this.$message.error('请选择门票')
      }

      if (this.loading) return

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

      if (moment(this.form.payDateBegin).isBefore(moment().startOf('day'))) {
        this.$message.error('当前游玩日期不可购买')
        return
      }
      // 非审核通过预订单，不继续执行
      if (!this.preOrderInfo || this.preOrderInfo.status !== 'APPROVE') {
        this.$message.error(`当前预订状态，无法继续执行`)
        return
      }

      console.log('this.preOrderInfo.number', this.preOrderInfo.number)
      this.form.count = this.preOrderInfo.number
      /*
      this.form.count = this.preOrderInfo.student_num + this.preOrderInfo.teacher_num
      */

      return this.$refs.form.validate((valid) => {
        if (valid) {
          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
            }
          }

          console.log('touristList', this.touristList)

          if (!id) {
            this.$message.error('请选择当前票种')
            return
          }

          if (!this.preOrderInfo || !this.preOrderInfo?.id) {
            this.$message.error('请先选择预订单')
            return
          }

          let tickets = this.touristList.map(item => {
            return {
              ticketTypeId: id,
              travellerType: this.preOrderInfo.travellers.find(traveller => item.guestIdentify && item.guestIdentify.length && traveller.idNum === item.guestIdentify)?.travellerType || 0,
              checkNum: check_count,
              price: this.currentPrice,
              discountPrice: this.currentPrice,
              guestName: item.guestName,
              guestPhone: item.guestPhone,
              guestIdentify: item.guestIdentify,
              guestIdentifyType: item.guestIdentifyType,
              face: item.face,
              payDateBegin: this.currentTicket.isNeedPlaytime ? payDateBegin : null,
              playDateEnd: this.currentTicket.isNeedPlaytime ? playDateEnd : null
            }
          })

          // console.log('tickets', tickets)

          /*
          if (this.preOrderInfo.teacher_num > 0) {
            let minusCount = 0
            let count = Math.floor((this.preOrderInfo.student_num + this.preOrderInfo.teacher_num) / 20)
            minusCount = minusCount + count
            let remainder = (this.preOrderInfo.student_num + this.preOrderInfo.teacher_num) % 20
            if (remainder > 14) {
              minusCount = minusCount + 1
            }
            let realCount = 0
            if (this.preOrderInfo.teacher_num > minusCount) {
              realCount = minusCount
            } else {
              realCount = this.preOrderInfo.teacher_num
            }
            for (var i = tickets.length - 1; i > tickets.length - 1 - realCount; i--) {
              tickets[i].discountPrice = 0
              tickets[i].price = 0
            }
            tickets.forEach(v => {
              v.discountPrice = v.price
            })
          }
          */
          // 这个笔订单，71学6教，应该免3个，买74张票，是3108，系统收3066，少收42元，免了4个人，多免了一个人，
          // 42元的票，总数买77张，录入6个教师，然后免三张票，也就是花了74张票的钱，应该收3108元
          /* 实际老师数为travellerType为1的元素个数，总数量其余假定为为学生 */

          // 许峰：不满20不免，满20后，余数大于等于15再免，免老师
          // 统一口径：学生人数不满20不免，学生人数满20后，余数大于等于15再免，免老师
          const preOrderInfo_teacher_num = this.preOrderInfo.travellers.filter(item => item.travellerType === 1)?.length
          const preOrderInfo_student_num = tickets.length - preOrderInfo_teacher_num // this.preOrderInfo.travellers.filter(item => item.travellerType === 0)?.length
          console.log('实际老师数', preOrderInfo_teacher_num, '实际学生数', preOrderInfo_student_num)
          if (preOrderInfo_teacher_num > 0) {
            let minusCount = 0
            // 按学生数量来满减；而不用总数preOrderInfo_student_num + preOrderInfo_teacher_num
            let count = Math.floor((preOrderInfo_student_num) / 20)
            minusCount = minusCount + count
            // 不用preOrderInfo_student_num + preOrderInfo_teacher_num
            let remainder = (preOrderInfo_student_num) % 20
            // 避免学生人数16,老师人数2的时候免(客户希望应该不免)
            if (remainder > 14 && preOrderInfo_student_num > 20) {
              minusCount = minusCount + 1
            }
            let realCount = 0
            if (preOrderInfo_teacher_num > minusCount) {
              realCount = minusCount
            } else {
              realCount = preOrderInfo_teacher_num
            }
            for (var i = tickets.length - 1; i > tickets.length - 1 - realCount; i--) {
              tickets[i].discountPrice = 0
              tickets[i].price = 0
            }
            tickets.forEach(v => {
              v.discountPrice = v.price
            })
          }

          // 合并游玩日期相同的票种数据
          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
          } else {
            this.orderItems.push({
              keyId: randomString(), // 唯一标识
              id, // 票种Id
              ticketName: name,
              count: this.preOrderInfo.number,
              price,
              payDateBegin: this.currentTicket.isNeedPlaytime ? payDateBegin : null,
              tickets
            })
          }

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

          this.form.count = 1

          this.form.preOrderId = this.preOrderInfo.id

          if (callback && typeof callback === 'function') {
            callback()
          }
        }
      })
    },
    setPrice () {
      if (!this.currentTicket) {
        this.currentPrice = 0
        return
      }
      this.loading = true
      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 === null ? this.currentTicket.price : res?.data.prices[0].price)
          : this.currentTicket.price
      }).finally(() => {
        this.loading = false
      })
    }
  },
  watch: {
    isFocus (val) {
      val && this.setFocus()
    },
    preOrderInfo: {
      async handler (val) {
        if (val) {
          // this.form.travelAgencyId = val.travelAgencyId
          // this.form.guideId = val.guideId
          console.log('val.number', val.number)
          this.form.count = val.number || val.travellers.length || 1
          // this.getGuideList(this.form.travelAgencyId)
          // this.form.payDateBegin = new Date(moment(val.play_date).startOf('day').valueOf())
          if (val.travellers && val.travellers.length) {
            this.syncTouristList()
            this.touristList.forEach((v, i) => {
              v.guestName = ''
              v.guestIdentifyType = ''
              v.guestIdentify = ''
              v.guestName = val.travellers[i]?.name
              v.guestIdentifyType = val.travellers[i]?.idType
              v.guestIdentify = val.travellers[i]?.idNum
              v.face_image = val.travellers[i]?.face_image
              // v._travellerType = val.travellerType
            })
            // console.log('this.touristList', val, this.touristList)
          }
        }
      },
      immediate: true,
      deep: true
    },
    currentTicket (val) {
      if (!val) return

      // 设置不可选日期
      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.setEndDate()
      this.timer && clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.setPrice()
      }, 300)
    },
    'form.payDateBegin' (val) {
      if (val) {
        this.setEndDate()
        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>
