<script setup lang="ts">
import { computed, ref, useTemplateRef } from 'vue';
import dayjs from 'dayjs';
import { fetchGetNomalOrderInfo } from '@/service/api/delivery/normal-orde';
import { useAppStore } from '@/store/modules/app';
import { copyTextToClipboard } from '@/utils/zt';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
import { closeStatus, dvyStatus, orderColumns, orderStatusEnum } from '../normal-order';
import DeliveryModal from './delivery-modal.vue';
const [registerModal, { openModal, setModalLoading }] = useModal({
  title: '订单详情',
  isShowHeaderText: false,
  showFooter: false,
  width: 1200,
  height: 800
});
const orderInfo = ref<Api.delivery.deliveryOrder>();
const appStore = useAppStore();
const TimeDown = ref<number>(0);
const ShipmentRef = useTemplateRef('Shipment');
const emit = defineEmits<{
  (e: 'finish'): void;
}>();
async function open(orderNumber: string) {
  openModal();
  setModalLoading(true);
  const { data, error } = await fetchGetNomalOrderInfo(orderNumber);
  if (!error) {
    orderInfo.value = data;
    if (orderInfo.value.hbLogisticStatus == orderStatusEnum.WAIT_PAY) {
      const createTime = dayjs(orderInfo.value.createTime);
      const currentTime = dayjs();
      const elapsed = currentTime.diff(createTime);
      const fifteenMinutesInMillis = 15 * 60 * 1000;
      TimeDown.value = fifteenMinutesInMillis - elapsed;
    }
  }
  setModalLoading(false);
}
defineExpose({ open });
function handleFinish() {
  open(String(orderInfo.value?.orderNumber));
  emit('finish');
}
const isRefund = computed(() => {
  const goodsData = orderInfo.value?.orderItems?.find(it => it.refundIngCount == 1);
  return Boolean(goodsData);
});
function handleShipment() {
  if (isRefund.value) {
    window.$message?.error('当前订单正在申请退款中');
    return;
  }
  ShipmentRef.value?.handleOpenOrder(String(orderInfo.value?.orderNumber));
}

const currentSteps = computed(() => {
  switch (orderInfo.value?.hbOrderStatus) {
    case orderStatusEnum.WAIT_PAY:
      return 1;
    case orderStatusEnum.ORDER_ACCEPT:
      return 2;
    case orderStatusEnum.ORDER_WAIT_DELIVERY:
      return 2;
    case orderStatusEnum.WAIT_DELIVERY:
      return 2;
    case orderStatusEnum.ORDER_DELIVERY:
      return 3;
    case orderStatusEnum.ORDER_ARRIVE:
      return 3;
    case orderStatusEnum.ORDER_COMPLETE:
      return 4;
    default:
      return 1;
  }
});
function handleCopy() {
  copyTextToClipboard(String(orderInfo.value?.orderNumber));
}
</script>

<template>
  <div>
    <BasicModal @register="registerModal" @after-leave="orderInfo = undefined">
      <div v-if="orderInfo">
        <NFlex justify="space-between" align="center">
          <NFlex>
            <NTag>
              <div class="flex items-center">
                订单编号: {{ orderInfo?.orderNumber }}
                <div @click="handleCopy">
                  <SvgIcon icon="bxs:copy" class="mx-3 cursor-pointer text-[#f97316]"></SvgIcon>
                </div>
              </div>
            </NTag>
            <NTag>下单时间: {{ orderInfo?.createTime }}</NTag>
          </NFlex>
          <NFlex vertical>
            <template v-if="orderInfo.hbOrderStatus == orderStatusEnum.WAIT_PAY">
              <div class="text-16px font-semibold">商品已拍下,等待买家付款</div>
              <div class="text-gray">
                如买家未在
                <NTag :type="TimeDown > 300094 ? 'success' : 'error'">
                  <NCountdown :duration="TimeDown" @finish="handleFinish" />
                </NTag>
                内付款，订单将 自动关闭。
              </div>
            </template>
            <template v-if="!orderInfo.dvyFlowId">
              <template
                v-if="
                  orderInfo.hbOrderStatus == orderStatusEnum.WAIT_DELIVERY ||
                  orderInfo.hbOrderStatus == orderStatusEnum.ORDER_ACCEPT ||
                  orderInfo.hbOrderStatus == orderStatusEnum.ORDER_DELIVERY
                "
              >
                <div class="text-16px font-semibold">等待商家发货</div>
                <NButton size="small" type="primary" @click="handleShipment">发货</NButton>
              </template>
            </template>
            <template v-if="orderInfo.hbOrderStatus == orderStatusEnum.ORDER_ARRIVE">
              <div class="text-16px font-semibold">等待买家收货</div>
              <div>商家已发货，等待确认收货</div>
            </template>
            <template v-if="orderInfo.hbOrderStatus == orderStatusEnum.ORDER_CANCEL">
              <div class="text-16px font-semibold">已取消</div>
              <div>取消原因：{{ closeStatus[orderInfo.closeType as keyof typeof closeStatus] || '未知取消原因' }}</div>
            </template>
            <template v-if="orderInfo.hbOrderStatus == orderStatusEnum.ORDER_COMPLETE">
              <div class="text-16px font-semibold">交易成功</div>
              <div>买家已收货</div>
            </template>
          </NFlex>
        </NFlex>
        <NDivider />
        <template v-if="orderInfo.hbOrderStatus != orderStatusEnum.ORDER_CANCEL">
          <div class="p3">
            <NSteps :current="currentSteps" :vertical="appStore.isMobile">
              <NStep title="用户下单" :description="orderInfo.createTime" />
              <NStep title="买家已付款" :description="orderInfo.payTime" />
              <NStep title="卖家已发货" :description="orderInfo.dvyTime" />
              <NStep title="买家已收货" :description="orderInfo.finallyTime" />
            </NSteps>
          </div>
          <NDivider />
        </template>
        <NDescriptions bordered :column="appStore.isMobile ? 1 : 4">
          <NDescriptionsItem label="收货人信息">
            <div>收货人姓名：{{ orderInfo?.userAddrOrder?.receiver || '---' }}</div>
            <div>收货人手机号：{{ orderInfo?.userAddrOrder?.mobile || '---' }}</div>
            <div>收货地址：{{ orderInfo?.userAddrOrder?.address || '---' }}</div>
          </NDescriptionsItem>
          <NDescriptionsItem label="配送信息">
            <div>配送方式: {{ dvyStatus[orderInfo.dvyType as keyof typeof dvyStatus] || '暂无' }}</div>
          </NDescriptionsItem>
          <NDescriptionsItem label="付款信息">
            <div>实付金额：{{ orderInfo.actualTotal }}元</div>
            <div>
              付款方式：{{
                orderInfo.hbOrderStatus == orderStatusEnum.WAIT_PAY ||
                orderInfo.hbOrderStatus == orderStatusEnum.ORDER_CANCEL
                  ? '暂无'
                  : '微信'
              }}
            </div>
            <div>付款时间：{{ orderInfo.payTime || '暂无' }}</div>
          </NDescriptionsItem>
          <NDescriptionsItem label="买家信息">
            <div>买家昵称：{{ orderInfo?.nickName || '---' }}</div>
            <div>买家电话：{{ orderInfo?.userMobile || '---' }}</div>
            <div>买家留言：{{ orderInfo?.remarks || '暂无' }}</div>
          </NDescriptionsItem>
        </NDescriptions>
        <NDivider />
        <NCard title="订单信息" :bordered="false">
          <NDataTable :columns="orderColumns" :data="orderInfo.orderItems" :bordered="false" />
        </NCard>
        <NCard title="费用信息" :bordered="false">
          <NTable :single-line="false">
            <NThead>
              <NTr>
                <NTh>费用类型</NTh>
                <NTh>金额/元</NTh>
              </NTr>
            </NThead>
            <NTbody>
              <NTr>
                <NTd>商品总额</NTd>
                <NTd>{{ orderInfo.total }}</NTd>
              </NTr>
              <NTr>
                <NTd>配送费（快递）</NTd>
                <NTd>{{ orderInfo.freightAmount }}</NTd>
              </NTr>
              <NTr>
                <NTd>积分</NTd>
                <NTd>-{{ (Number(orderInfo.offsetPoints) / 100).toFixed(2) || 0 }}</NTd>
              </NTr>
              <NTr>
                <NTd v-if="orderInfo.hbOrderStatus == orderStatusEnum.WAIT_PAY">需付款</NTd>
                <NTd
                  v-if="
                    orderInfo.hbOrderStatus != orderStatusEnum.WAIT_PAY &&
                    orderInfo.hbOrderStatus != orderStatusEnum.ORDER_CANCEL
                  "
                >
                  实际付款
                </NTd>
                <NTd v-if="orderInfo.hbOrderStatus == orderStatusEnum.ORDER_CANCEL">应付款</NTd>
                <NTd>{{ orderInfo.actualTotal }}</NTd>
              </NTr>
            </NTbody>
          </NTable>
        </NCard>
      </div>
    </BasicModal>
    <DeliveryModal ref="Shipment" @finish="emit('finish')"></DeliveryModal>
  </div>
</template>

<style scoped></style>
