<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 === 'yb'" class="text-center text-dark-500 text-16px font-semibold">
            确定退药费+诊疗费<span class="text-red-500">（¥{{ ybFee }}）</span>？
          </div>
          <template v-if="refundType === 'zf'">
            <el-form-item class="is-required" label="退费项">
              <div>
                退运费<span class="ml-2 text-red-500">（{{order.shippingFeeStr }}）</span>
              </div>
            </el-form-item>
            <template v-if="order.shippingType==='fengniao'">
              <el-form-item class="is-required" label="取消角色">
                <el-radio-group v-model="role">
                  <el-radio label="1" value="1">商户取消</el-radio>
                  <el-radio label="2" value="2"> 用户取消</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item class="is-required" label="退费原因">
                <div class="flex-grow flex items-center">
                  <el-select v-model="cancelCode" class="flex-grow mr-2">
                    <el-option v-for="item in reasonList" :key="item.code" :label="item.name"
                      :value="item.code"></el-option>
                  </el-select>
                  <el-icon class="flex-shrink-0 text-blue-500 text-24px cursor-pointer flex-shrink-0"
                    :class="{'animate-spin': reloading}" @click="getReasonList()">
                    <Refresh />
                  </el-icon>
                </div>
              </el-form-item>
            </template>
            <el-form-item class="is-required" label="原因">
              <el-input v-model="reason" type="textarea" placeholder="请输入原因" resize="none"
                :autosize="{ minRows: 5, maxRows: 8 }" :maxlength="maxlength" show-word-limit />
            </el-form-item>
          </template>
        </el-form>
      </div>
    </el-scrollbar>
    <div v-if="isCancelFengniao && fengniaoErrorTip" class="text-center border-t pt-3 border-gray-200">
      <el-text>蜂鸟配送不可取消，原因：</el-text>
      <el-text class="text-red-500" type="danger">{{ fengniaoErrorTip }}</el-text>
    </div>
    <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 { getCancelReasons, preCancelFengniaoOrder, refundMedicinePurchaseOrderSelfFee, refundMedicinePurchaseOrderYbFee, getMedicinePurchaseOrderDetail } 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 cancelCode = ref('');
const reasonList = ref([]);
const role = ref('1');
const reloading = ref(false);
const fengniaoErrorTip = ref('');
const maxlength = computed(() => props.order.shippingType === 'fengniao' ? 20 : 200);
const isCancelFengniao = computed(() => {
  const isFengniao = props.order && props.order.shippingType === 'fengniao';
  return props.visible && isFengniao && refundType.value == 'zf'
})

const ybFee = computed(() => {
  const regFee = props.order && typeof props.order.regFee == 'number' ? props.order.regFee : 0;
  const drugFee = props.order && typeof props.order.drugFee == 'number' ? props.order.drugFee : 0;
  return new BigNumber(regFee).plus(drugFee).toNumber();
})

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

function getRefundType(order) {
  if (['ybPaid', 'shipped'].includes(order.status)) return 'yb';
  if ('ybFeeRefunded' === order.status && order.payTime) return 'zf';
  return ''
}

async function confirm() {
  if (loading.value) return;
  if (refundType.value === 'yb') {
    refundYbFee()
  } else {
    refundZfFee()
  }
}

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

async function refundYbFee() {
  loading.value = true;
  const { success, message } = await refundMedicinePurchaseOrderYbFee({
    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 === 'zf') {
      try {
        await ElMessageBox.confirm('退费成功，是否继续退运费？', '提示', { type: 'warning' });
        refundType.value = 'zf';
        emits('replace', detail);
        return
      } catch (e) { }
    }
    emits('replace', detail);
    close();
  } else {
    close()
    emits('change')
  }
}

async function refundZfFee() {
  const params = {
    id: props.order._id,
    orderNo: props.order.orderNo,
    operator: memberInfo.value.anotherName,
    operatorId: memberInfo.value.userid
  }
  if (props.order.shippingType === 'fengniao' && !reasonList.value.some(i => i.code === cancelCode.value)) {
    return ElMessage.info('请选择取消原因')
  }
  if (props.order.shippingType === 'fengniao' && !['1', '2'].includes(role.value)) {
    return ElMessage.info('请选择取消角色')
  }
  if (reason.value.trim() === '') {
    return ElMessage.info('请填写取消原因')
  }
  if (props.order.shippingType === 'fengniao') {
    params.cancelCode = cancelCode.value + '';
    params.role = role.value;
    await preCancel()
  }
  params.reason = reason.value;
  loading.value = true;
  const { success, message } = await refundMedicinePurchaseOrderSelfFee(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')
  }
}

async function getReasonList() {
  if (reloading.value) return;
  reloading.value = true;
  const { success, message, data } = await getCancelReasons(props.order.orderNo);
  reloading.value = false;
  reasonList.value = data && Array.isArray(data.data) ? data.data : [];
  if (success) {
    fengniaoErrorTip.value = ''
  } else {
    fengniaoErrorTip.value = message || '获取蜂鸟配送订单取消原因失败'
  }
}

async function preCancel() {
  loading.value = true;
  const { success, message, data } = await preCancelFengniaoOrder({ orderNo: props.order.orderNo, reasonCode: cancelCode.value });
  loading.value = false;
  if (success) {
    return true
  } else {
    ElMessage.error(message)
    return Promise.reject('')
  }
}

watch(
  () => props.visible,
  (n) => {
    if (n) {
      reloading.value = false;
      fengniaoErrorTip.value = '';
      cancelCode.value = '';
      role.value = '1';
      reason.value = ''
      refundType.value = getRefundType(props.order || {})
    }
  }
);
watch(isCancelFengniao, n => n && getReasonList())
</script>