<script lang="ts" setup>
/**
 * 仓药绑定弹窗
 * 新增时用 DrugSearchSelect(is-card) 选药；编辑/预填锁定时不可换药
 * 有总仓售价时：展示、新增默认平台费=售价5%、三费超售价实时提醒并拦截提交
 * 注意：必须 await setValues，否则异步覆盖会把 sale_price 冲掉
 */
import { nextTick, onMounted, onUnmounted, ref } from 'vue';

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

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

import { useVbenForm } from '#/adapter/form';
import { DrugSearchSelect } from '#/components/drug-search-select';
import {
  createDeliveryWarehouseDrug,
  updateDeliveryWarehouseDrug,
} from '#/views/system/delivery-warehouse-drug/api';
import {
  applyAutoPromoFee,
  calcFeeSum,
  isFeeOverSalePrice,
  modalFormProps,
  registerFeeOverTipHandler,
  resetAutoPromoFeeKey,
  seedAutoPromoFeeKey,
  syncFeeSumDisplay,
} from '#/views/system/delivery-warehouse-drug/config/form';
import { resolveCentralPrice } from '#/views/system/delivery-warehouse-drug/utils/resolve-central-price';

/** 非中药品类：西药/保健/中成药/服务包/非药品/医疗器械 */
const NON_CHINESE_DRUG_TYPES = [2, 3, 4, 5, 6, 7];

/** 只读卡片占位图 */
const DRUG_PLACEHOLDER_IMAGE =
  'https://xiaokang88.oss-cn-hangzhou.aliyuncs.com/xk_upload_20250510/cd470ebf97e31c4048ba502ba71b66a3.jpg';

const isUpdate = ref(false);
/** 从药品列表打开时锁定药品 */
const lockDrug = ref(false);
const gridApi = ref();
/** 三费超售价时的醒目红色提示（空串表示无提示） */
const feeOverTip = ref('');
const editDrugCard = ref<{
  name: string;
  id: number | null;
  spec: string;
  image: string;
} | null>(null);

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

// 表单 dependencies 触发 sync 时同步到弹窗红色文案
onMounted(() => {
  registerFeeOverTipHandler((tip) => {
    feeOverTip.value = tip;
  });
});
onUnmounted(() => {
  registerFeeOverTipHandler(null);
});

/**
 * 写入售价；新增时默认平台费 = 售价 5%，并按差额回填推广费
 * 编辑仅写售价并锁定依赖 key，不覆盖已有三费
 */
async function applyCentralPrice(
  price: number | string | null | undefined,
  isCreate: boolean,
) {
  const n = Number(price);
  if (!(n > 0)) {
    await formApi.setFieldValue('sale_price', undefined);
    return;
  }
  const sale = Number(n.toFixed(4));
  await formApi.setFieldValue('sale_price', sale);
  if (isCreate) {
    const platform = Number((sale * 0.05).toFixed(4));
    await formApi.setFieldValue('platform_fee', platform);
    const values = await formApi.getValues();
    const merged = { ...values, sale_price: sale, platform_fee: platform };
    applyAutoPromoFee(merged, formApi);
    syncFeeSumDisplay(merged, formApi);
    return;
  }
  const values = await formApi.getValues();
  const merged = { ...values, sale_price: sale };
  seedAutoPromoFeeKey(merged);
  syncFeeSumDisplay(merged, formApi);
}

/**
 * 从弹窗入参解析售价：优先 data.central_price，再嵌套/values/preset
 */
function pickSalePrice(data: Record<string, any>) {
  const fromData = resolveCentralPrice(data);
  if (fromData != null) return fromData;
  const fromValues = resolveCentralPrice(data.values);
  if (fromValues != null) return fromValues;
  return resolveCentralPrice(data.presetDrug);
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const values = await formApi.getValues();
    if (!isUpdate.value && !values.drug_id) {
      message.error('请选择药品');
      return;
    }
    // 提交前实时拦截：三费合计不得超过药品售价
    if (isFeeOverSalePrice(values)) {
      message.warning(
        `三费合计已超过药品售价 ¥${Number(values.sale_price).toFixed(4)}`,
      );
      return;
    }
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const payload = { ...(await formApi.getValues()) };
        // sale_price 只作封顶校验，不用费用合计覆盖
        if (payload.sale_price === undefined || payload.sale_price === '') {
          delete payload.sale_price;
        }
        delete payload._fee_sum;
        if (Number(calcFeeSum(payload)) <= 0) {
          message.warning('报价/推广费/平台费合计必须大于0');
          return;
        }
        modalApi.setState({ loading: true, confirmLoading: true });
        const submitApi = isUpdate.value
          ? updateDeliveryWarehouseDrug
          : createDeliveryWarehouseDrug;
        submitApi(payload)
          .then(() => {
            message.success('保存成功');
            gridApi.value?.query?.() ?? gridApi.value?.reload?.();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
    await formApi.validateAndSubmitForm();
  },
  async onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (!isOpen) {
      feeOverTip.value = '';
      return;
    }
    const data = modalApi.getData<Record<string, any>>() || {};
    const { values, update, presetDrug } = data;
    isUpdate.value = !!update;
    lockDrug.value = !!data.lockDrug && !update;
    editDrugCard.value = null;
    feeOverTip.value = '';
    // 清零自动算费 key，避免沿用上一单的报价/平台费组合
    resetAutoPromoFeeKey();
    const salePrice = pickSalePrice(data);
    // 先重置，再 await 写入，避免异步 setValues 冲掉 sale_price
    await formApi.resetForm();
    const nextValues = {
      ...(values || {}),
      ...(salePrice != null ? { sale_price: salePrice } : {}),
    };
    if (Object.keys(nextValues).length) {
      await formApi.setValues(nextValues);
    }
    if (update && values) {
      editDrugCard.value = {
        id: values.drug_id ? Number(values.drug_id) : null,
        name:
          values.drug?.drug_name ||
          values.drug_name ||
          (values.drug_id ? `药品#${values.drug_id}` : ''),
        spec: values.drug?.specification || values.specification || '',
        image: values.drug?.image || values.image || DRUG_PLACEHOLDER_IMAGE,
      };
      // 编辑：只写售价，不覆盖已有三费
      await applyCentralPrice(salePrice, false);
    } else if (lockDrug.value && presetDrug) {
      const id = Number(presetDrug.id || values?.drug_id || 0);
      await formApi.setFieldValue('drug_id', id);
      editDrugCard.value = {
        id,
        name: presetDrug.drug_name || `药品#${id}`,
        spec: presetDrug.specification || '',
        image: presetDrug.image || DRUG_PLACEHOLDER_IMAGE,
      };
      await applyCentralPrice(salePrice, true);
    } else if (!update) {
      await applyCentralPrice(salePrice, true);
    }
    // 再确认一次：部分表单实现会二次回填空值
    await nextTick();
    const after = await formApi.getValues();
    const afterSale = Number(after?.sale_price);
    if (salePrice != null && (!(afterSale > 0) || afterSale !== salePrice)) {
      await applyCentralPrice(salePrice, !update);
    }
    // 打开后同步一次上限与提示（售价写入后 dependencies 可能未立刻跑完）
    const latest = await formApi.getValues();
    feeOverTip.value = syncFeeSumDisplay(latest, formApi);
  },
});

async function onSelectDrug(item: any) {
  if (isUpdate.value || lockDrug.value) return;
  if (!item) {
    await formApi.setFieldValue('drug_id', undefined);
    return;
  }
  const drugId = Number(item?.drug?.id || item?.drug_id || item?.id || 0);
  if (!drugId) {
    message.error('药品数据异常');
    return;
  }
  await formApi.setFieldValue('drug_id', drugId);
  // 搜药选中后若带总仓价则预填平台费 5%
  const price = resolveCentralPrice(item) ?? resolveCentralPrice(item?.drug);
  if (price != null) {
    await applyCentralPrice(price, true);
  }
}
</script>
<template>
  <Modal
    :title="`${isUpdate === true ? '编辑' : '新增'}仓药绑定`"
    class="w-[40%]"
  >
    <div class="mb-4">
      <div class="mb-1 text-sm text-muted-foreground">
        药品
        <span class="text-red-500">*</span>
      </div>
      <div
        v-if="(isUpdate || lockDrug) && editDrugCard"
        class="warehouse-drug-readonly-card"
      >
        <img
          :src="editDrugCard.image || DRUG_PLACEHOLDER_IMAGE"
          alt=""
          class="warehouse-drug-readonly-card__img"
        />
        <div class="warehouse-drug-readonly-card__info">
          <div class="warehouse-drug-readonly-card__name">
            {{ editDrugCard.name || `药品ID：${editDrugCard.id}` }}
          </div>
          <div class="warehouse-drug-readonly-card__meta">
            <span v-if="editDrugCard.id">ID：{{ editDrugCard.id }}</span>
            <span v-if="editDrugCard.spec">规格：{{ editDrugCard.spec }}</span>
            <span class="warehouse-drug-readonly-card__hint">
              {{ isUpdate ? '编辑时不可更换药品' : '已自动选中当前药品' }}
            </span>
          </div>
        </div>
      </div>
      <DrugSearchSelect
        v-else
        :types="NON_CHINESE_DRUG_TYPES"
        :is-card="true"
        placeholder="聚焦或搜索药品（不含中药）"
        @select="onSelectDrug"
      />
    </div>
    <!-- 超售价醒目提示：不能只靠 InputNumber max -->
    <div v-if="feeOverTip" class="fee-over-tip">{{ feeOverTip }}</div>
    <Form />
  </Modal>
</template>
<style scoped>
.fee-over-tip {
  margin-bottom: 12px;
  font-size: 13px;
  line-height: 1.5;
  color: hsl(var(--destructive));
}
/* 只用框架主题变量，避免硬编码 / :global(.dark) 污染全局配色 */
.warehouse-drug-readonly-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: hsl(var(--muted) / 0.3);
  border: 1px solid hsl(var(--border));
  border-radius: 8px;
}
.warehouse-drug-readonly-card__img {
  width: 48px;
  height: 48px;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid hsl(var(--border));
  flex-shrink: 0;
}
.warehouse-drug-readonly-card__info {
  flex: 1;
  min-width: 0;
}
.warehouse-drug-readonly-card__name {
  font-size: 14px;
  font-weight: 500;
  color: hsl(var(--foreground));
  margin-bottom: 4px;
}
.warehouse-drug-readonly-card__meta {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  font-size: 12px;
  color: hsl(var(--muted-foreground));
}
.warehouse-drug-readonly-card__hint {
  color: hsl(var(--muted-foreground));
}
</style>
