<template>
  <div class="app-container">
    <div class="filter-container">
      <span style="font-size: 20px;font-weight: bold;">平台代金券种类：</span>
      <el-select
        :value="voucherChooseInfo.platformVoucherId" clearable size="medium" class="filter-item"
        style="width: 200px;margin-left: 10px;" placeholder="请选择平台代金券种类" @change="handleVoucherItemSelect"
      >
        <el-option
          v-for="item in platformVoucherList" :key="item.id"
          :label="`${item.voucherName}（${item.platformVoucherId}）`" :value="item.platformVoucherId"
          style="height: auto;border-bottom: 1px solid #8492a6;"
        >
          <div style="display: flex;align-items: center;">
            <div style="margin-right: 4px;">{{ `${item.voucherName}（${item.platformVoucherId}）` }}</div>
            <div style="font-size: 13px;color: #8492a6;">
              <div>购买比例：{{ item.purchaseRatio }}：1</div>
              <div>抵扣比例：{{ item.paymentRatio }}：1</div>
            </div>
          </div>
        </el-option>
      </el-select>
    </div>
    <el-card style="margin-bottom: 10px;">
      <h2>代金券</h2>
      <div style="display: flex;justify-content: space-around;align-items: center;font-size: 20px;text-align: center;">
        <div>
          <div style="font-size: 28px;font-weight: bold;color: #c5c900;">{{ voucherAcount.chongzhiRechargeTotal }}</div>
          <div style="margin-top: 10px;">充值代金券</div>
        </div>
        <div>
          <div style="font-size: 28px;font-weight: bold;color: #c5c900;">{{ voucherAcount.duihuanRechargeTotal }}</div>
          <div style="margin-top: 10px;">兑换代金券</div>
        </div>
      </div>
    </el-card>

    <el-card style="margin-bottom: 10px;">
      <h2>转赠</h2>
      <el-form
        ref="transferDataForm" :model="transferFormData" :rules="transferFormRules" size="mini"
        label-suffix=":"
        label-width="200px"
      >
        <el-form-item label="代金券类型" prop="shelveState">
          <el-radio-group v-model="transferFormData.voucherType">
            <el-radio label="1">充值代金券</el-radio>
            <el-radio label="2">兑换代金券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户ID（被赠与方）" prop="buyerUserId">
          <el-input
            v-model="transferFormData.buyerUserId" clearable size="mini" type="number"
            style="width: 200px;"
            placeholder="请输入转赠用户ID"
          />
        </el-form-item>
        <el-form-item label="数量" prop="number">
          <el-input
            v-model="transferFormData.number" clearable size="mini" type="number"
            style="width: 200px;"
            placeholder="请输入代金券数量"
          />
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="handleTransfer">
          转赠
        </el-button>
      </div>
    </el-card>

    <el-card style="margin-bottom: 10px;">
      <h2>充值</h2>
      <el-form
        ref="rechargeDataForm" :model="rechargeFormData" :rules="rechargeFormRules" size="mini"
        label-suffix=":"
        label-width="200px"
      >
        <div>
        </div>
        <el-form-item label="数量" prop="number">
          <el-input
            v-model="rechargeFormData.number" clearable size="mini" type="number"
            style="width: 250px;"
            placeholder="请输入代金券数量"
          >
            <template #append>
              <span v-if="rechargeFormData.number">售价{{ rechargeFormData.number / 2 }}元</span>
              <span v-else>代金券</span>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="showPayTypePopup = true">
          充值
        </el-button>
      </div>
    </el-card>

    <el-dialog
      :visible.sync="showPayTypePopup"
      v-bind="{ closeOnClickModal: false, width: '420px', title: '支付方式选择' }"
    >
      <div v-if="showPayTypePopup" style="padding: 10px 0 14px;">
        <CashierList
          :price-pay="rechargeFormData.number / 2" show
          @change="(e) => payInfo = e"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="showPayTypePopup = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="handleRecharge">确认支付</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import CashierList from '@/components/CashierList'
import { getAllPlatformVoucher, getByUserOrderShopVoucher, getShopTotalShopVoucher, updateTransferRechargeShopVoucher, updateTransferExchangeShopVoucher, submitShopVoucherEntryRecord } from '@/api/voucherManagement/voucherOperation'
import { handleDoPay } from '../../../utils/payUtil'

export default {
  name: 'VoucherOperation',
  components: {
    CashierList
  },
  data() {
    return {
      platformVoucherList: [],
      // 选择的代金券种类
      voucherChooseInfo: {
        platformVoucherId: ''
      },
      // 账户数据
      voucherAcount: {
        chongzhiRechargeTotal: 0,
        duihuanRechargeTotal: 0
      },
      // 表单数据
      transferFormData: {
        voucherType: '1',
        buyerUserId: '',
        number: ''
      },
      transferFormRules: {
        voucherType: [ { required: true, message: '请选择代金券类型' } ],
        buyerUserId: [ { required: true, message: '被赠与方id不能为空', trigger: 'blur' } ],
        number: [ { required: true, message: '数量不能为空', trigger: 'blur' } ]
      },
      rechargeFormData: {
        voucherId: '',
        number: '',
        payGrade: ''
      },
      rechargeFormRules: {
        number: [ { required: true, message: '数量不能为空' } ]
      },
      showPayTypePopup: false,
      payInfo: {}
    }
  },
  created() {
    this.initData()
  },
  methods: {
    async initData() {
      await this.getPlatformVoucherList()
    },
    async getPlatformVoucherList() {
      const loading = this.$loading({ text: '加载中' })
      const res = await getAllPlatformVoucher({ page: 1, pageSize: 9999 })
      this.platformVoucherList = res.data.list
      if (this.platformVoucherList && this.platformVoucherList.length) {
        this.handleVoucherItemSelect(this.platformVoucherList[0].platformVoucherId)
      }
      loading.close()
    },
    // 平台代金券选择
    async handleVoucherItemSelect(id) {
      if (this.voucherChooseInfo.platformVoucherId === id) return
      this.voucherChooseInfo.platformVoucherId = id
      if (this.voucherChooseInfo.platformVoucherId) {
        const res1 = await getByUserOrderShopVoucher({ page: 1, pageSize: 9999 })
        this.voucherAcount.chongzhiRechargeTotal = Number(res1.data.voucherTotal)
        const res2 = await getShopTotalShopVoucher({ page: 1, pageSize: 9999 })
        this.voucherAcount.duihuanRechargeTotal = Number(res2.data.voucherTotal)
      }
    },
    handleTransfer() {
      this.$refs.transferDataForm.validate(async (valid) => {
        if (valid) {
          const loading = this.$loading({ text: '提交中，请稍候……' })
          try {
            const { ...otps } = this.transferFormData
            const params = {
              ...otps
            }
            let _url
            if (this.transferFormData.voucherType === '1') {
              _url = updateTransferRechargeShopVoucher
            } else if (this.transferFormData.voucherType === '2') {
              _url = updateTransferExchangeShopVoucher
            }
            await _url(params)
            loading.close()
            this.$message({ message: `操作成功!`, type: 'success' })
            this.$refs.transferDataForm && this.$refs.transferDataForm.resetFields()
          } catch (e) {
            loading.close()
          } finally {
            loading.close()
          }
        } else {
          this.$message({ message: '请输入相关信息', type: 'warning' })
          return false
        }
      })
    },
    handleRecharge() {
      if (!this.voucherChooseInfo.platformVoucherId) return this.$message({ message: '缺少代金券种类', type: 'warning' })
      this.$refs.rechargeDataForm.validate(async (valid) => {
        if (valid) {
          const loading = this.$loading({ text: '提交中，请稍候……' })
          try {
            const { number, ...otps } = this.rechargeFormData
            const params = {
              ...otps,
              voucherId: this.voucherChooseInfo.platformVoucherId,
              number,
              payGrade: number / 2
            }
            const res = await submitShopVoucherEntryRecord(params)
            await handleDoPay({ ...res.data, ...this.payInfo }, 4, '')
            loading.close()
            this.$message({ message: `充值成功！`, type: 'success' })
            this.$refs.rechargeDataForm && this.$refs.rechargeDataForm.resetFields()
          } catch (e) {
            loading.close()
          } finally {
            loading.close()
          }
        } else {
          this.$message({ message: '请输入相关信息', type: 'warning' })
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
	padding: 20px;
	display: flex;
	flex-direction: column;

	.filter-container {
		.filter-item {
			display: inline-block;
			vertical-align: middle;
			margin-bottom: 10px;
		}
	}
}
</style>
