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

        <div>【 {{ playDate }} 】 票价：<span class="price"><b>{{ currentTicket && currentTicket.price }}</b> 元</span></div>
      </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="旅行社"
          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
            disabled
            :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"
            :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
          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"
          :disabled="!currentTicket"
          @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 { papersType, checkWayList } from '@/assets/staticData'
import { setTourist } from '@/pages/common'
import { apiGetGuideList } from '@/api/travelAgency'
import TouristList from '../common/TouristList'
import ReaderInput from '@/components/ReaderInput'
import moment from 'moment'

export default {
  props: {
    currentBatch: {
      type: Object,
      default: () => null
    },
    currentSchedule: {
      type: Object,
      default: () => null
    },
    currentTicket: {
      type: Object,
      default: () => null
    },
    currentCategoryType: {
      type: [Number, String],
      default: () => null
    },
    orderItems: {
      type: Array,
      default: () => []
    },
    playDate: {
      type: String,
      default: moment().format('YYYY-MM-DD')
    }
  },
  components: {
    TouristList,
    ReaderInput
  },
  computed: {
    totalPrice () {
      if (!this.currentTicket) {
        return 0
      }
      return this.$NP.times(this.currentTicket.price, this.form.count)
    },
    agencyList () {
      return this.$store.state.app.agencyList
    }
  },
  data () {
    return {
      loading: false,
      keyControl: 2, // 键盘控制：1,2,3标识选中顺序
      isFocus: false, // 当前组件是否选中
      papersType,
      checkWayList,
      guideList: [],
      filterAgencyList: [],
      playEndDate: '',
      touristList: [{
        idKey: randomString(),
        guestName: '',
        guestPhone: '',
        guestIdentify: '',
        cardNo: '',
        lock: false // 是否可编辑
      }],
      form: {
        buyerIdentify: '',
        buyerName: '',
        buyerIdentifyType: '',
        buyerPhone: '',
        groupIndividual: 1,
        travelAgencyId: '',
        guideId: '',
        count: this.$localStore.get('initNum') === '空' ? undefined : 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,
    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 : ''
      })
    },
    setFocus () {
      this.$refs.ticketCount.focus()
      this.$refs.ticketCount.select()
    },
    resetForm () {
      this.touristList = [{
        idKey: randomString(),
        guestName: '',
        guestPhone: '',
        guestIdentify: '',
        cardNo: '',
        lock: false // 是否可编辑
      }]
      this.$refs.form.resetFields()
    },
    // 更新游客列表
    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

      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, 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 {
              batch_config_id: this.currentBatch.batch_config_id,
              schedule_config_id: this.currentSchedule ? this.currentSchedule.schedule_config_id : 0,
              ticketTypeId: id,
              checkNum: check_count,
              price: this.currentTicket.price,
              guestName: item.guestName,
              guestPhone: item.guestPhone,
              guestIdentify: item.guestIdentify,
              guestIdentifyType: item.guestIdentifyType,
              ticketNo: item.ticketNo,
              face: item.face,
              payDateBegin: payDateBegin,
              playDateEnd: playDateEnd
            }
          })

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

          if (existItem) {
            existItem.batch = this.currentBatch
            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(), // 唯一标识
              batch: this.currentBatch,
              id, // 票种Id
              ticketName: name,
              count: tickets.length,
              price,
              total: this.totalPrice,
              payDateBegin: payDateBegin,
              currentTicket: {
                ...this.currentTicket,
                price_plan_id: this.currentPlan,
                price,
                payDateBegin,
                playDateEnd,
                batch_config_id: this.currentBatch.batch_config_id,
                schedule_config_id: this.currentSchedule ? this.currentSchedule.schedule_config_id : 0

              },
              tickets
            })
          }

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

          this.form.count = 1

          if (callback && typeof callback === 'function') {
            callback()
          }
        }
      })
    }
  },
  watch: {
    agencyList: {
      handler (val) {
        this.filterAgencyList = val
      },
      immediate: true
    },
    playDate: {
      handler (val) {
        this.form.payDateBegin = new Date(val)
      },
      immediate: true
    },
    currentTicket: {
      handler (val) {
        if (val && val.category) {
          this.form.checkWay = val.category
        }
      },
      immediate: true
    },
    currentCategoryType: {
      handler (val) {
        if (val) this.form.checkWay = val
      },
      immediate: true
    }
  }
}
</script>

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