<template>
  <el-form
    class="container"
    ref="form"
    :model="form"
    :inline="true"
    label-width="120px">
    <el-card
      shadow="hover"
      style="margin-bottom:10px"
      class="top-block form-wrap">
      <div slot="header">
        基本信息
      </div>
      <el-alert
        style="margin-bottom:10px"
        v-if="form.discount-0>10"
        title="警告：当前设置的价格已大于原始价格"
        type="warning">
      </el-alert>

      <el-form-item
        verify
        prop="salesperson"
        label="销售">
        <el-input v-model="form.salesperson">
        </el-input>
      </el-form-item>

      <el-form-item
        verify
        prop="total_money"
        label="出库单价">
        <el-input-number
          @change="handlePriceChange"
          :min="0"
          :precision="2"
          :controls="false"
          v-model="form.price">
        </el-input-number>
      </el-form-item>

      <el-form-item
        verify
        prop="discount"
        label="出库折扣">
        <el-input-number
          @change="handleDiscountChange"
          v-model="form.discount"
          :controls="false"
          :step="0.1"
          :min="0"
          :precision="1"></el-input-number>
      </el-form-item>

      <el-form-item
        verify
        prop="activate_end_time"
        label="激活截止日期">
        <el-date-picker
          style="width:194px"
          :editable="false"
          :clearable="false"
          v-model="form.activate_end_time"
          value-format="yyyy-MM-dd"
          type="date"
          :picker-options="dateOption"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item
        verify
        label="渠道"
        prop="channel">
        <el-select
          style="width:200px"
          @change="handleChannelChange"
          v-model="form.channel">
          <el-option
            label="线上"
            value="线上">
          </el-option>
          <el-option
            label="散客"
            value="散客">
          </el-option>
          <el-option
            label="团客"
            value="团客">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="客户类型"
        prop="channel">
        <el-select
          style="width:200px"
          v-model="form.customerType">
          <el-option
            v-for="item in customerType"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="备注"
        prop="remark">
        <el-input v-model="form.remark"></el-input>
      </el-form-item>

      <el-form-item
        verify
        can-be-empty
        label="会员类型">
        <span class="text"><b>{{ (cardType&&cardType.name) || '无' }}</b></span>
      </el-form-item>

      <el-form-item label="出库数量">
        <span class="text"><b>{{ cardList.length }}</b></span>
      </el-form-item>

      <el-form-item
        label="线上会员订单"
        v-if="form.channel==='线上'"
        verify
        prop="currentOrder"
        style="width:100%">
        <el-button
          type="primary"
          @click="$refs.ticketNoSelector.show()">
          请选择
        </el-button>
        <span
          class="warning"
          style="margin-left:20px">建议出库价格填0，否则将会重复计算收益</span>
      </el-form-item>

      <el-table
        border
        ref="table"
        v-if="form.currentOrder"
        :data="form.currentOrder">
        <el-table-column
          width="180"
          prop="orderNo"
          label="订单号">
        </el-table-column>
        <el-table-column
          prop="otaSourceName"
          label="分销商">
        </el-table-column>
        <el-table-column
          label="票种">
          <template slot-scope="scope">
            {{ scope.row.tickets[0].tname }}
          </template>
        </el-table-column>
        <el-table-column
          width="80"
          prop="tickets.length"
          label="票数量">
        </el-table-column>
        <el-table-column
          width="100"
          prop="buyerName"
          label="预订人">
        </el-table-column>
        <el-table-column
          width="120"
          prop="buyerPhone"
          label="预订手机">
        </el-table-column>
        <el-table-column
          label="证件号码">
          <template slot-scope="scope">
            {{ scope.row.buyerIdentifyType | paperType }}
          &nbsp;
            {{ scope.row.buyerIdentify }}
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          label="售票时间">
          <template slot-scope="scope">
            {{ scope.row.createTime | formatTime }}
          </template>
        </el-table-column>
        <el-table-column
          width="80"
          label="总价">
          <template slot-scope="scope">
            {{ scope.row.tickets.length * scope.row.tickets[0].price }}
          </template>
        </el-table-column>
        <el-table-column
          width="120"
          label="取票码">
          <template slot-scope="scope">
            {{ scope.row.tickets[0].selfservice_code }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card
      header="订单明细"
      style="margin-bottom:10px">
      <div class="pay-channel-wrap">
        <label class="text">支付方式：</label>
        <el-radio-group
          border
          fill="#379143"
          class="tags-btn"
          v-model="form.payChannel">
          <el-radio
            border
            v-for="val in payChannelOptions"
            :key="val"
            :value="val"
            :label="val"></el-radio>
        </el-radio-group>
      </div>
      <div class="btn-wrap">
        <div>
          <span class="item price">总数：<b>{{ cardList.length }}</b> 张</span>
          <span class="item price">总价：<b>{{ totalMoney }}</b> 元</span>
        </div>
        <el-button
          type="primary"
          size="medium"
          class="warn-btn"
          :disabled="submitDisable"
          @click="handleConfirm">
          {{ submitDisable?'正在处理':'确认出库' }}
        </el-button>
      </div>
    </el-card>

    <Confirm
      ref="confirm"
      :member-type="cardType&&cardType.name"
      @submit="handleSubmit"></Confirm>

    <ReadValueCard
      ref="readValueCard"
      @getInfo="handleValueCardPay"
      @close="submitDisable=false"></ReadValueCard>
    <PosQrCodeReader
      ref="posQrCodeReader"
      @getQrcode="handleSubmit"></PosQrCodeReader>
    <XSCQrCodeReader
      ref="XSCQrCodeReader"
      @getQrcode="handleSubmit"></XSCQrCodeReader>

    <TicketNoSelector
      ref="ticketNoSelector"
      @select="form.currentOrder=$event"></TicketNoSelector>
  </el-form>
</template>

<script>
import moment from 'moment'
import Confirm from './Confirm'
import TicketNoSelector from './TicketNoSelector'
import { getMemberTradeList, iccardStorageSell } from '@/api/member'

import { valueCardMemberStorageSell } from '@/api/valueCard'

import ReadValueCard from '@/pages/sellManage/common/ReadValueCard'
import posMixin from '@/pages/common/posMixin'
import { debounce } from 'throttle-debounce'
import handlePay from '@/pages/sellManage/common/handlePay'

export default {
  mixins: [posMixin],
  props: {
    cardList: {
      type: Array,
      default: () => []
    },
    cardType: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    Confirm,
    ReadValueCard,
    TicketNoSelector
  },
  computed: {
    showPosQrcode () {
      // 需要手动扫码的景区
      const list = ['东方绿舟', '天津之眼', '绿博园']

      if (this.scenicName === '绿博园' && (!this.$localStore.get('posName') || this.$localStore.get('posName') === 'jianhang')) {
        return false
      }

      return list.indexOf(this.scenicName) > -1
    },
    scenicName () {
      return this.$localStore.get('scenicName') || this.$store.state.user.scenicName
    },
    customerType () {
      return this.$store.state.app.customerType
    },
    originPrice () {
      return this.cardType ? this.cardType.capital : 0
    },
    originTotal () {
      return this.cardType ? this.cardList.length * this.cardType.capital : 0
    },
    payChannelOptions () {
      return this.$store.state.app.payChannelOptions
    },
    totalMoney () {
      return this.form.price * this.cardList.length
    },
    ticketNoList () {
      if (this.form.currentOrder) {
        return this.form.currentOrder[0].tickets.map(i => i.ticketNo)
      } else {
        return []
      }
    }
  },
  data () {
    return {
      submitDisable: false,
      confirmData: null,
      payStatus: 0, // 支付状态
      createOrderStatus: 0, // 创建订单状态
      orderTempInfo: {}, // 临时订单信息，防止重复创建订单
      timer: null, // 检查订单是否支付成功计时器
      form: {
        price: 0,
        remark: '',
        channel: '',
        customerType: '',
        activate_end_time: moment().add('day', 30).toDate(),
        total_money: 0,
        discount: 10,
        salesperson: '',
        payChannel: '',
        currentOrder: ''
      },
      dateOption: {
        disabledDate (theTime) {
          let startTime = moment().format('YYYY-MM-DD') + ' 00:00:00'
          return moment(theTime).isBefore(startTime)
        }
      }
    }
  },
  methods: {
    moment,
    handleChannelChange (e) {
      if (e !== '线上') {
        this.form.currentOrder = null
      }
    },
    handlePriceChange (e) {
      this.form.discount = (this.form.price / this.originPrice * 10).toFixed(1)
    },
    handleTotalChange (e) {
      this.form.discount = (this.form.total_money / this.originTotal * 10).toFixed(1)
    },
    handleDiscountChange (e) {
      this.form.price = (this.originPrice * this.form.discount / 10).toFixed(2)
    },
    handleSubmit: debounce(1000, true, function (qrcode, cardInfo) {
      if (this.confirmData.payChannel.indexOf('储值卡') > -1 && this.scenicName === '西宁景区') {
        this.$refs.readValueCard.show(this.confirmData)
        return
      }
      // 是否使用外部扫码
      if (this.confirmData.payChannel === '聚合扫码' && !qrcode && this.showPosQrcode) {
        this.$refs.posQrCodeReader.show()
        return
      }
      const scanArr = ['中旅银行', '瑞通储值卡', '建行B扫C', '银联B扫C', '支付宝B扫C', '微信B扫C']
      // 是否使用外部扫码
      if (scanArr.indexOf(this.confirmData.payChannel) > -1 && !qrcode) {
        iccardStorageSell(this.confirmData).then(res => {
          this.$log.warn('散客下单成功')
          this.createOrderStatus = 1
          this.orderTempInfo = res
          this.$refs.XSCQrCodeReader.show(this.confirmData.iccardList, this.confirmData.payChannel)
        })
        return
      }
      // 防止重复提交
      if (this.submitDisable) return
      this.submitDisable = true
      // 支付已成功只提交订单
      if (this.payStatus === 1) {
        this.iccardStorageSell(this.confirmData)
        return
      }
      this.params = JSON.parse(JSON.stringify(this.confirmData))
      this.params.price = this.confirmData.total_money
      this.params.qrCode = qrcode
      this.iccardStorageSell()
    }),
    iccardStorageSell () {
      this.submitDisable = true
      if (this.createOrderStatus === 1) {
        handlePay(this.params, this.orderTempInfo, this, () => {})
        if (this.payStatus !== 1) {
          this.getSingleMember(this.orderTempInfo, this.params)
        }
      } else {
        iccardStorageSell(this.confirmData).then(res => {
          this.$message.success('操作成功')
          this.createOrderStatus = 1
          this.orderTempInfo = res
          handlePay(this.params, res, this, () => {})
          if (this.payStatus !== 1) {
            this.getSingleMember(res, this.params)
          }
        }).catch(e => {
          this.submitDisable = false
        })
      }
    },

    getSingleMember (res, params) {
      getMemberTradeList({ keyWords7: res?.data }).then(order => {
        if (order.list[0] && order.list[0].pay_status === 'PAYED') {
          this.timer && window.clearTimeout(this.timer)
          this.handleCreateSuccess(params, res)
          this.$log.info('会员出库成功')
        } else if (order.list[0] && order.list[0].pay_status === 'CLOSED') {
          this.timer && window.clearTimeout(this.timer)
          this.$message.error('交易失败，订单关闭，请重新创建订单')
          this.$log.warn('会员出库失败，支付已关闭')
          this.submitDisable = false
        } else {
          this.timer = setTimeout(() => {
            this.getSingleMember(res, params)
          }, 2000)
        }
      })
    },
    handleCreateSuccess (params, res) {
      this.$message.success('出库成功')
      this.submitDisable = false
      this.reset()

      // this.$emit('complete')
    },
    handleValueCardPay (cardInfo) {
      console.log('储值卡信息', cardInfo)

      valueCardMemberStorageSell({
        cardNo: cardInfo.cardCode,
        cardVendor: 'CHANGYI',
        memberStorageSellLog: this.confirmData
      }).then(res => {
        this.$refs.readValueCard.visible = false
        this.reset()
      }).finally(e => {
        this.submitDisable = false
      })
    },
    reset () {
      this.$refs.form.resetFields()
      this.form.currentOrder = ''
      this.confirmData = null
      this.$emit('clear')
    },
    handleConfirm () {
      if (this.cardList.length === 0) {
        this.$message.error('IC卡列表为空，请添加IC卡')
        return
      }

      if (!this.form.currentOrder && this.form.channel === '线上') {
        this.$message.error('请选择线上会员订单')
        return
      }

      if (this.form.channel === '线上' && (this.form.currentOrder && this.form.currentOrder[0].tickets.length) !== this.cardList.length) {
        this.$message.error('会员卡数量与订单不符')
        return
      }

      this.$refs.form.validate((valid) => {
        if (valid) {
          // console.log(params)
          this.form.total_money = this.totalMoney
          const { channel, customerType, discount, total_money, salesperson, payChannel, remark, price } = this.form
          const iccardList = this.cardList.map(i => i.iccard)

          this.confirmData = {
            activate_end_time: moment(this.form.activate_end_time).hours(23).minutes(59).seconds(59).toDate(),
            discount,
            total_money,
            salesperson,
            iccardList,
            payChannel,
            remark,
            price,
            channel,
            customerType,
            ticketNoList: this.ticketNoList,
            number: iccardList.length
          }

          console.log(this.confirmData)

          this.payStatus = 0
          this.createOrderStatus = 0
          this.$refs.confirm.show(this.confirmData)
        }
      })
    }
  },
  watch: {
    originPrice (val) {
      // this.form.price = val
      this.handlePriceChange()
    },
    payChannelOptions: {
      handler (val) {
        if (val.length > 0) {
          this.form.payChannel = val[0]
        }
      },
      immediate: true
    }
  },
  beforeDestroy () {
    this.killAllPosProcess()
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;  height: 100%; flex-direction: column;
  ::v-deep .el-input-number,.el-date-editor {
    width: 200px;
  }
  .top-block {
    flex: 1;
  }
}

.block-title {
  margin-bottom: 20px;
}

.item {
  margin-left: 20px;
}
.price-info {
  padding: 10px 0;  text-align: right; background: #fff;
}
.btn-wrap {
  display: flex; width: 100%; margin-bottom: 10px; font-size: 14px; justify-content: space-between; align-items: center;

  .el-input {
    display: inline-block; width: 100px;
  }
}
.card-title {
  margin-bottom: 20px; font-size: 16px;
}

</style>
