<template>
  <el-dialog 
    title="退款" 
    :visible.sync="dialogVisible" 
    width="500px" 
    append-to-body 
    @open="handleOpen"
  > 
    <el-form :model="form" :rules="rules" ref="form" label-width="6em" v-loading="loading" size="small">
      <el-form-item label="退款金额" prop="amount">
        <el-input-number v-model="form.amount" :min="0" :max="canRefundAmount" placeholder="请输入退款金额" style="width: 100%;" />
      </el-form-item>
      <el-form-item label="退款原因" prop="reason">
        <el-input v-model="form.reason" type="textarea" placeholder="请输入退款原因" show-word-limit maxlength="200" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit">确认退款</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {getOrder, refundOrder} from '@/api/bst/order'

export default {
  props: {
    id: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showRefundDialog: false,
      detail: {},
      form: {},
      loading: false,
      rules: {
        amount: [
          { required: true, message: '请输入退款金额', trigger: 'blur' },
        ],
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    },
    // 可退款金额
    canRefundAmount() {
      let payAmount = this.detail.payAmount || 0;  
      let payRefunded = this.detail.payRefunded || 0;
      let payRefunding = this.detail.payRefunding || 0;
      return payAmount - payRefunded - payRefunding;
    }
  },
  methods: {
    getDetail() {
      this.loading = true;
      getOrder(this.id).then(response => {
        this.detail = response.data;
        this.form.amount = this.canRefundAmount;
      }).finally(() => {
        this.loading = false;
      });
    },
    handleOpen() {
      this.getDetail();
      this.reset();
    },
    reset() {
      this.form = {
        orderId: this.id,
        amount: 0,
        reason: null,
      };
      this.resetForm('form');
    },
    handleSubmit() {
      this.$refs.form.validate().then(() => {
        this.loading = true;
        refundOrder(this.form).then((response) => {
          if (response.code == 200) {
            this.$message.success('退款成功');
            this.dialogVisible = false;
            this.$emit('success');
          }
        }).finally(() => {
          this.loading = false;
        });
      });
    }


  }
}
</script>

<style lang="scss" scoped>

</style>