<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>{{ discountPrice }}</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
            v-model="form.travelAgencyId"
            filterable
            :filter-method="filterAgency"
            @change="changeGuideList">
            <el-option
              v-for="item in filterAgencyList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button
            v-if="projectName==='sanheguzhen'"
            style="margin-left:5px"
            type="primary"
            plain
            @click="showDialog('new')">
            创建
          </el-button>
        </el-form-item>
        <el-form-item
          verify
          prop="payDateBegin"
          label="游玩日期">
          <el-date-picker
            :clearable="false"
            :editable="false"
            :picker-options="dateOption"
            v-model="form.payDateBegin"
            @change="setPalyDate"
            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
          v-if="allowDiscount"
          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"
            :disabled="group_lockCheckStyle">
            <el-option
              v-for="item in checkWayList"
              :key="item.val"
              :value="item.val"
              :label="item.name"
            ></el-option>
          </el-select>
          <el-checkbox
            style="margin-left:10px"
            v-model="group_lockCheckStyle">
            锁定
          </el-checkbox>
        </el-form-item>
        <el-form-item
          label="价格方案">
          <el-select
            v-model="currentPlan"
            v-if="pricePlan.length">
            <el-option
              v-for="item in pricePlan"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- v-if="form.checkWay === 3 || form.checkWay === 4" -->
        <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"
          @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>

    <!-- 弹框 -->
    <ElDialog
      title="新增旅行社"
      width="760px"
      v-model="dialogVisible">
      <AgencyDialog
        :dialog-type="dialogType"
        @updateList="getAgencyList">
      </AgencyDialog>
    </ElDialog>

    <ElDialog
      title="录入导游信息"
      width="760px"
      v-model="dialogVisible2">
      <EditDialog
        :dialog-type="dialogType"
        :agency-list="agencyList"
        @updateList="getGuideList"
      ></EditDialog>
    </ElDialog>
  </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 { getTicketPricePlanList } from '@/api/ticketPricePlan'
import { setTourist } from '@/pages/common'

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

import ElDialog from '@/components/Dialog'
import AgencyDialog from '@/pages/agency/agencySetting/EditDialog'
import EditDialog from '@/pages/agency/guideQuery/EditDialog'

export default {
  props: {
    currentTicket: {
      type: Object,
      default: () => null
    },
    orderItems: {
      type: Array,
      default: () => []
    }
  },
  components: {
    ElDialog,
    AgencyDialog,
    EditDialog,
    TouristList
  },
  computed: {
    //  旅行社和导游是否独立
    allowAgency () {
      const value = this.$store.state.app.systemConfig.find(i => i.configKey === 'guide_bind_travel_agency').configValue
      return value !== '0'
    },
    // 是否允许优惠售票
    allowDiscount () {
      const value = this.$store.state.app.systemConfig.find(i => i.configKey === 'group_ticket_sale_has_discount_price').configValue
      return value !== '0'
    },
    totalPrice () {
      if (!this.currentTicket) {
        return 0
      }
      return this.$NP.times(this.currentPrice, this.form.count)
    },
    agencyList () {
      return this.$store.state.app.agencyList
    },
    scenicName () {
      return this.$store.state.user.scenicName
    }
  },
  data () {
    return {
      loading: false,
      papersType,
      checkWayList,
      playEndDate: '',
      agencyInfo: {}, // 传入确认框中的旅行社名称和导游名称
      guideList: [],
      discountPrice: 0, // 优惠价
      pricePlan: [],
      currentPlan: null,
      group_lockCheckStyle: this.$localStore.get('group_lockCheckStyle') || false,
      touristList: [{
        idKey: randomString(),
        guestName: '',
        guestPhone: '',
        guestIdentify: '',
        guestIdentifyType: 'ID_CARD',
        lock: false // 是否可编辑
      }],
      currentPrice: 0,
      form: {
        groupIndividual: 2,
        teamIndividual: 2,
        travelAgencyId: '',
        guideId: '',
        managerId: 0,
        payChannel: '现金',
        price: 0, // 实际总价
        tickets: [],
        discount: 10, // 辅助信息
        payDateBegin: new Date(moment().startOf('day').valueOf()),
        playDateEnd: '',
        checkWay: this.$localStore.get('group_checkWay') || 2,
        count: this.$localStore.get('initNum') === '空' ? undefined : 1,
        checkNum: 1
      },
      filterAgencyList: [],
      projectName: process.env.VUE_APP_PROJECT,
      dialogVisible: false,
      dialogVisible2: false,
      dialogType: 'new',
      dateOption: {
        // 日历禁用日期
        disabledDate () {
          return false
        }
      }
    }
  },
  methods: {
    verifyId,
    verifyPhone,
    randomString,
    setPalyDate (val) {
      this.$emit('changePlayDate', val)
    },
    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
      }
    },
    // 获取价格方案表
    getTicketPricePlanList () {
      getTicketPricePlanList({ keyWords1: 1, pageNum: 0, pageSize: -1 }).then(res => {
        this.pricePlan = res.list

        this.pricePlan.unshift({
          id: null,
          name: '无'
        })
      })
    },

    // 选择旅行社
    changeGuideList (agencyId) {
      let agency = this.agencyList.find(a => a.id === agencyId)
      // 设置折扣
      this.$parent.$parent.$refs.orderInfo.discount = (agency ? agency.discount : 10)
      this.allowAgency && this.getGuideList(agencyId)
    },
    // 获取旅行社列表
    getGuideList (agencyId) {
      let agency = this.agencyList.find(a => a.id === agencyId)
      apiGetGuideList({
        keyWords3: agencyId && agency.name,
        keyWords6: 1,
        pageNum: 0,
        pageSize: -1
      }).then(res => {
        this.guideList = res.list
        // this.form.guideId = this.guideList[0] ? this.guideList[0].id : ''
      })
    },
    getAgencyList () {
      this.$store.dispatch('getAgencyList')
    },
    showDialog (type, item) {
      this.dialogType = type
      this.dialogVisible = true
    },
    showDialog2 (type, item) {
      this.dialogType = type
      this.dialogVisible2 = true
    },
    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()

      if (this.group_lockCheckStyle) {
        this.form.checkWay = this.$localStore.get('group_checkWay') || 2
      } else {
        this.form.checkWay = 2
      }
    },
    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.discountPrice = e || (e === 0 ? 0 : this.currentTicket.price)
      this.$parent.$parent.orderItems.forEach(item => {
        if (item.id === this.currentTicket.id) {
          item.price = this.discountPrice
          item.total = this.$NP.times(item.tickets.length, e)
          item.tickets.forEach(t => {
            t.price = this.discountPrice
            t.discount = Math.round(e / t.originalPrice * 100)
          })
        }
      })
    },
    addToOrder (callback) {
      if (!this.currentTicket) {
        return this.$message.error('请选择门票')
      }

      if (this.loading) return

      // 校验当前票种与价格是否一致
      if (this.priceObj.id !== this.currentTicket.id) {
        this.setPrice()
        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.allowDiscount ? this.discountPrice : this.currentPrice,
              guestName: item.guestName,
              guestPhone: item.guestPhone,
              guestIdentify: item.guestIdentify,
              guestIdentifyType: item.guestIdentifyType,
              ticketNo: item.ticketNo,
              face: item.face,
              price_plan_id: this.currentPlan || 0,
              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 && i.price === this.discountPrice
          })

          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,
              originalPrice: price, // 原价
              price: this.allowDiscount ? this.discountPrice : price, // 折后价
              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: '',
            guestIdentifyType: 'ID_CARD',
            lock: false // 是否可编辑
          }]

          this.form.count = this.$localStore.get('initNum') === '空' ? undefined : 1

          if (callback && typeof callback === 'function') {
            callback()
          }

          this.$nextTick(() => {
            this.$refs.form.clearValidate()
          })
        }
      })
    },
    setPrice () {
      if (!this.currentTicket) {
        this.currentPrice = 0
        return
      }
      this.loading = true

      getTicketTypeInfo({
        planId: this.currentPlan,
        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
      })
    }
  },
  mounted () {
    this.getTicketPricePlanList()
    !this.allowAgency && this.getGuideList()
  },
  watch: {
    isFocus (val) {
      val && this.setFocus()
    },
    group_lockCheckStyle (val) {
      if (val) {
        this.$localStore.set('group_checkWay', this.form.checkWay)
      }
      this.$localStore.set('group_lockCheckStyle', val)
    },
    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.timer && clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.setPrice()
      }, 300)
    },
    'form.payDateBegin' (val) {
      if (val) {
        this.setEndDate()
        this.currentPlan = null
        this.timer && clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.setPrice()
        }, 300)
      }
    },
    currentPlan () {
      this.setPrice()
    }
  }
}
</script>

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

</style>
