<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible="visible"
    :before-close="handleClose"
    title="出票确认"
    width="80%">
    <el-form
      v-loading="submitDisable"
      element-loading-text="正在处理付款请求，请稍候"
      class="info-wrap"
      label-width="100px"
      :inline="true">
      <div style="margin-bottom: 20px;">
        付款方式：
        <el-radio-group
          :disabled="createOrderStatus===1"
          size="medium"
          fill="#ff6934"
          v-model="currentPayChannel">
          <el-radio-button
            v-for="val in payChannelOptions"
            :key="val"
            :label="val"></el-radio-button>
        </el-radio-group>
      </div>
      <el-table
        border
        :data="orderInfo"
        style="margin-bottom:30px">
        <el-table-column
          label="预订单号"
          prop="pre_no"
        >
        </el-table-column>
        <el-table-column
          prop="ticketTypeName"
          label="票种名称"
          width="180">
        </el-table-column>
        <el-table-column
          label="单价"
          prop="price"
        >
        </el-table-column>
        <el-table-column
          label="发码模式"
          prop="num_type"
        >
          <template slot-scope="scope">
            {{ scope.row.num_type===1?'一码多人':'一码一人' }}
          </template>
        </el-table-column>
        <el-table-column
          label="游玩时间"
          prop="play_date"
          min-width="120"
        >
        </el-table-column>

        <el-table-column
          label="备注"
          prop="remark"
          min-width="120"
        >
          <template slot-scope="scope">
            <Ellipsis
              v-if="scope.row.remark"
              :content="scope.row.remark"
              :length="10"></Ellipsis>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          width="140"
        >
          <template slot-scope="scope">
            {{ scope.row.createTime | formatTime }}
          </template>
        </el-table-column>
      </el-table>

      <el-form-item
        label="总数"
        class="warning">
        <span class="strong">
          {{ totalCount }}
        </span> 张
      </el-form-item>

      <el-form-item
        label="总金额"
        class="warning">
        <span class="strong">
          {{ orderPrice }}
        </span> 元
      </el-form-item>

      <el-form-item
        label="折扣"
        class="warning">
        <span class="strong">
          {{ discount }}
        </span> 折
      </el-form-item>

      <el-form-item
        label="折后总额"
        class="warning">
        <span class="strong">
          {{ finalPrice }}
        </span> 元
      </el-form-item>

      <el-form-item
        label="检票方式"
        class="warning">
        <span class="strong">
          {{ getCheckWayName(formData?formData.checkWay:'') }}
        </span>
      </el-form-item>

      <el-form-item
        label="付款方式"
        class="warning">
        <span class="strong">
          {{ payChannel }}
        </span>
      </el-form-item>

      <el-form-item
        v-if="currentPayChannel==='旅行社余额' && currentAgency"
        label="预付余额"
        class="warning">
        <span class="strong">
          {{ currentAgency.prepayment_amount }}
        </span>
      </el-form-item>

      <el-form-item
        v-if="currentPayChannel==='旅行社余额' && currentAgency"
        label="信用限额"
        class="warning">
        <span class="strong">
          {{ currentAgency.prepayment_type?currentAgency.prepayment_limit:'无限制' }}
        </span>
      </el-form-item>

      <br>
      <el-form-item
        label="备注">
        {{ formData.remark }}
      </el-form-item>
    </el-form>
    <div
      class="table-box"
      style="padding-top:0">
      <Collapse title="游客详情信息">
        <el-table
          stripe
          :data="tickets">
          <el-table-column
            type="index"
            width="50"
          >
          </el-table-column>

          <el-table-column
            prop="guestName"
            label="游客姓名"
          >
          </el-table-column>

          <el-table-column
            prop="guestPhone"
            label="游客电话"
          >
          </el-table-column>

          <el-table-column
            prop="guestIdentify"
            label="身份证"
            min-width="130"
          >
          </el-table-column>
        </el-table>
      </Collapse>
    </div>

    <div class="dialog-btn-wrap">
      打印小票
      <el-switch
        style="margin:0 50px 0 10px"
        v-model="isPrintSmallTicket">
      </el-switch>

      自动打印
      <el-switch
        style="margin:0 50px 0 10px"
        v-model="isPrint">
      </el-switch>

      <el-button @click="handleClose">
        取消
      </el-button>

      <el-button
        type="warning"
        v-if="showRefresh"
        :disabled="isRefresh"
        @click="payRefresh">
        刷新支付状态<span v-if="isRefresh">({{ countNum }})</span>
      </el-button>

      <el-button
        type="danger"
        v-if="scenicName==='狼山景区'||scenicName==='军山景区'"
        @click="$refs.queryPos.show()">
        查询POS机交易
      </el-button>
      <el-button
        type="primary"
        :disabled="submitDisable"
        @click="submit()"
      >
        {{ submitDisable?'正在处理':'确认出票' }}
      </el-button>
    </div>

    <ReadValueCard
      ref="readValueCard"
      @getInfo="handleValueCardPay"
      @close="submitDisable=false"></ReadValueCard>

    <QueryPos
      ref="queryPos"
      @confirm="handleQueryPos"></QueryPos>

    <!-- GlobalComponents 全局组件 -->
    <PosQrCodeReader
      ref="posQrCodeReader"
      @getQrcode="submit"></PosQrCodeReader>
    <XSCQrCodeReader
      ref="XSCQrCodeReader"
      @getQrcode="submit"></XSCQrCodeReader>
    <ValueCardInput
      ref="ValueCardInput"
      @getMemberSystemId="submit"></ValueCardInput>
  </el-dialog>
</template>

<script>
import { preorderCreateOrder } from '@/api/order'
import { getPosPayChannel } from '@/utils/choosePay'

import mixin from './mixin'
import posMixin from '@/pages/common/posMixin'
import confirmMixin from '../common/confirmMixin'

import handlePay from '../common/handlePay'
import { debounce } from 'throttle-debounce'

export default {
  props: {
    discount: {
      type: Number,
      default: 0
    },
    finalPrice: {
      type: Number,
      default: 0
    },
    preOrderInfo: {
      type: Object,
      default: () => null
    }
  },
  mixins: [mixin, posMixin, confirmMixin],
  computed: {
    agencyList () {
      return this.$store.state.app.agencyList
    },
    currentAgency () {
      return this.agencyList.find(i => i.id === this.formData.travelAgencyId)
    }
  },
  data () {
    return {
      pageName: '团体预订售票',
      printPlayDateBegin: ''
    }
  },
  methods: {
    setParams () {
      let tickets = JSON.parse(JSON.stringify(this.tickets))
      let params = Object.assign({}, this.formData)
      params.ticketTypeId = this.orderInfo[0].tickets[0].ticketTypeId
      params.price = this.orderInfo[0].tickets[0].price
      params.payChannel = this.currentPayChannel

      // 一码多人
      if (params.checkWay - 0 === 2) {
        let allTickets = []

        this.orderInfo.forEach((item, index) => {
          let count = item.count
          let ticketOrderTravellers = item.tickets.map(i => {
            return {
              name: i.guestName,
              idType: i.guestIdentifyType,
              idNum: i.guestIdentify,
              mobile: i.guestPhone
            }
          })
          let obj = JSON.parse(JSON.stringify(item.tickets[0]))
          obj.ticketOrderTravellers = ticketOrderTravellers
          let originItem = JSON.stringify(obj)

          if (!this.maxNum) {
            let item = JSON.parse(originItem)
            item.checkNum = count
            item.price = this.$NP.times(item.checkNum, item.discountPrice)
            allTickets.push(item)
            return
          }

          if (count > this.maxNum) {
            let num = Math.ceil(count / this.maxNum)

            for (let i = 0; i < num - 1; i++) {
              let newItem = JSON.parse(originItem)
              newItem.checkNum = this.maxNum
              newItem.price = this.$NP.times(this.maxNum, newItem.discountPrice)
              allTickets.push(newItem)
            }
            let lastItem = JSON.parse(originItem)

            if (count % this.maxNum === 0) {
              lastItem.checkNum = this.maxNum
            } else {
              lastItem.checkNum = count % this.maxNum
            }

            lastItem.price = this.$NP.times(lastItem.checkNum, lastItem.discountPrice)

            allTickets.push(lastItem)
          } else {
            let item = JSON.parse(originItem)
            item.checkNum = count
            item.price = this.$NP.times(item.checkNum, item.discountPrice)
            allTickets.push(item)
          }
        })

        params.tickets = allTickets
      } else {
        params.tickets = tickets.map(item => {
          item.price = item.discountPrice
          return item
        })
      }
      params.tickets.forEach(v => {
        v.play_date = this.preOrderInfo.play_date
        v.payDateBegin = this.preOrderInfo.play_date
      })
      params.payChannel = this.currentPayChannel
      params.price = this.finalPrice
      params.sellDevice = this.sellerDevice && this.sellerDevice.ip4

      params.tickets.forEach(ticket => {
        ticket.face = {
          face_img: ticket.face
        }
      })

      this.params = params
    },
    createOrder (params) {
      if (params.bocTradeNo) {
        params.payChannel = getPosPayChannel(params.bocTradeNo)
      }
      this.submitDisable = true
      if (this.createOrderStatus === 1) {
        handlePay(this.params, this.orderTempInfo, this, () => {})
        if (this.payStatus !== 1) {
          this.getSingleOrder(this.orderTempInfo, params)
        }
      } else {
        preorderCreateOrder({
          order: params,
          id: this.preOrderInfo.id
        }).then(res => {
          this.$log.warn('预订票下单成功')
          this.createOrderStatus = 1
          this.orderTempInfo = res
          handlePay(this.params, res, this, () => {})
          if (this.payStatus !== 1) {
            this.getSingleOrder(res, params)
          }
        }).catch(e => {
          this.submitDisable = false
        })
      }
    },
    createSuccessCallback () {
      // 更新旅行社余额
    },
    submit: debounce(1000, true, function (qrcode, cardInfo) {
      console.log(this.payType)
      // 西宁景区储值卡支付预留
      if (this.payType === 'VALUECARD' && this.scenicName === '西宁景区') {
        this.setParams()
        this.$refs.readValueCard.show(this.params)
        return
      }

      // POS支付是否使用外部扫码
      if (this.payType === 'POS' && !qrcode && this.showPosQrcode) {
        this.$refs.posQrCodeReader.show()
        return
      }

      const scanArr = ['瑞通储值卡']
      // 是否使用外部扫码
      if ((scanArr.indexOf(this.currentPayChannel) > -1 || this.payType === 'B_SCAN_C_PAY') && !qrcode) {
        this.setParams()
        /*
        preorderCreateOrder({
          ...this.params
        })
        */
        preorderCreateOrder({
          order: this.params,
          id: this.preOrderInfo.id
        }).then(res => {
          this.$log.warn(this.pageName + '下单成功')
          this.createOrderStatus = 1
          this.orderTempInfo = res
          this.$refs.XSCQrCodeReader.show(this.tickets, this.currentPayChannel)
        })
        return
      }

      // 防止重复提交
      if (this.submitDisable) return
      this.submitDisable = true

      // 支付已成功只提交订单
      if (this.payStatus === 1) {
        this.createOrder(this.params)
        return
      }

      this.setParams()

      this.params.qrCode = qrcode
      this.$log.warn('预订票支付下单')
      this.createOrder(this.params)
    })
  }
}
</script>

<style lang="scss" scoped>
.btn-wrap {
  padding-top: 20px; text-align: center;
}
.info-wrap {
  padding: 20px 20px;
  ::v-deep .el-form-item__label{
    font-size: 16px;
  }
  ::v-deep .el-form-item{
    display: inline-block;
  }
  .strong {
    font-size: 1.8em; font-weight: bold;
  }
}

</style>

<style lang="scss">

</style>
