<template>
  <div>
    <el-card>
      <template slot="header">
        <div
          class="card-title"
          v-if="currentTicket">
          <span>当前票种：<b>{{ currentTicket.name || '无' }}</b></span>
        </div>
        <span
          v-else
          style="color:red">请选择门票</span>
      </template>
      <el-form
        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
          label="游客类型"
          prop="customerType">
          <el-select v-model="form.customerType">
            <el-option
              v-for="item in customerType"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          can-be-empty
          label="游客联系方式"
          :verify="verifyPhone"
          prop="buyerPhone">
          <el-input
            v-model="form.buyerPhone">
          </el-input>
        </el-form-item>
        <el-form-item
          label="销售"
          prop="salesperson">
          <el-input
            v-model="form.salesperson">
          </el-input>
        </el-form-item>

        <el-form-item
          label="旅行社"
          prop="travelAgencyId">
          <el-select
            v-model="form.travelAgencyId"
            filterable
            :filter-method="filterAgency"
            @change="getGuideList">
            <el-option
              v-for="item in filterAgencyList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="导游"
          prop="guideId">
          <el-select 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
          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-date-picker
            disabled
            v-model="playEndDate"
            type="date">
          </el-date-picker>
        </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
          verify
          number
          label="优惠价">
          <el-input-number
            @change="handlePriceChange"
            controls-position="right"
            v-model.number="discountPrice"
            :min="0"
            :precision="2"
            :step="1"
          ></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-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 { getCustomerType } from '@/api/systemConfig'
import { setTourist } from '@/pages/common'
import { checkWayList } from '@/assets/staticData'
import { apiGetGuideList } from '@/api/travelAgency'

import TouristList from '../common/TouristList'
import moment from 'moment'

export default {
  props: {
    currentTicket: {
      type: Object,
      default: () => null
    },
    orderItems: {
      type: Array,
      default: () => []
    }
  },
  components: {
    TouristList
  },
  computed: {
    totalPrice () {
      if (!this.currentTicket) {
        return 0
      }
      return this.$NP.times(this.discountPrice, this.form.count)
    },
    agencyList () {
      return this.$store.state.app.agencyList
    }
  },
  data () {
    return {
      checkWayList,
      customerType: [],
      keyControl: 2, // 键盘控制：1,2,3标识选中顺序
      isFocus: false, // 当前组件是否选中
      playEndDate: '',
      discountPrice: 0,
      guideList: [],
      filterAgencyList: [],
      touristList: [{
        idKey: randomString(),
        guestName: '',
        guestPhone: '',
        guestIdentify: '',
        lock: false // 是否可编辑
      }],
      form: {
        buyerName: '',
        buyerPhone: '',
        salesperson: '',
        customerType: '',
        groupIndividual: 3, // 企事业
        travelAgencyId: '',
        guideId: '',
        managerId: 0,
        payChannel: '现金',
        price: 0, // 实际总价
        tickets: [],
        payDateBegin: new Date(moment().startOf('day').valueOf()),
        playDateEnd: '',
        checkWay: this.$localStore.get('checkWay') || 1,
        count: 1,
        checkNum: 1
      },
      dateOption: {
        // 日历禁用日期
        disabledDate () {
          return false
        }
      }
    }
  },
  created () {
    this.getCustomerType()
  },
  methods: {
    verifyId,
    verifyPhone,
    randomString,
    filterAgency (input) {
      if (input) {
        this.filterAgencyList = this.agencyList.filter(i => i.shorthand.toLowerCase().indexOf(input.toLowerCase()) > -1 || i.name.indexOf(input) > -1)
      } else {
        this.filterAgencyList = this.agencyList
      }
    },
    // 获取旅行社列表
    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 : ''
      })
    },
    getCustomerType () {
      getCustomerType().then(res => {
        this.customerType = res
      })
    },
    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.touristVisible = true
      this.$refs.touristList.show()
    },
    handlePriceChange (e) {
      this.$parent.$parent.orderItems.forEach(item => {
        if (item.id === this.currentTicket.id) {
          item.price = e
          item.total = this.$NP.times(item.tickets.length, e)
          item.tickets.forEach(t => {
            t.price = e
            t.discount = Math.round(e / t.originalPrice * 100)
          })
        }
      })
    },
    addToOrder (callback) {
      if (!this.currentTicket) {
        return this.$message.error('请选择门票')
      }

      if (this.loading) return

      this.form.count = this.form.count || 1
      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, price } = this.currentTicket

          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.discountPrice,
              originalPrice: price,
              discount: Math.round(this.discountPrice / price * 100),
              guestName: item.guestName,
              guestPhone: item.guestPhone,
              guestIdentify: item.guestIdentify,
              ticketNo: item.ticketNo,
              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
            existItem.total = this.$NP.plus(existItem.total, this.totalPrice)
          } else {
            this.orderItems.push({
              keyId: randomString(), // 唯一标识
              id, // 票种Id
              ticketName: name,
              count: tickets.length,
              discount: Math.round(this.discountPrice / price * 100),
              originalPrice: price, // 原价
              price: this.discountPrice, // 折后价
              total: this.$NP.times(tickets.length, this.discountPrice), // 总价
              payDateBegin: this.currentTicket.isNeedPlaytime ? payDateBegin : null,
              currentTicket: { ...this.currentTicket, price_plan_id: this.currentPlan, price, payDateBegin, playDateEnd },
              tickets
            })
          }
          // 重置游客数量
          this.touristList = [{
            idKey: randomString(),
            guestName: '',
            guestPhone: '',
            guestIdentify: '',
            lock: false // 是否可编辑
          }]

          this.form.count = 1

          if (callback && typeof callback === 'function') {
            callback()
          }
        }
      })
    }
  },
  watch: {
    isFocus (val) {
      val && this.setFocus()
    },
    agencyList: {
      handler (val) {
        this.filterAgencyList = val
      },
      immediate: true
    },
    currentTicket (val) {
      if (!val) return

      this.resetForm()

      // 设置初始日期
      // 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.discountPrice = val.price
      // 修改原订单票种价格
      this.handlePriceChange(val.price)
      this.setEndDate()
    },
    'form.payDateBegin' (val) {
      if (val) {
        this.setEndDate()
      }
    }
  }
}
</script>

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

</style>
