<template>
  <el-dialog :model-value="visible" :width="width" title="退费" @close="close()">
    <el-scrollbar v-loading="loading" wrap-class="el-dialog-body-full-scroll">
      <div v-if="refundType" class="overflow-hidden p-15px">
        <el-form label-width="100px" label-position="left">
          <div v-if="refundType === 'goodsFee'" class="text-center text-dark-500 text-16px font-semibold">
             确定退药费<span class="text-red-500">（¥{{ order.goodsFee }}）</span>？
          </div>
          <template v-if="refundType === 'shippingFee'">
            <el-form-item class="is-required" label="退费项">
              <div>
                退运费<span class="ml-2 text-red-500">（{{ order.shippingFeeStr }}）</span>
              </div>
            </el-form-item>
            <el-form-item class="is-required" label="原因">
              <el-input v-model="reason" type="textarea" placeholder="请输入原因" resize="none"
                :autosize="{ minRows: 5, maxRows: 8 }" :maxlength="200" show-word-limit />
            </el-form-item>
          </template>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div text-center>
        <!-- <el-button plain class="w-100px" type="primary" @click="getDetail()">详情</el-button> -->
        <el-button plain class="w-100px" type="primary" @click="close()">取消</el-button>
        <el-button class="w-100px" :loading="loading" type="primary" @click="confirm()">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { computed, ref, watch } from "vue";
import { storeToRefs } from 'pinia';
import { ElMessage, ElMessageBox } from "element-plus";
import BigNumber from "bignumber.js";
import { refundWineOrderFee, refundWineOrderShippingFee, getRxMedicalWineOrder } from "@/api/hlw";
import { memberStore } from "@/store/member";

import { Refresh } from "@element-plus/icons-vue";

const emits = defineEmits(["close", "change", "replace"]);
const props = defineProps({
  order: { type: Object, default: () => ({}) },
  visible: { type: Boolean, default: false },
  width: { type: [String, Number], default: "500px" },
});

const { memberInfo } = storeToRefs(memberStore());
const loading = ref(false);
const refundType = ref('');
const reason = ref('');
const reloading = ref(false);

function close() {
  emits("close");
}

function getRefundType(order) {
  if (['paid', 'shipped'].includes(order.status)) return 'goodsFee';
  if ('goodsFeeRefunded' === order.status && order.payTime) return 'shippingFee';
  return ''
}

async function confirm() {
  if (loading.value) return;
  if (refundType.value === 'goodsFee') {
    refundGoodsFee()
  } else {
    refundShipping()
  }
}

async function getDetail() {
  const { success, message, data } = await getRxMedicalWineOrder({ id: props.order._id });
  if (data && data.data) {
    return data.data;
  }
  return null;
}

async function refundGoodsFee() {
  loading.value = true;
  const { success, message } = await refundWineOrderFee({
    id: props.order._id,
    orderNo: props.order.orderNo,
    operator: memberInfo.value.anotherName,
    operatorId: memberInfo.value.userid
  });
  loading.value = false;
  if (success) {
    ElMessage.success('退费成功')
  } else {
    ElMessage.error(message)
    return
  }
  loading.value = true;
  const detail = await getDetail();
  loading.value = false;
  if (detail) {
    const type = getRefundType(detail);
    if (type === 'shippingFee') {
      try {
        await ElMessageBox.confirm('退费成功，是否继续退运费？', '提示', { type: 'warning' });
        refundType.value = 'shippingFee';
        emits('replace', detail);
        return
      } catch (e) { }
    }
    emits('replace', detail);
    close();
  } else {
    close()
    emits('change')
  }
}

async function refundShipping() {
  const params = {
    id: props.order._id,
    orderNo: props.order.orderNo,
    operator: memberInfo.value.anotherName,
    operatorId: memberInfo.value.userid
  }
  if (reason.value.trim() === '') {
    return ElMessage.info('请填写取消原因')
  }
  params.reason = reason.value;
  loading.value = true;
  const { success, message } = await refundWineOrderShippingFee(params);
  loading.value = false;
  if (success) {
    ElMessage.success('退费成功')
  } else {
    ElMessage.error(message)
    return
  }
  const detail = await getDetail();
  close()
  if (detail) {
    emits('replace', detail)
  } else {
    emits('change')
  }
}

watch(
  () => props.visible,
  (n) => {
    if (n) {
      reloading.value = false;
      reason.value = ''
      refundType.value = getRefundType(props.order || {})
    }
  }
);
</script>