<template>
  <el-dialog title="商家代金券提现审核" :visible.sync="examineVisible" width="30%" :close-on-click-modal="false">
    <el-form ref="examineFormRef" :model="form" label-width="auto" :rules="rules">
      <el-form-item label="审核状态" prop="auditStatus">
        <el-radio-group v-model="form.auditStatus">
          <el-radio :label="2">通过</el-radio>
          <el-radio :label="3">不通过</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="form.auditStatus === 2" label="提现比例, 范围：0 ~ 40" prop="ratio" :rules="[{ validator: validateRatio, trigger: 'blur' }]">
        <el-input placeholder="请输入提现比例" v-model="form.ratio">
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="examineVisible = false">取 消</el-button>
      <el-button size="mini" type="primary" @click="handleSubmit" :loading="isLoading">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
// api docs: https://www.showdoc.com.cn/2068420669770919/11538603024917661
import { examineWithdrawalApplication } from '@/api/business'

export default {
  data() {
    return {
      examineVisible: false,
      form: {
        id: '',
        auditStatus: 2, // 1=已申请、2=审核通过、3=审核不通过
        ratio: '' // 提现比例，最高不能超过0.4， [0, 40]
      },
      rules: {
        auditStatus: [{ required: true, message: '请选择审核状态', type: 'number' }]
      },
      isLoading: false
    }
  },

  watch: {
    examineVisible(val) {
      if (!val) {
        this.reset()
      }
    }
  },

  methods: {
    open(row) {
      if (!row.id) {
        return this.$message.error('数据错误')
      }
      this.form.id = row.id
      this.examineVisible = true
    },

    validateRatio(rule, value, callback) {
      const number = Number(value)
      if (isNaN(number)) {
        callback(new Error('提现比例必须是数字'))
      } else if (!Number.isInteger(number)) {
        callback(new Error('必须是整数'))
      } else if (number <= 0 || number > 40) {
        callback(new Error('提现比例必须大于0且小于等于40'))
      } else {
        callback()
      }
    },

    async handleSubmit() {
      this.isLoading = true
      try {
        await this.$refs.examineFormRef.validate()
        const data = JSON.parse(JSON.stringify(this.form))
        data.ratio = (data.ratio / 100).toFixed(2)
        const res = await examineWithdrawalApplication(data)
        if (res.code == '200') {
          this.$message.success('审核成功')
          this.$emit('refresh')
          this.examineVisible = false
        }
      } finally {
        this.isLoading = false
      }
    },

    reset() {
      this.$refs.examineFormRef.resetFields()
      this.form.auditStatus = 2
      this.form.ratio = ''
    }
  }
}
</script>

<style lang="scss" scoped></style>
