<template>
  <el-container>
    <el-main>
      <el-form ref="formRef" :model="form.model" :rules="form.rules" label-width="80px">
        <el-form-item label="退款方式" prop="refund_type">
          <div>
            <el-radio-group v-model="form.model.refund_type">
              <el-radio label="back">原路退回</el-radio>
              <el-radio label="money">退回余额</el-radio>
            </el-radio-group>
            <div v-if="props.modal.params.type != 'order.refund'" class="tip">
              将全额退款，并且退回库存减少销量
            </div>
          </div>
        </el-form-item>
        <el-form-item
          label="退款金额"
          prop="refund_money"
          v-if="props.modal.params.type == 'order.refund'"
        >
          <div>
            <el-input
              v-model="form.model.refund_money"
              :placeholder="`建议退款金额${modal.params.data.suggest_refund_fee}元`"
            />
            <div class="tip sa-m-t-16"> 退款时请与买家协商好，退款之后不可撤回 </div>
          </div>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button type="primary" @click="confirm">确定</el-button>
    </el-footer>
  </el-container>
</template>
<script setup>
  import { reactive, ref, unref } from 'vue';
  import { api } from '../order.service';

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps(['modal']);

  const formRef = ref();
  const form = reactive({
    model: {
      refund_type: 'back',
      refund_money: '',
    },
    rules: {
      refund_money: [{ required: true, message: '请输入退款金额', trigger: 'blur' }],
    },
  });

  function confirm() {
    unref(formRef).validate(async (valid) => {
      if (!valid) return;
      if (valid) {
        if (props.modal.params.type == 'order.fullRefund') {
          const { code } = await api.order.fullRefund(props.modal.params.data.id, {
            refund_type: form.model.refund_type,
          });
          if (code == '200') {
            emit('modalCallBack', { event: 'confirm' });
          }
        }

        if (props.modal.params.type == 'order.refund') {
          const { code } = await api.order.refund(
            props.modal.params.data.id,
            props.modal.params.data.item_id,
            {
              refund_type: form.model.refund_type,
              refund_money: form.model.refund_money,
            },
          );
          if (code == '200') {
            emit('modalCallBack', { event: 'confirm' });
          }
        }
      }
    });
  }
</script>
<style lang="scss">
  .el-dialog.refund-dialog {
    --el-dialog-width: 500px;
  }
</style>
