<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-loading="loading"
        class="sale-form-wrap"
        ref="form"
        :model="form"
        :inline="true"
        label-width="120px">
        <!-- <el-form-item
          verify
          class="is-required"
          label="旅行社"
          prop="travelAgencyId">
          <el-select
            disabled
            v-model="form.travelAgencyId"
            @change="getGuideList">
            <el-option
              v-for="item in agencyList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item
          label="导游"
          prop="guideId">
          <el-select
            disabled
            v-model="form.guideId">
            <el-option
              v-for="item in guideList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item
          v-if="currentTicket&&currentTicket.isNeedPlaytime"
          verify
          disabled
          prop="payDateBegin"
          label="游玩日期">
          <el-date-picker
            :clearable="false"
            :editable="false"
            :picker-options="dateOption"
            v-model="form.payDateBegin"
            type="date">
          </el-date-picker>
        </el-form-item>
        <el-form-item
          v-if="currentTicket && currentTicket.isNeedPlaytime"
          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">
            <el-option
              v-for="item in checkWayList"
              :key="item.val"
              :value="item.val"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.checkWay === 3 || form.checkWay === 4"
          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-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 { apiGetGuideList } from '@/api/travelAgency'
import { getTicketTypeInfo } from '@/api/ticketType'
import { setTourist } from '@/pages/common'

import TouristList from '../common/TouristList'

import moment from 'moment'

export default {
  props: {
    currentTicket: {
      type: Object,
      default: () => null
    },
    orderItems: {
      type: Array,
      default: () => []
    },
    preOrderInfo: {
      type: Object,
      default: () => null
    }
  },
  components: {
    TouristList
  },
  computed: {
    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 // 是否可编辑
      }],
      currentPrice: 0,
      form: {
        groupIndividual: 2,
        travelAgencyId: '',
        guideId: '',
        managerId: 0,
        payChannel: '现金',
        price: 0, // 实际总价
        tickets: [],
        discount: 10, // 辅助信息
        payDateBegin: new Date(moment().startOf('day').valueOf()),
        playDateEnd: '',
        checkWay: this.$localStore.get('checkWay') || 1,
        count: 1,
        checkNum: 1
      },
      dateOption: {
        // 日历禁用日期
        disabledDate () {
          return false
        }
      }
    }
  },
  methods: {
    verifyId,
    verifyPhone,
    randomString,
    // 获取旅行社列表
    getGuideList (agencyId) {
      let agency = this.agencyList.find(a => a.id === agencyId)
      // 设置折扣
      this.$parent.$parent.$refs.orderInfo.discount = agency.discount

      apiGetGuideList({
        keyWords3: agency.name,
        keyWords6: 1,
        pageNum: 0,
        pageSize: -1
      }).then(res => {
        this.guideList = res.list
        this.form.guideId = this.guideList[0] ? this.guideList[0].id : ''
      })
    },
    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 () {
      let num = this.form.count - this.touristList.length
      setTourist(this.touristList, num)
    },
    // 显示游客弹窗
    showTouristList () {
      this.syncTouristList()
      this.touristVisible = true
      this.$refs.touristList.show()
    },
    addToOrder (callback) {
      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 !== 'AGREE') {
        this.$message.error(`当前预订状态，无法继续执行`)
        return
      }

      return 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,
              guestIdentifyType: item.guestIdentifyType,
              face: 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
          } else {
            this.orderItems.push({
              keyId: randomString(), // 唯一标识
              id, // 票种Id
              ticketName: name,
              count: tickets.length,
              price,
              payDateBegin: this.currentTicket.isNeedPlaytime ? payDateBegin : null,
              tickets
            })
          }

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

          this.form.count = 1

          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
          this.form.count = val.booking_num || val.number
          this.getGuideList(this.form.travelAgencyId)
          this.form.payDateBegin = new Date(moment(val.play_date).startOf('day').valueOf())
          if (val.ticket_order && val.ticket_order[0] && val.ticket_order[0].travellers && val.ticket_order[0].travellers.length) {
            this.syncTouristList()
            this.touristList.forEach((v, i) => {
              v.guestName = ''
              v.guestIdentifyType = ''
              v.guestIdentify = ''
              v.guestName = val.ticket_order[0].travellers[i]?.name
              v.guestIdentifyType = val.ticket_order[0].travellers[i]?.idType
              v.guestIdentify = val.ticket_order[0].travellers[i]?.idNum
            })
          }
        }
      },
      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>
