<script setup lang="tsx">
import { nextTick, ref, unref } from 'vue';
import { fetchDeliveryOrder, fetchGetNomalOrderInfo } from '@/service/api/delivery/normal-orde';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
import { useForm } from '@/components/zt/Form/hooks/useForm';
import { deliveryInfo } from '../normal-order';
const [registerModal, { openModal, setModalProps, setSubLoading, closeModal, setModalLoading }] = useModal({
  title: '订单发货',
  width: 1200,
  height: 800,
  isShowHeaderText: false
});
const [registerForm, { validate, getFieldsValue, setFieldsValue }] = useForm({
  schemas: deliveryInfo,
  labelWidth: 120,
  layout: 'horizontal',
  gridProps: {
    cols: '1',
    itemResponsive: true
  },
  collapsedRows: 1,
  showActionButtonGroup: false
});
const emit = defineEmits<{
  (e: 'finish'): void;
}>();

const orderInfo = ref<Api.delivery.deliveryOrder>();
const isRefundIng = ref(false);
const ShipmentColumns: NaiveUI.TableColumn<Api.delivery.OrderItemElement>[] = [
  {
    title: '商品',
    key: 'goodsName',
    width: 300,
    render: row => {
      return (
        <div class={'flex items-center'}>
          <n-image src={row.pic} width={80} height={80} class={'min-w-80px'}></n-image>
          <div class={'ml2'}>
            <div class={'text-15px font-semibold'}> {row.skuName} </div>
            <div class={'text-gray'}>规格: {row.spec || '---'}</div>
          </div>
        </div>
      );
    }
  },
  {
    title: '可发货数量',
    key: 'num',
    width: 250,
    render: row => {
      const count = Number(row.prodCount) - Number(row.refundSuccessCount);
      if (Number(row.refundIngCount)) {
        isRefundIng.value = true;
      }
      return (
        <div class={'flex items-center justify-center'}>
          {count} {handleCreateTag(row)}
        </div>
      );
    }
  },
  {
    title: '状态',
    key: 'status',
    align: 'center',
    render: _row => {
      return orderInfo.value?.hbOrderStatus == 1 ? <n-tag>等待发货</n-tag> : <n-tag type="success">已发货</n-tag>;
    }
  },
  {
    title: '发货数量',
    key: 'count',
    align: 'center',
    render: row => {
      const count = Number(row.prodCount) - Number(row.refundSuccessCount);
      return count;
    }
  }
];

defineExpose({
  setModalProps,
  handleOpenOrder
});
function handleCreateTag(row: Api.delivery.OrderItemElement) {
  if (row.refundSuccessCount) {
    return (
      <n-tag type="success" class={'ml2'}>
        已扣除退款成功：{row.refundSuccessCount}
      </n-tag>
    );
  }
  if (row.refundIngCount) {
    return (
      <n-tag type="error" class={'ml2'}>
        售后处理：{row.refundIngCount}
      </n-tag>
    );
  }
  return '';
}
async function handleOpenOrder(orderNumber: string) {
  openModal();
  setModalLoading(true);
  const { data, error } = await fetchGetNomalOrderInfo(orderNumber);
  setModalLoading(false);
  if (!error) {
    orderInfo.value = data;
    const Info = {
      ...data.userAddrOrder,
      ...data
    };
    nextTick(() => {
      setFieldsValue(Info);
    });
  }
}
async function handleSubmit() {
  if (unref(isRefundIng)) {
    window.$message?.error('存在售后处理中的商品，请处理后再发货');
    return;
  }
  await validate();
  setSubLoading(true);
  const form: Recordable = {
    ...getFieldsValue(),
    orderNumber: orderInfo.value?.orderNumber
  };
  delete form.receiver;
  delete form.mobile;
  delete form.address;
  const { error } = await fetchDeliveryOrder(form);
  if (!error) {
    emit('finish');
    closeModal();
  } else {
    setSubLoading(false);
  }
}
</script>

<template>
  <BasicModal @register="registerModal" @ok="handleSubmit" @after-leave="isRefundIng = false">
    <div v-if="orderInfo">
      <NCard :bordered="false" title="商品信息">
        <NDataTable :scroll-x="1000" :columns="ShipmentColumns" :data="orderInfo.orderItems" :bordered="false" />
      </NCard>
      <NCard :bordered="false" title="订单信息">
        <BasicForm @register-form="registerForm"></BasicForm>
      </NCard>
    </div>
  </BasicModal>
</template>

<style scoped></style>
