<template>
  <div>
    <el-dialog
      title="填写订单信息"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="90%"
      @close="visible=false">
      <div class="wrap">
        <el-form
          class="sale-form-wrap"
          ref="buyerForm"
          :model="form"
          :inline="true"
          label-position="top"
          label-width="100px">
          <el-form-item
            style="width:250px"
            verify
            can-be-empty
            label="顾客姓名"
            prop="buyerName"

          >
            <el-input
              v-model="form.buyerName"
            ></el-input>
          </el-form-item>

          <el-form-item
            style="width:250px"
            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
            style="width:250px"
            key="id2"
            label="证件号码"
            prop="buyerIdentify">
            <el-input v-model="form.buyerIdentify"></el-input>
          </el-form-item>

          <el-form-item
            style="width:250px"
            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
            style="width:250px"
            can-be-empty
            :verify="verifyPhone"
            label="手机号码"
            prop="buyerPhone">
            <el-input
              v-model="form.buyerPhone"></el-input>
          </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
            style="width:250px"
            label="旅行社"
            prop="travelAgencyId">
            <el-select
              v-model="form.travelAgencyId"
              filterable
              @change="getGuideList">
              <el-option value="">
                无
              </el-option>
              <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
            style="width:250px"
            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>

        <el-form
          ref="guestForm"
          :model="model"
        >
          <el-table
            max-height="400px"
            :data="model.ticketsData"
            border
            stripe>
            <el-table-column
              prop="price"
              label="游客姓名"
              width="250">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.guestName"
                  style="margin-bottom:17px"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              prop="price"
              label="游客证件号"
              width="250">
              <template slot-scope="scope">
                <!-- 非身份证入园，不可为空 -->
                <el-form-item
                  v-if="form.checkWay===3"
                  :verify="form.checkWay===3?verifyId:null"
                  :prop="'ticketsData.' + scope.$index + '.guestIdentify'"
                >
                  <el-input v-model="scope.row.guestIdentify"></el-input>
                </el-form-item>
                <el-form-item
                  v-else
                  can-be-empty
                  :verify="form.checkWay===3?verifyId:null"
                  :prop="'ticketsData.' + scope.$index + '.guestIdentify'"
                >
                  <el-input v-model="scope.row.guestIdentify"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="区域"
              width="120">
              <template slot-scope="scope">
                <el-tag
                  :color="scope.row.area.color"
                  style="color:#fff">
                  {{ scope.row.area.name }}
                </el-tag>
              </template>
            </el-table-column>

            <!-- <el-table-column
              prop="name"
              label="座位号"
              width="100">
              <template slot-scope="scope">
                {{ scope.row.seat.row_tag + '排' +scope.row.seat.name+'座' }}
              </template>
            </el-table-column> -->

            <el-table-column
              prop="name"
              label="票种选择">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.ticketTypeId"
                  @change="handleTicketTypeChange(scope.row,$event,scope.$index)">
                  <el-option
                    v-for="item in scope.row.ticketTypeList"
                    :key="item.ticketTypeId"
                    :label="item.ticketTypeName"
                    :value="item.ticketTypeId">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column
              prop="price"
              label="价格"
            >
              <template slot-scope="scope">
                {{ currentPlan ? (scope.row.priceMap[currentPlan] || '未设置价格') : (currentTicket[scope.$index].price||'未设置价格') }}
              </template>
            </el-table-column>
          </el-table>
        </el-form>

        <div class="checkoutWrap">
          <div class="pricePlan">
            票种设置：
            <el-select
              clearable
              v-model="ticketAll"
              @change="handleTicketTypeChangeAll($event)">
              <el-option
                v-for="item in model.ticketsData[0].ticketTypeList "
                :key="item.ticketTypeId"
                :label="item.ticketTypeName"
                :value="item.ticketTypeId">
              </el-option>
            </el-select>
          </div>
          <div class="pricePlan">
            价格方案：
            <el-select
              clearable
              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>
          </div>

          <div class="info">
            {{ date | formatDate }} - {{ performInfo.name }} - {{ batchInfo.name }}

            <span>{{ batchInfo.startTime }} ~ {{ getEndTime(batchInfo) }}</span>

            <br>
            <span
              v-for="(item,index) in ticketsNumList"
              :key="index">
              {{ item.name }}：<b>{{ item.num }}</b> 张
            </span>

            <span>
              总价：<b>{{ totalPrice }}</b> 元
            </span>

            <div v-if="currentAgency">
              <span>旅行社有效期：<b>{{ currentAgency.valid_date | formatDate }}</b></span>
              <span>旅行社余额：<b>{{ currentAgency.prepayment_amount }}</b></span> 元
            </div>
          </div>

          <div>
            付款方式：
            <el-radio-group
              size="medium"
              fill="#ff6934"
              v-model="form.payChannel">
              <el-radio-button
                v-for="val in payChannelOptions"
                :key="val"
                :label="val"></el-radio-button>
            </el-radio-group>
          </div>

          <div>
            <div style="margin-top:10px">
              <span class="item">实付金额：
                <el-input-number
                  clearable
                  :min="0"
                  :precision="2"
                  :controls="false"
                  v-model.number="form.actualMoney"></el-input-number>
              </span>
              <span class="item">备注：
                <el-input
                  clearable
                  v-model="form.remark"
                  style="width:200px"></el-input>
              </span>
              <span class="item">图片备注：
                <el-button
                  type="primary"
                  size="small"
                  icon="el-icon-edit"
                  @click="showUploadImgDialog"
                >
                  编辑查看
                </el-button>
              </span>

              <span class="item price">{{ payBack>0?'找零':'还需支付' }}：<b>{{ Math.abs(payBack) }}</b> 元</span>

              <span class="item">
                <PrintSmallTicketCheckbox v-model="isPrintSmallTicket"></PrintSmallTicketCheckbox>

                <el-checkbox
                  v-model="autoPrint"
                  style="margin:10px"
                  @change="handleAutoPrintChange"
                >
                  门票打印
                </el-checkbox>
              </span>
            </div>
          </div>
        </div>
      </div>

      <span slot="footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button
          type="primary"
          :disabled="submitDisable"
          @click="handleSubmit()">确 定</el-button>
      </span>
      <ReadValueCard
        ref="readValueCard"
        @getInfo="handleValueCardPay"
        @close="submitDisable=false"></ReadValueCard>

      <!-- GlobalComponents 全局组件 -->
      <PosQrCodeReader
        ref="posQrCodeReader"
        @getQrcode="handleSubmit"></PosQrCodeReader>
      <XSCQrCodeReader
        ref="XSCQrCodeReader"
        @getQrcode="handleSubmit"></XSCQrCodeReader>
      <!-- 图片备注 -->
    </el-dialog>
    <UploadImgList
      :picture-remarks="pictureRemarks"
      :update-remarks="updateRemarks"
      ref="uploadImgDialog">
    </UploadImgList>
  </div>
</template>

<script>
import { papersType } from '@/assets/staticData'
import { verifyId, verifyPhone } from '@/utils/validate'
import { createOrder, getSingleOrder } from '@/api/order'
import groupBy from 'lodash/groupBy'
import moment from 'moment'
import { randomString } from '@/utils'
import UploadImgList from '../common/uploadImgList'
import ReadValueCard from '../common/ReadValueCard'
import handlePay from '../common/handlePay'
import posMixin from '@/pages/common/posMixin'
import { createValueCardOrder } from '@/api/valueCard'
import { apiGetGuideList } from '@/api/travelAgency'
import { debounce } from 'throttle-debounce'
import PrintSmallTicketCheckbox from '../common/PrintSmallTicketCheckbox'

const checkWayList = [
  { name: '一码一人', val: 1 },
  //   { name: '一码多人', val: 2 },
  { name: '身份证入园', val: 3 }
//   { name: '人脸入园', val: 4 }
]

export default {
  props: {
    selectedSeat: {
      type: Array,
      default: () => []
    },
    pricePlan: {
      type: Array,
      default: () => []
    }
  },
  mixins: [posMixin],
  components: {
    ReadValueCard,
    PrintSmallTicketCheckbox,
    UploadImgList
  },
  computed: {
    payChannelOptions () {
      return this.$store.state.app.payChannelOptions
    },
    payBack () {
      if (this.form.actualMoney === undefined) {
        return -this.totalPrice
      } else {
        return this.$NP.minus(this.form.actualMoney, this.totalPrice)
      }
    },
    agencyList () {
      return this.$store.state.app.agencyList
    },
    currentAgency () {
      return this.form.travelAgencyId ? this.agencyList.find(i => i.id === this.form.travelAgencyId) : null
    },
    tickets () {
      return this.model.ticketsData.map((ticket, index) => {
        const { ticketTypeId, seat, priceMap, ticketNameMap, guestName, guestIdentify, ticketTypeList, seat_area_id } = ticket
        // const { is_discount } = ticket.ticketTypeList.find(i => i.ticketTypeId === ticket.ticketTypeId)
        return {
          guestName,
          guestIdentify,
          face: {},
          perform_id: this.performInfo.id,
          batch_config_id: this.batchInfo.batch_config_id,
          seat_id: seat.id,
          ticketTypeList,
          ticketTypeId,
          // is_discount,
          payDateBegin: this.date,
          playDateEnd: '',
          checkNum: 1,
          price_plan_id: this.currentPlan,
          ticketTypeName: ticketNameMap[ticketTypeId],
          price: this.currentPlan ? priceMap[this.currentPlan] : this.currentTicket[index].price || 0,
          seat_area_id
        }
      })
    },
    totalPrice () {
      return this.tickets.reduce((i, init) => {
        return (i * 1000 + init.price * 1000) / 1000
      }, 0)
    },
    ticketsNumList () {
      if (this.tickets.length) {
        const group = groupBy(this.tickets, i => i.ticketTypeName)

        const result = []

        for (let key in group) {
          result.push({
            name: key,
            num: group[key].length
          })
        }

        return result
      } else {
        return []
      }
    }
  },
  data () {
    return {
      ticketAll: '',
      currentTicket: [],
      verifyId,
      verifyPhone,
      papersType,
      checkWayList,
      visible: false,
      guideList: [],
      model: {
        ticketsData: []
      },
      priceMap: {},
      batchInfo: {},
      currentPlan: null,
      createOrderStatus: 0, // 创建订单状态
      payStatus: 0, // 支付状态
      timer: null, // 检查订单是否支付成功计时器
      orderTempInfo: {}, // 临时订单信息，防止重复创建订单
      submitDisable: false,
      date: '',
      performInfo: {},
      autoPrint: this.$localStore.get('autoPrint'),
      isPrintSmallTicket: this.$localStore.get('autoPrintSmallTicket'),
      form: {
        buyerIdentify: '',
        buyerName: '',
        buyerIdentifyType: 'ID_CARD',
        buyerPhone: '',
        travelAgencyId: '',
        guideId: '',
        groupIndividual: 1,
        payChannel: '现金',
        payDateBegin: new Date(moment().startOf('day').valueOf()),
        playDateEnd: '',
        price: 0,
        checkWay: this.$localStore.get('checkWay') || 1,
        remark: '',
        actualMoney: 0 // 实付金额，不需要传给后台
      },
      pictureRemarks: [{
        idKey: randomString(),
        url: '',
        remark: ''
      }]
    }
  },
  methods: {
    // 更新图片备注列表
    updateRemarks (data) {
      this.pictureRemarks = data
    },
    // 显示图片备注弹窗
    showUploadImgDialog () {
      this.$refs.uploadImgDialog.show()
    },
    show (info, currentArea, currentTicket, currentTicketNum) {
      this.submitDisable = false
      this.visible = true
      this.createOrderStatus = 0

      this.date = info.date
      this.priceMap = info.priceMap
      this.batchInfo = info.batchInfo
      this.performInfo = info.performInfo

      // this.currentPlan = this.pricePlan.length ? this.pricePlan[0].id : 0
      console.log('info', info)
      let selectedSeat = []
      for (var i = 0; i < currentTicketNum; i++) {
        selectedSeat.push({
          area_id: currentArea,
          ticketTypeId: currentTicket.ticketTypeId
        })
      }
      console.warn(selectedSeat)

      this.model.ticketsData = selectedSeat.map((seat, index) => {
        const ticketTypeList = info.priceMap[seat.area_id]

        const ticket_type = (ticketTypeList && ticketTypeList.length && ticketTypeList[0]) || null

        const plan_price = ticket_type && ticket_type.plan_price

        const ticketNameMap = {}

        ticketTypeList.forEach(item => {
          ticketNameMap[item.ticketTypeId] = item.ticketTypeName
        })

        const priceMap = {}

        plan_price.forEach(item => {
          priceMap[item.plan_id] = item.price
        })

        const planMap = {}
        this.currentTicket[index] = ticketTypeList[0]
        ticketTypeList.forEach(item => {
          planMap[item.ticketTypeId] = item.plan_price || 0
        })
        return {
          seat,
          ticketNameMap,
          guestName: '',
          guestIdentify: '',
          ticketTypeId: seat.ticketTypeId,
          area: info.areaMap[seat.area_id],
          ticketTypeList: ticketTypeList,
          planMap,
          priceMap,
          seat_area_id: currentArea
        }
      })
    },
    getGuideList (agencyId) {
      let agency = this.agencyList.find(a => a.id === agencyId)
      // 设置折扣
      // this.$parent.$parent.$refs.orderInfo.discount = agency.discount
      this.guideList = []
      this.form.guideId = ''

      agency && 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 : ''
      })
    },
    handleValueCardPay (cardInfo) {
      console.log('储值卡信息', cardInfo)
      createValueCardOrder({
        cardNo: cardInfo.cardCode,
        cardVendor: 'CHANGYI',
        order: this.params
      }).then(res => {
        this.handleCreateSuccess(this.params, res)
      })
    },
    handleAutoPrintChange (val) {
      this.$localStore.set('autoPrint', val)
    },
    getEndTime (i) {
      if (!i) return
      return moment(i.startTime, 'HH:mm:ss').add(moment.duration(i.duration)).format('HH:mm:ss')
    },
    handleTicketTypeChange (ticket, id, index) {
      this.currentTicket[index] = ticket.ticketTypeList.filter(e => {
        return e.ticketTypeId === id
      })[0]
      const priceMap = {}
      ticket.planMap[id].forEach(item => {
        priceMap[item.plan_id] = item.price
      })

      ticket.seat.ticketTypeId = id
      ticket.priceMap = priceMap
      ticket.ticket_type = priceMap
    },
    handleTicketTypeChangeAll (id) {
      this.model.ticketsData.forEach((ticket, index) => {
        ticket.ticketTypeId = id
        this.handleTicketTypeChange(ticket, id, index)
      })
    },
    handleClose () {
      this.timer && clearTimeout(this.timer)
      if (this.submitDisable) {
        this.$confirm('支付尚未完成，是否强制关闭？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$log.info('支付进程被强制关闭')
          this.visible = false

          // 结束支付进程
          this.killAllPosProcess()
        }).catch(() => {})
        return
      }

      this.visible = false

      this.$refs.buyerForm.resetFields()
      // 结束支付进程
      this.killAllPosProcess()
    },

    handleSubmit: debounce(1000, true, async function (qrcode, cardInfo) {
      let buyerValid
      let guestValid

      try {
        buyerValid = await this.$refs.buyerForm.validate()
        guestValid = await this.$refs.guestForm.validate()
      } catch (e) {
      }

      if (!buyerValid || !guestValid) return
      if (this.form.payChannel === '旅行社余额' && !this.form.travelAgencyId) {
        this.$message.error('请选择旅行社')
        return false
      }

      this.form.price = this.totalPrice
      this.form.tickets = this.tickets
      this.form.pictureRemarks = this.pictureRemarks

      // 保存检票方式
      this.$localStore.set('checkWay', this.form.checkWay)
      this.$localStore.set('batch_config_id', this.batchInfo.batch_config_id)
      this.$localStore.set('perform_id', this.performInfo.id)

      // if (this.form.payChannel.indexOf('储值卡') > -1 && this.scenicName === '西宁景区') {
      //   // ID卡
      //   this.$refs.readValueCard.show()
      //   return
      // }

      // 是否使用外部扫码
      if (this.form.payChannel === '聚合扫码' && !qrcode) {
        this.$refs.posQrCodeReader.show()
        return
      }
      // if (this.form.payChannel.indexOf('储值卡') > -1) {
      //   // ID卡
      //   this.$refs.readValueCard.show()
      //   return
      // }
      const scanArr = ['中旅银行', '瑞通储值卡', '建行B扫C', '福建农信']
      // 是否使用外部扫码
      if (scanArr.indexOf(this.form.payChannel) > -1 && !qrcode) {
        this.$refs.XSCQrCodeReader.show(this.tickets, this.form.payChannel)
        return
      }
      // 防止重复提交
      if (this.submitDisable) return
      this.submitDisable = true

      this.form.qrCode = qrcode
      this.form.discount = cardInfo ? cardInfo.discount : ''
      this.form.password = cardInfo ? cardInfo.password : ''
      this.$log.warn('支付下单')
      this.createOrder(this.form)

      // createOrder(this.form).then(res => {
      //   this.$message.success('下单成功')

      //   // 身份证检票不打印
      //   let autoPrint = this.form.checkWay === 3 ? false : (this.$localStore.get('autoPrint') || false)

      //   // 获取订单详情
      //   // 自动打印
      //   autoPrint && getSingleOrder(res?.data).then(order => {
      //     this.$print(order)
      //   })

      //   this.$emit('update')

      //   this.handleClose()
      // })
    }),
    handleCreateSuccess (params, res) {
      this.$message.success('出票成功')
      this.submitDisable = false
      // 获取订单详情
      // 自动打印
      // 身份证检票不打印
      let autoPrint = this.form.checkWay === 3 ? false : (this.$localStore.get('autoPrint') || false)

      // 获取订单详情
      // 自动打印
      getSingleOrder(res?.data).then(async order => {
        autoPrint && this.$print(order)

        if (this.form.payChannel === '旅行社余额') {
          await this.$store.dispatch('getAgencyList')
        }

        const currentAgency = this.agencyList.find(i => i.id === this.form.travelAgencyId)

        if (currentAgency) {
          order.prepayment_amount = currentAgency.prepayment_amount
        }

        console.error(order)

        this.isPrintSmallTicket && this.$printSmallTicket(order)

        this.$emit('update')

        this.handleClose()
      })
    },
    createOrder (params) {
      this.submitDisable = true
      if (this.createOrderStatus === 1) {
        handlePay(this.form, this.orderTempInfo, this, () => {})
      } else {
        createOrder(params).then(res => {
          this.$log.warn('散客下单成功')
          this.createOrderStatus = 1
          this.orderTempInfo = res
          handlePay(this.form, res, this, () => {})
          if (this.payStatus !== 1) {
            this.getSingleOrder(res, params)
          }
        })
      }
    },
    getSingleOrder (res, params) {
      this.timer && clearTimeout(this.timer)
      getSingleOrder(res?.data).then(order => {
        console.log('order', order)
        if (order.pay_status === 'PAYED') {
          this.handleCreateSuccess(params, res)
        } else if (order.pay_status === 'CLOSED') {
          this.$message.error('交易失败，订单关闭，请重新创建订单')
          this.submitDisable = false
          this.visible = false
        } else {
          this.timer = setTimeout(() => {
            this.getSingleOrder(res, params)
          }, 1000)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrap {
  padding: 20px;
}
.title {
  display: flex; padding: 10px; font-size: 20px; color: red;  text-align: center; justify-content: space-between; align-items: center;
}

.numWrap {display: flex;
  padding: 10px 0; font-size: 18px; color: red; justify-content: space-between; align-items: top;
  span {
    margin-right: 20px;
  }
  b {
    font-size: 1.4em;
  }
}

.el-input,.el-select,.el-date-editor,.el-date-editor.el-input,.el-input-number {
  width: 200px;
}
.el-dialog .el-form-item {
  display: inline-block;
}

.checkoutWrap {
  text-align: right;

  .info {padding: 10px; font-size: 18px; line-height: 2;
    color: red;
  }

  .pricePlan {
    padding: 10px;
  }

  span {
    margin-left: 20px;
  }
}

</style>
