<script lang="ts" setup>
/**
 * 总仓改价后：强制重分配配送仓三费
 * 不可点击遮罩关闭，必须确认或取消
 */
import { computed, ref } from 'vue';

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

import { Alert, InputNumber, Table, message } from 'ant-design-vue';

import {
  calcFeeSum,
  calcPromoFee,
} from '#/views/system/delivery-warehouse-drug/config/form';

import { updateWarehouseWithDeliveryFees } from '../api';

type BindRow = {
  id: number;
  warehouse_id: number;
  warehouse_name: string;
  quote: number;
  promo_fee: number;
  platform_fee: number;
};

const rows = ref<BindRow[]>([]);
const salePrice = ref(0);
const marketPrice = ref(0);
const centralId = ref(0);
const drugId = ref(0);
const gridApi = ref<any>(null);
const onSuccess = ref<(() => void) | null>(null);

const saleText = computed(() => `¥${Number(salePrice.value || 0).toFixed(4)}`);

const columns = [
  { title: '配送仓', dataIndex: 'warehouse_name', key: 'warehouse_name', ellipsis: true },
  { title: '报价', key: 'quote', width: 130 },
  { title: '平台费', key: 'platform_fee', width: 130 },
  { title: '推广费', key: 'promo_fee', width: 130 },
  { title: '合计', key: 'sum', width: 110 },
];

/**
 * 售价变化后自动回填推广费 = 售价 − 报价 − 平台费
 */
function syncPromo(row: BindRow) {
  row.promo_fee = calcPromoFee({
    sale_price: salePrice.value,
    quote: row.quote,
    platform_fee: row.platform_fee,
    promo_fee: row.promo_fee,
  });
}

function feeSum(row: BindRow) {
  return Number(
    calcFeeSum({
      quote: row.quote,
      promo_fee: row.promo_fee,
      platform_fee: row.platform_fee,
    }),
  );
}

const [Modal, modalApi] = useVbenModal({
  class: 'w-[820px]',
  draggable: true,
  fullscreenButton: false,
  // 禁止点遮罩关闭，避免漏填三费
  closeOnClickModal: false,
  closeOnPressEscape: false,
  confirmText: '确认并保存',
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    if (!rows.value.length) {
      message.warning('没有需要重分配的配送仓');
      return;
    }
    for (const row of rows.value) {
      const sum = feeSum(row);
      if (!(sum > 0)) {
        message.warning(`配送仓「${row.warehouse_name}」三费合计必须大于0`);
        return;
      }
      if (salePrice.value > 0 && sum - salePrice.value > 0.00005) {
        message.warning(
          `配送仓「${row.warehouse_name}」三费合计不能超过售价 ${saleText.value}`,
        );
        return;
      }
    }
    modalApi.setState({ confirmLoading: true, loading: true });
    try {
      await updateWarehouseWithDeliveryFees({
        id: centralId.value,
        drug_id: drugId.value,
        market_price: marketPrice.value,
        price: salePrice.value,
        delivery_binds: rows.value.map((r) => ({
          id: r.id,
          quote: Number(r.quote),
          promo_fee: Number(r.promo_fee),
          platform_fee: Number(r.platform_fee),
        })),
      });
      message.success('已更新总仓价格并重分配配送仓三费');
      gridApi.value?.query?.() ?? gridApi.value?.reload?.();
      onSuccess.value?.();
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false, loading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      rows.value = [];
      onSuccess.value = null;
      return;
    }
    const data = modalApi.getData<Record<string, any>>() || {};
    centralId.value = Number(data.central_id || data.id || 0);
    drugId.value = Number(data.drug_id || 0);
    salePrice.value = Number(data.price || 0);
    marketPrice.value = Number(data.market_price || 0);
    gridApi.value = data.gridApi || null;
    onSuccess.value = data.onSuccess || null;
    const binds = Array.isArray(data.delivery_binds) ? data.delivery_binds : [];
    rows.value = binds.map((b: any) => {
      const row: BindRow = {
        id: Number(b.id),
        warehouse_id: Number(b.warehouse_id),
        warehouse_name: String(b.warehouse_name || `仓#${b.warehouse_id}`),
        quote: Number(b.quote || 0),
        platform_fee: Number(b.platform_fee || 0),
        promo_fee: Number(b.promo_fee || 0),
      };
      // 按新售价重算推广费默认值
      if (salePrice.value > 0) {
        if (!(row.platform_fee > 0)) {
          row.platform_fee = Number((salePrice.value * 0.05).toFixed(4));
        }
        syncPromo(row);
      }
      return row;
    });
  },
});
</script>

<template>
  <Modal title="重分配配送仓三费">
    <Alert
      type="warning"
      show-icon
      class="mb-3"
      message="该药品已绑定配送仓，总仓改价后必须重新填写各仓报价/平台费/推广费后才能保存"
      :description="`新建议售价 ${saleText}；推广费默认=售价−报价−平台费，可微调`"
    />
    <Table
      size="small"
      :pagination="false"
      :columns="columns"
      :data-source="rows"
      :scroll="{ y: 360 }"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'quote'">
          <InputNumber
            v-model:value="record.quote"
            :min="0"
            :precision="4"
            class="w-full"
            size="small"
            @change="syncPromo(record)"
          />
        </template>
        <template v-else-if="column.key === 'platform_fee'">
          <InputNumber
            v-model:value="record.platform_fee"
            :min="0"
            :precision="4"
            class="w-full"
            size="small"
            @change="syncPromo(record)"
          />
        </template>
        <template v-else-if="column.key === 'promo_fee'">
          <InputNumber
            v-model:value="record.promo_fee"
            :min="0"
            :precision="4"
            class="w-full"
            size="small"
          />
        </template>
        <template v-else-if="column.key === 'sum'">
          <span
            :style="
              salePrice > 0 && feeSum(record) - salePrice > 0.00005
                ? { color: 'hsl(var(--destructive))' }
                : undefined
            "
          >
            ¥{{ feeSum(record).toFixed(4) }}
          </span>
        </template>
      </template>
    </Table>
  </Modal>
</template>
