<template>
  <div class="form-wrap">
    <el-form
      class="search-box"
      ref="form"
      :model="form"
      :inline="true"
      label-width="120px"
    >
      <el-form-item
        verify
        :label="agencyName()"
        prop="travelAgencyId">
        <el-select
          v-model="form.travelAgencyId"
          @change="getGuideList"
          filterable>
          <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
        verify
        label="带队导游"
        prop="guideId">
        <el-select
          v-model="form.guideId"
          filterable>
          <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
        :verify="verifyPhone"
        label="联系方式"
        prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>

      <el-form-item
        verify
        label="游玩日期"
        prop="play_date">
        <el-date-picker
          :clearable="false"
          :editable="false"
          :picker-options="dateOption"
          v-model="form.play_date"
          type="date"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item
        verify
        label="支付方式"
        prop="pay_type">
        <el-select v-model="form.pay_type">
          <el-option
            v-for="item in payTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        verify
        label="人数"
        prop="number">
        <el-input-number
          @change="changeNumber"
          v-model="form.number"
          :min="1"
          :precision="0"></el-input-number>
      </el-form-item>

      <el-form-item
        label="客源地"
        prop="customer_source_area">
        <el-input v-model="form.customer_source_area"></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="ticketTypeId">
        <el-select
          v-model="form.ticketTypeId"
          @change="changeTicket">
          <el-option
            v-for="item in ticketsList.filter(item => item.isSale === 1)"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="备注信息"
        class="full-width"
        prop="remark">
        <el-input
          type="textarea"
          :rows="3"
          v-model="form.remark"
          placeholder="如：车辆信息、导游信息、游客信息、门票信息等"></el-input>
      </el-form-item>

      <el-form-item
        label="其他需求"
        class="full-width"
        prop="remark_request">
        <el-input
          type="textarea"
          :rows="3"
          v-model="form.remark_request"
          placeholder="如：运营需求、门票需求等"></el-input>
      </el-form-item>

      <div v-if="form.ticketTypeId">
        <div
          v-if="projectName==='jiulonghu'"
          style="padding:10px;display: flex;"
        >
          <span style="flex:1"> 0 到 18: {{ age1 }} 人</span>
          <span style="flex:1"> 19 到 59: {{ age2 }} 人</span>
          <span style="flex:1"> 60 到 69: {{ age3 }} 人</span>
          <span style="flex:1"> 70 以上: {{ age4 }} 人</span>
        </div>
        <div
          v-if="projectName==='jiulonghu'"
          style="padding:10px;display: flex;">
          <span style="flex:1"> 全价: {{ form.ticket_order[0].travellers.length-age1-age3-age4 }} 人</span>
          <span style="flex:1"> 半价: {{ age1+age3 }} 人</span>
          <span style="flex:1"> 免票: {{ age4 }} 人</span>
          <span style="flex:1"> </span>
        </div>

        <div style="display:flex;margin-bottom:5px;">
          <el-button
            plain
            size="mini"
            type="primary"
            @click="downloadTemp"
            style="margin-right:10px"
          >
            下载模板
          </el-button>

          <el-upload
            :action="uploadUrl"
            :auto-upload="true"
            :show-file-list="false"
            :on-success="handleSuccess"
            :on-error="handleError"
          >
            <el-button
              size="mini"
              type="primary"
            >
              导入模板
            </el-button>
          </el-upload>
        </div>

        <table>
          <tr>
            <th>姓名</th>
            <th>证件类型</th>
            <th>身份证</th>
            <th>操作</th>
          </tr>
          <tr
            v-for="(item,index) in form.ticket_order[0].travellers"
            :key="index">
            <td>
              <el-input
                v-model="form.ticket_order[0].travellers[index].name"
                clearable>
              </el-input>
            </td>
            <td>
              <el-select
                value-key="id"
                v-model="form.ticket_order[0].travellers[index].idType"
                placeholder="请选择">
                <el-option
                  v-for="item1 in papersOption"
                  :key="item1.id"
                  :label="item1.name"
                  :value="item1.id">
                </el-option>
              </el-select>
            </td>
            <td>
              <el-input
                @blur="getAge"
                v-model="form.ticket_order[0].travellers[index].idNum"
                maxlength="18"
                clearable>
              </el-input>
            </td>
            <td>
              <el-button
                :disabled="form.ticket_order[0].travellers.length<2"
                size="mini"
                plain
                type="primary"
                @click="delIdNum(index)"
              >
                删除
              </el-button>
            </td>
          </tr>
        </table>
      </div>

      <div class="btn-wrap">
        <el-button @click="reset()">
          重置
        </el-button>

        <el-button
          type="primary"
          class="btn"
          @click="submit">
          提交预约
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import moment from 'moment'
import { apiGetGuideList, agencyPreOrder } from '@/api/travelAgency'
import { getTicketTypeList } from '@/api/ticketType'
import { verifyPhone } from '@/utils/validate.js'
import { getAgeByCardId } from '@/utils/index.js'
import { papersType } from '@/assets/staticData'

const payTypeOptions = [
  {
    label: '到付',
    value: 1
  },
  {
    label: '预付',
    value: 2
  }
]

export default {
  computed: {
    agencyList () {
      return this.$store.state.app.agencyList
    }
  },
  data () {
    return {
      projectName: process.env.VUE_APP_PROJECT,
      age1: 0, // 0-18
      age2: 0, // 19-59
      age3: 0, // 60-69
      age4: 0, // 70-
      payTypeOptions,
      guideList: [],
      form: {
        travelAgencyId: '',
        guideId: '',
        play_date: '',
        pay_type: 1,
        number: 1,
        salesperson: '',
        remark: '',
        remark_request: '',
        ticket_order: [
          this.defaultTicket() // 只是作为容器 实际需要的是其子级的travellers(身份证)
        ]
      },
      dateOption: {
        // 日历禁用日期
        disabledDate (theTime) {
          let startTime = moment().format('YYYY-MM-DD') + ' 00:00:00'
          return moment(theTime).isBefore(startTime)
        }
      },
      papersOption: Object.keys(papersType).map(key => {
        return {
          id: key,
          name: papersType[key]
        }
      }),
      ticketsList: [],
      uploadUrl: ''
    }
  },
  methods: {
    verifyPhone,
    reset () {
      this.$refs.form.resetFields()
      // this.guideList = []
    },
    getGuideList (agencyId) {
      // let agency = this.agencyList.find(a => a.id === agencyId)

      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 : ''
      })
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log(this.form)
          let params = JSON.parse(JSON.stringify(this.form))
          params.ticket_order[0].travellers = this.form.ticket_order[0].travellers
          params.ticket_order[0].ticketTypeId = this.form.ticketTypeId
          agencyPreOrder(params).then(res => {
            this.$message.success('预订成功。')
            this.reset()
          })
        }
      })
    },
    getTicketTypeList () {
      getTicketTypeList({
        pageNum: 0,
        pageSize: -1
      }).then(res => {
        this.ticketsList = res.list.map(item => {
          item.number = 1
          item.unit_price = item.price // 现数据中 单价对应unit_price    原数据中 单价对应price字段
          item.price = item.unit_price * item.number // 现数据中price改为对应总价
          return item
        })
        if (!this.ticketsList.length) {
          this.form.ticketTypeId = null
          this.form.ticket_order[0].travellers = []
        }
      })
    },
    changeTicket (e) {
      const selectedTicket = this.ticketsList.find(v => v.id === e)
      this.form.ticket_order[0].unit_price = selectedTicket.price
      this.form.ticket_order[0].commission = selectedTicket.commission
      this.form.ticket_order[0].ticketTypeId = selectedTicket.ticketTypeId
      this.form.ticket_order[0].number = this.form.number
      this.form.ticket_order[0].travellers.length = this.form.number
    },
    defaultTicket () {
      let ticket = {
        number: 0,
        price: 0,
        ticketTypeId: 0,
        unit_price: 0,
        commission: 0,
        travellers: [{ idNum: '', idType: 'ID_CARD', name: '' }]
      }
      Reflect.defineProperty(ticket, 'price', {
        set (val) {},
        get () { return ticket.unit_price * ticket.number }
      })
      return ticket
    },
    changeNumber () {
      if (this.form.number > this.form.ticket_order[0].travellers.length) {
        let array = new Array(this.form.number - this.form.ticket_order[0].travellers.length)
        array.fill({ idNum: '', idType: 'ID_CARD', name: '' })
        this.form.ticket_order[0].travellers = this.form.ticket_order[0].travellers.concat(array)
      }
      this.form.ticket_order[0].travellers.length = this.form.number
      this.form.ticket_order[0].number = this.form.number
    },
    delIdNum (index) {
      this.form.ticket_order[0].travellers.splice(index, 1)
      this.form.ticket_order[0].number = this.form.ticket_order[0].travellers.length
      this.form.number = this.form.ticket_order[0].travellers.length
    },
    downloadTemp () {
      window.location.href = require('path').join(__static, '游客信息导入模板.xlsx')
    },
    handleSuccess (response, file, fileList) {
      if (response.resCode === 200) {
        this.$message.success('上传成功')
        this.form.ticket_order[0].travellers = []
        response.extraInfo.forEach(v => {
          this.form.ticket_order[0].travellers.push({
            name: v.guestName,
            idType: this.papersOption.find(w => w.name === v.guestIdentifyType)?.id,
            idNum: v.guestIdentify
          })
        })
        this.form.number = this.form.ticket_order[0].travellers.length
        this.form.ticket_order[0].number = this.form.number
        this.getAge()
      } else {
        this.$message.error('上传失败')
      }
    },
    handleError (e) {
      this.$message.error('上传失败')
    },
    getAge () {
      if (this.projectName !== 'jiulonghu') return
      this.age1 = 0
      this.age2 = 0
      this.age3 = 0
      this.age4 = 0
      this.form.ticket_order[0].travellers.forEach(v => {
        let age
        if (v.idType === 'ID_CARD' && v.idNum.length === 18) {
          age = getAgeByCardId(v.idNum)
          if (age < 18) { // 半价
            this.age1++
          } else if (age > 59 && age < 70) { // 半价
            this.age3++
          } else if (age > 70) { // 免费
            this.age4++
          } else {
            this.age2++
          }
        }
      })
    }
  },
  created () {
    const Store = require('electron-store')
    const localStore = new Store()
    this.uploadUrl = localStore.get('serverUrl') + '/importMission/importTravelInfo'
    this.getTicketTypeList()
    this.getGuideList()
  }
}
</script>

<style lang="scss" scoped>
.full-width{
  width:100%;
  ::v-deep .el-form-item__content{
    width:100%;
  }
}
.btn-wrap{
  text-align: right
}
</style>
