<template>
  <el-dialog
    :close-on-click-modal="false"
    :visible.sync="visible"
    :before-close="handleClose"
    title="门票信息"
    width="80%">
    <el-form
      inline
      label-width="120px"
    >
      <div
        class="dialog-info"
        style="padding-bottom: 0">
        <div class="block-title">
          订单信息
        </div>
        <el-form-item label="订单号">
          {{ info.orderNo }}
        </el-form-item>
        <el-form-item label="支付方式">
          {{ info.payChannel }}
        </el-form-item>
        <el-form-item label="订单金额">
          {{ info.price }}
        </el-form-item>
        <el-form-item label="订单可退金额">
          {{ cancelPrice }}
        </el-form-item>
        <el-form-item
          label="客户姓名"
          v-if="info.buyerName">
          {{ info.buyerName }}
        </el-form-item>
        <el-form-item
          label="手机号码"
          v-if="info.buyerPhone">
          {{ info.buyerPhone }}
        </el-form-item>
        <el-form-item
          label="身份证号"
          v-if="info.buyerIdentify">
          {{ info.buyerIdentify }}
        </el-form-item>
        <el-form-item label="下单时间">
          {{ info.createTime | formatTime }}
        </el-form-item>
      </div>
      <div class="table-box">
        <div class="block-title">
          含票信息
        </div>
        <el-table
          border
          stripe
          :data="info.tickets"
        >
          <el-table-column
            width="160"
            prop="ticketNo"
            label="票号"
          >
          </el-table-column>
          <el-table-column
            width="80"
            prop="guestName"
            label="游客"
          >
          </el-table-column>
          <el-table-column
            width="100"
            prop="guestPhone"
            label="手机号码"
          >
          </el-table-column>
          <el-table-column
            width="150"
            prop="guestIdentify"
            label="证件号码"
          >
          </el-table-column>
          <el-table-column
            width="60"
            prop="price"
            label="票价"
          >
          </el-table-column>
          <el-table-column
            prop="tname"
            label="票种"
          >
          </el-table-column>
          <el-table-column
            width="90"
            prop="statusText"
            label="状态"
          >
            <template slot-scope="scope">
              <OrderStatusTag :value="scope.row.status"></OrderStatusTag>
            </template>
          </el-table-column>
          <el-table-column
            width="220px"
            label="备注"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.cancel_remark"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <div class="dialog-btn-wrap">
      <!-- <span
        class="item"
        style="margin-right:20px">
        退款方式：
        <el-select
          v-model="cancel_pay_channel"
          ref="channelSelect"
          name="channel-select">
          <el-option
            value="现金"
            label="现金"
          ></el-option>
          <el-option
            v-if="info.payChannel!=='现金'"
            :value="info.payChannel"
            :label="info.payChannel"
          ></el-option>
        </el-select>
      </span> -->
      <p class="info-label">
        退票金额
      </p>
      共&nbsp;<div class="warning">
        <span class="strong">
          {{ cancelPrice }}
        </span>元
      </div>&emsp;

      <!-- 显示pos查询时，将之前的查询信息置空后再显示 -->
      <!-- <el-button
        type="danger"
        v-if="showPosQuery"
        @click="isRefundPosInfo=null,$refs.queryPos.show()">
        查询POS机交易
      </el-button> -->

      <el-button
        @click="isRefundPosInfo=null,submit()"
        :disabled="isRefunding"
        type="primary"
      >
        {{ isRefunding?'正在处理':'确认提交' }}
      </el-button>
    </div>

    <SalesList
      ref="salesList"
      :default-payment="info.payChannel"
      @change="handleGetSaleId"></SalesList>

    <QueryPos
      ref="queryPos"
      type="refund"
      :preorder-info="info.bocTradeNo"
      @confirm="handleQueryPos"></QueryPos>
  </el-dialog>
</template>

<script>
import { isJSON } from '@/utils'
import { getPayResponse } from '@/utils/posUtils'
import { apiOrder } from '@/api/order'
import { cancelValueCardOrder, cancelValueCardCheckedTicket } from '@/api/valueCard'
import posMixin from '@/pages/common/posMixin'
import SalesList from '../SalesList'
import choosePay from '@/utils/choosePay'
import QueryPos from '../../common/QueryPos'
import { refundPOS } from '@/api/pay'

const posPayArray = ['银行卡', '银联扫码', '银联钱包', '银联二维码', '支付宝', '微信', '龙支付']

export default {
  mixins: [posMixin],
  components: {
    SalesList,
    QueryPos
  },
  data () {
    return {
      isRefunding: false,
      visible: false,
      cancel_pay_channel: '',
      cancel_manager: '',
      isRefundPosInfo: null, // 银行已退款
      info: {}
    }
  },
  computed: {
    scenicName () {
      return this.$localStore.get('scenicName') || this.$store.state.user.scenicName
    },
    payChannelOptions () {
      return this.$store.state.app.payChannelOptions
    },
    totalCancelPrice () {
      return this.info.price
    },
    cancelPrice () {
      // 已取消的订单，传原订单价格进行pos退款
      // if (this.info.status === 'CANCELED') {
      //   return this.info.price
      // }
      return this.info.tickets ? this.info.tickets.filter(i => i.status !== 'CANCELED').reduce((init, item) => {
        return init + item.price
      }, 0).toFixed(2) : 0
    },
    // 显示pos查询按钮
    showPosQuery () {
      return (this.scenicName === '狼山景区' || this.scenicName === '军山景区') && this.info.payChannel && (this.info.payChannel.indexOf('中行') > -1 || posPayArray.indexOf(this.info.payChannel) > -1)
    }
  },
  methods: {
    show (data) {
      this.visible = true
      this.cancel_manager = null
      this.info = JSON.parse(JSON.stringify(data))
      this.cancel_pay_channel = this.info.payChannel
    },
    handleClose () {
      if (this.isRefunding) {
        this.$confirm('正在退款，是否强制退出？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$log.info('退款被强制终止。')
          this.visible = false
          this.isRefunding = false
          this.killAllPosProcess()
        }).catch(() => {})

        return
      }
      this.visible = false
      this.isRefunding = false
      this.killAllPosProcess()
    },
    handleGetSaleId ({ cancel_manager, cancel_pay_channel, cancel_password }) {
      this.cancel_manager = cancel_manager
      this.cancel_pay_channel = cancel_pay_channel
      this.cancel_password = cancel_password

      this.submit()
    },
    submit () {
      // 昭苏 强退已检票必填退票原因
      if (['昭苏'].includes(this.scenicName)) {
        if (this.info.tickets.some(v => !v.cancel_remark && v.status === 'USED')) {
          return this.$message.error('退已检票请填写退票原因')
        }
      }

      if (!this.cancel_manager) {
        this.$refs.salesList.show(this.info.managerId, this.info.status)
        return
      }

      let str = `<div>
        <p>订单号：${this.info.orderNo}</p>
        <p>退款金额：<b style="font-size: 20px;color:red">${this.cancelPrice}</b></p>
        <p>退款方式：<b style="font-size: 20px;color:red">${this.cancel_pay_channel}</b></p>
        <p style="${this.cancel_manager ? '' : 'display:none'}">售票员：<b style="font-size: 20px;color:red">${this.cancel_manager && this.cancel_manager.nickName}</b></p>
        <p>确认退票 ？</p>
      </div>`

      this.$confirm(str, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(async () => {
        this.params = JSON.parse(JSON.stringify(this.info))
        switch (true) {
          // 中行支付
          case this.cancel_pay_channel.indexOf('中行') > -1 || posPayArray.indexOf(this.cancel_pay_channel) > -1:
            // 设置可退金额
            this.params.price = this.cancelPrice

            // 有已退款信息时，直接取消订单
            if (this.isRefundPosInfo) {
              this.cancelOrder()
            } else {
              if (this.info.status !== 'CANCELED') {
                await this.cancelOrder(true)
              }
              this.handlePosPay(this.params)
            }
            break
            // 储值卡支付
          case this.cancel_pay_channel.indexOf('储值') > -1 && this.scenicName.indexOf('西宁') > -1:

            this.handleValueCardRefund()
            break
          // 其他
          default:
            this.cancelOrder()
        }
      }).catch(() => {
        this.cancel_manager = null
      })
    },
    // 储值卡退单
    handleValueCardRefund () {
      let { payChannel, changyi_valuecardNo, id, tickets } = this.info

      if (this.info.status === 'PART_USE' || this.info.status === 'COMPLETE') {
        let ticket = this.info.tickets.map(i => {
          return {
            id: i.id,
            cancelPrice: i.price,
            cancel_pay_channel: this.cancel_pay_channel,
            cancel_managerId: this.cancel_manager.id
          }
        })
        cancelValueCardCheckedTicket({
          cardNo: changyi_valuecardNo,
          cardVendor: 'CHANGYI',
          ticketList: ticket
        }).then(res => {
          this.$message.success('取消订单成功')
          this.$emit('updateList')
          this.handleClose()
        }).finally(() => {
          this.isRefunding = false
          this.cancel_manager = null
        })
        return
      }

      tickets.forEach(t => {
        t.cancelPrice = t.price
        t.cancel_pay_channel = payChannel
      })

      cancelValueCardOrder({
        cancelOrderInfo: {
          cancel_pay_channel: payChannel,
          id,
          tickets
        },
        cardNo: changyi_valuecardNo,
        cardVendor: 'CHANGYI'
      }).then(res => {
        this.$message.success('取消订单成功')
        this.$emit('updateList')
        this.handleClose()
      })
    },
    // pos机退单
    handlePosPay (params) {
      params.tickets = params.tickets.filter(i => i.status === 'WAIT_USE' || i.status === 'USED')
      this.$log.info('POS退款')
      this.isRefunding = true
      // 'C'代表消费，’R‘代表退货
      choosePay('refund', params, this).then(data => {
        if (data) {
          this.$log.info('POS退款成功')
          this.$message.success('退款成功')
          if (isJSON(data)) {
            params.bocTradeNo = data
            params.bocPosId = JSON.parse(data).terminal || JSON.parse(data).terminalID
            // 设置本地pos终端号
            this.refundPOS(params)
            this.$localStore.set('termId', params.bocPosId)
          } else {
            params.bocTradeNo = data
            params.bocPosId = getPayResponse(data).terminalNo
            this.refundPOS(params)
            this.$localStore.set('termId', params.bocPosId)
          }
        }
      }).finally(() => {
        this.isRefunding = false
        this.handleClose()
      })
    },
    refundPOS (params) {
      const paramsData = {
        list: params.tickets.map(i => { return { id: i.id } }),
        refund_info: params.bocTradeNo,
        refund_pos_id: params.bocPosId,
        type: 'TICKET'
      }

      this.$log.info('更新退款门票状态', paramsData)
      refundPOS(paramsData).then(res => {
        this.$emit('updateList')
      })
    },
    cancelOrder (isPosPay) {
      let posId = this.$localStore.get('termId') || ''

      if (this.info.status === 'PART_USE' || this.info.status === 'COMPLETE') {
        let ticket = this.info.tickets.filter(i => i.status !== 'CANCELED').map(i => {
          return {
            id: i.id,
            boc_cancel_pos_id: posId,
            cancelPrice: i.price,
            cancel_pay_channel: this.cancel_pay_channel,
            cancel_managerId: this.cancel_manager.id,
            cancel_password: this.cancel_password ? this.cancel_password : undefined,
            cancel_remark: i.cancel_remark
          }
        })
        return apiOrder('cancelCheckedTicket', {
          ticketList: ticket
        }).then(res => {
          this.$log.info('取消订单成功')
          this.$message.success('取消订单成功')
          this.$emit('updateList')
          if (!isPosPay) {
            this.isRefunding = false
            this.handleClose()
          }
        })
      }
      return apiOrder('cancelOrder', {
        id: this.info.id,
        cancel_pay_channel: this.cancel_pay_channel,
        tickets: this.info.tickets
          .filter(i => (i.status === 'WAIT_USE' || i.status === 'OUTOFDATE'))
          .map(t => {
            return {
              id: t.id,
              boc_cancel_pos_id: posId,
              cancelPrice: t.price,
              cancel_remark: t.cancel_remark,
              cancel_pay_channel: this.cancel_pay_channel,
              cancel_managerId: this.cancel_manager.id
            }
          })
      }).then(res => {
        this.$log.info('取消订单成功')
        this.$message.success('取消订单成功')

        // 更新旅行社余额
        this.info.payChannel === '旅行社余额' && (this.$store.dispatch('getAgencyList'))
        this.$emit('updateList')
        if (!isPosPay) {
          this.isRefunding = false
          this.handleClose()
        }
      })
    },
    handleQueryPos (posInfo) {
      console.log(posInfo)
      if ((posInfo.amount / 100).toFixed(2) !== this.cancelPrice) {
        this.$message.error('退款金额不一致。')
        return
      }
      this.isRefundPosInfo = posInfo
      this.submit()
    }
  },
  beforeDestroy () {
    this.killAllPosProcess()
  }
}
</script>
