<script lang="ts" setup>
/**
 * 总仓药品新增/编辑
 * 编辑且该药已绑配送仓时：打开不可点遮罩关闭的三费重分配确认窗
 */
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { getDeliveryWarehouseDrugList } from '#/views/system/delivery-warehouse-drug/api';

import {
  createWarehouseDrugManagement,
  getWarehouseDrugManagementInfo,
  updateWarehouseDrugManagement,
} from '../api';
import { modalFormProps } from '../config/form';
import DeliveryFeeReallocateModalDemo from './delivery-fee-reallocate-modal.vue';

const isUpdate = ref(false);
const gridApi = ref();

const [Form, formApi] = useVbenForm(modalFormProps);

const [FeeModal, feeModalApi] = useVbenModal({
  connectedComponent: DeliveryFeeReallocateModalDemo,
});

/**
 * 查询该药品是否已绑定配送仓
 */
async function fetchDeliveryBinds(drugId: number) {
  if (drugId < 1) return [];
  const res = await getDeliveryWarehouseDrugList({
    page: 1,
    pageSize: 100,
    drug_id: drugId,
  });
  return res?.items || [];
}

/**
 * 普通保存（无配送仓绑定 / 新增）
 */
async function submitPlain(values: Record<string, any>) {
  modalApi.setState({ loading: true, confirmLoading: true });
  try {
    const submitApi = isUpdate.value
      ? updateWarehouseDrugManagement
      : createWarehouseDrugManagement;
    await submitApi(values);
    message.success('保存成功');
    gridApi.value?.reload?.() ?? gridApi.value?.query?.();
    modalApi.close();
  } finally {
    modalApi.setState({ loading: false, confirmLoading: false });
  }
}

/**
 * 打开三费重分配确认（禁止点遮罩关闭）
 */
function openFeeReallocate(payload: Record<string, any>) {
  feeModalApi.setData(payload);
  feeModalApi.open();
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    formApi.validate().then(async (e: any) => {
      if (!e.valid) return;
      const values = await formApi.getValues();
      if (!isUpdate.value) {
        await submitPlain(values);
        return;
      }
      // 商品列表点总仓售价时可能只带了总仓 id，补齐 drug_id
      let drugId = Number(values.drug_id || 0);
      modalApi.setState({ loading: true, confirmLoading: true });
      try {
        if (!drugId && values.id) {
          const info = await getWarehouseDrugManagementInfo(Number(values.id));
          drugId = Number(info?.drug_id || 0);
          values.drug_id = drugId;
        }
        const binds = await fetchDeliveryBinds(drugId);
        if (!binds.length) {
          await submitPlain(values);
          return;
        }
        modalApi.close();
        openFeeReallocate({
          id: Number(values.id),
          central_id: Number(values.id),
          drug_id: drugId,
          market_price: Number(values.market_price),
          price: Number(values.price),
          delivery_binds: binds.map((b: any) => ({
            id: b.id,
            warehouse_id: b.warehouse_id,
            warehouse_name:
              b.warehouse?.name || b.warehouse_name || `仓#${b.warehouse_id}`,
            quote: b.quote,
            promo_fee: b.promo_fee,
            platform_fee: b.platform_fee,
          })),
          gridApi: gridApi.value,
        });
      } catch (err) {
        console.error(err);
      } finally {
        modalApi.setState({ loading: false, confirmLoading: false });
      }
    });
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (!isOpen) return;
    const modalData = modalApi.getData<{
      gridApi?: unknown;
      listDrugType?: number;
      update?: boolean;
      values?: Record<string, any>;
    }>();
    const listDrugType = modalData?.listDrugType ?? 1;
    formApi.updateSchema([
      {
        fieldName: 'drug_id',
        component: 'WarehouseAdminDrugSearch' as const,
        componentProps: {
          class: 'w-full',
          productType: listDrugType,
        },
      },
    ]);
    const { values, update } = modalData ?? {};
    if (values) {
      isUpdate.value = !!update;
      formApi.setValues(values);
    } else {
      isUpdate.value = false;
      formApi.resetForm();
    }
  },
});
</script>

<template>
  <!-- FeeModal 与编辑窗平级，避免编辑窗关闭后确认窗挂载异常 -->
  <FeeModal />
  <Modal
    :title="`${isUpdate === true ? '编辑' : '新增'}仓库药品`"
    class="w-[60%] h-[60%]"
  >
    <Form />
  </Modal>
</template>
