import type { VbenFormProps } from '#/adapter/form';

import { getDeliveryWarehouseOption } from '#/views/system/delivery-warehouse/api';

/** 计算三费合计，用于表单联动展示 */
export function calcFeeSum(values: Record<string, any>) {
  const quote = Number(values.quote) || 0;
  const promoFee = Number(values.promo_fee) || 0;
  const platformFee = Number(values.platform_fee) || 0;
  return (quote + promoFee + platformFee).toFixed(4);
}

/**
 * 门店推广费 = 售价 − (报价 + 平台费)，不低于 0
 * 有售价时用于自动回填，保证三费合计贴合售价
 */
export function calcPromoFee(values: Record<string, any>): number {
  const sale = Number(values.sale_price) || 0;
  if (!(sale > 0)) return Number(values.promo_fee) || 0;
  const quote = Number(values.quote) || 0;
  const platformFee = Number(values.platform_fee) || 0;
  return Number(Math.max(0, sale - quote - platformFee).toFixed(4));
}

/** 三费是否超过药品售价 */
export function isFeeOverSalePrice(values: Record<string, any>) {
  const sale = Number(values.sale_price);
  if (!(sale > 0)) return false;
  return Number(calcFeeSum(values)) > sale;
}

/** 超售价文案回调（由 modal 注册，用于醒目红色提示） */
type FeeOverTipHandler = (tip: string) => void;
let feeOverTipHandler: FeeOverTipHandler | null = null;

/**
 * 记录上次自动算费依赖（售价|报价|平台费）
 * 仅依赖变化时覆盖 promo_fee，避免手改推广费被立刻冲掉
 */
let lastAutoPromoKey = '';

/** 注册/注销弹窗内的超售价文本提示处理器 */
export function registerFeeOverTipHandler(handler: FeeOverTipHandler | null) {
  feeOverTipHandler = handler;
}

/** 弹窗打开/重置时清零，避免沿用上一次绑定的 key */
export function resetAutoPromoFeeKey() {
  lastAutoPromoKey = '';
}

/**
 * 编辑回填后锁定当前依赖 key，避免一打开就把已有推广费冲掉
 * 之后只有改报价/平台费/售价才会重新自动算
 */
export function seedAutoPromoFeeKey(values: Record<string, any>) {
  const sale = Number(values.sale_price) || 0;
  if (!(sale > 0)) {
    lastAutoPromoKey = '';
    return;
  }
  lastAutoPromoKey = `${sale}|${Number(values.quote) || 0}|${Number(values.platform_fee) || 0}`;
}

/**
 * 有售价且 quote/platform/sale 变化时，自动回填门店推广费
 * @returns 回填后的 values（含最新 promo_fee），供合计展示使用
 */
export function applyAutoPromoFee(
  values: Record<string, any>,
  formApi: any,
): Record<string, any> {
  const sale = Number(values.sale_price) || 0;
  if (!(sale > 0)) {
    return values;
  }
  const key = `${sale}|${Number(values.quote) || 0}|${Number(values.platform_fee) || 0}`;
  const nextPromo = calcPromoFee(values);
  // 依赖未变：可能是手改推广费触发，不覆盖
  if (key === lastAutoPromoKey) {
    return values;
  }
  lastAutoPromoKey = key;
  const cur = Number(values.promo_fee);
  if (!(Math.abs(cur - nextPromo) < 0.00005)) {
    formApi.setFieldValue('promo_fee', nextPromo);
  }
  return { ...values, promo_fee: nextPromo };
}

/**
 * 费用合计联动：先按差额回填推广费，再刷新合计 / 超售价提示
 * 为什么放在 trigger：输入报价或平台费即触发，不必等提交
 * @returns 超售价提示文案（无则空串）
 */
export function syncFeeSumDisplay(
  values: Record<string, any>,
  formApi: any,
): string {
  const merged = applyAutoPromoFee(values, formApi);
  const sum = calcFeeSum(merged);
  formApi.setFieldValue('_fee_sum', sum);
  const sale = Number(merged.sale_price) || 0;
  const over = sale > 0 && Number(sum) > sale;
  const tip = over
    ? `三费合计已超过药品售价 ¥${sale.toFixed(4)}，请下调报价/推广费/平台费`
    : '';
  const feeHelp = over
    ? tip
    : sale > 0
      ? `推广费自动=售价−(报价+平台费)；合计不得超过 ¥${sale.toFixed(4)}`
      : '报价+推广费+平台费之和，保存时需大于0';
  // 单项输入上限：有售价时不得超过售价；同时刷新合计 help
  const feeInputProps = {
    min: 0,
    precision: 4,
    class: 'w-full',
    ...(sale > 0 ? { max: sale } : {}),
  };
  formApi.updateSchema([
    {
      fieldName: 'quote',
      componentProps: {
        ...feeInputProps,
        placeholder: '请输入报价',
      },
    },
    {
      fieldName: 'promo_fee',
      help: sale > 0 ? '自动计算：售价 − (报价 + 平台费)，可微调' : undefined,
      componentProps: {
        ...feeInputProps,
        placeholder: sale > 0 ? '自动=售价−报价−平台费' : '请输入推广费',
      },
    },
    {
      fieldName: 'platform_fee',
      componentProps: {
        ...feeInputProps,
        placeholder: '请输入平台费',
      },
    },
    {
      fieldName: '_fee_sum',
      help: feeHelp,
      componentProps: {
        disabled: true,
        placeholder: '报价+推广费+平台费',
        style: over ? { color: 'hsl(var(--destructive))' } : undefined,
      },
    },
  ]);
  feeOverTipHandler?.(tip);
  return tip;
}

export const modalFormProps: VbenFormProps = {
  wrapperClass: 'grid-cols-12',
  commonConfig: {
    formItemClass: 'col-span-12',
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'VbenInput',
      fieldName: 'id',
      label: 'ID',
      dependencies: {
        show: false,
        triggerFields: ['id'],
      },
    },
    {
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        showSearch: true,
        filterOption: (input: string, option: any) =>
          option?.label.toLowerCase().indexOf(input.toLowerCase()) >= 0,
        afterFetch: (data: { id: number; name: string }[]) =>
          data.map((item: any) => ({
            label: item.name,
            value: item.id,
          })),
        api: getDeliveryWarehouseOption,
        placeholder: '请选择配送仓库',
      },
      fieldName: 'warehouse_id',
      label: '配送仓库',
      rules: 'required',
    },
    {
      // 由弹窗顶部 DrugSearchSelect 写入，表单内隐藏避免手填
      component: 'InputNumber',
      fieldName: 'drug_id',
      label: '药品ID',
      rules: 'required',
      dependencies: {
        show: false,
        triggerFields: ['drug_id'],
      },
    },
    {
      // 总仓售价只读展示，同时作为提交时的 sale_price 封顶基准
      component: 'InputNumber',
      componentProps: {
        disabled: true,
        precision: 4,
        class: 'w-full',
        placeholder: '无总仓售价',
      },
      fieldName: 'sale_price',
      label: '药品售价',
      help: '来自总仓库建议售价；三费合计不得超过该值',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入报价',
        min: 0,
        precision: 4,
        class: 'w-full',
      },
      fieldName: 'quote',
      label: '报价',
      rules: 'required',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入推广费',
        min: 0,
        precision: 4,
        class: 'w-full',
      },
      fieldName: 'promo_fee',
      label: '推广费',
      help: '有售价时自动=售价−(报价+平台费)',
      rules: 'required',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入平台费',
        min: 0,
        precision: 4,
        class: 'w-full',
      },
      fieldName: 'platform_fee',
      label: '平台费',
      rules: 'required',
    },
    {
      component: 'VbenInput',
      componentProps: {
        disabled: true,
        placeholder: '报价+推广费+平台费',
      },
      fieldName: '_fee_sum',
      label: '费用合计',
      help: '报价+推广费+平台费之和，保存时需大于0',
      dependencies: {
        trigger(values, formApi) {
          syncFeeSumDisplay(values, formApi);
        },
        triggerFields: ['quote', 'promo_fee', 'platform_fee', 'sale_price'],
      },
    },
    // 创建时可填初始库存，提交后走入库流水（编辑时不展示）
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '选填，默认 0',
        min: 0,
        precision: 0,
        class: 'w-full',
      },
      fieldName: 'initial_stock',
      label: '初始库存',
      help: '大于 0 时绑定成功后自动入库并记流水',
      defaultValue: 0,
      dependencies: {
        show(values) {
          return !values?.id;
        },
        triggerFields: ['id'],
      },
    },
    {
      component: 'RadioGroup',
      componentProps: {
        options: [
          { label: '下架', value: 1 },
          { label: '上架', value: 2 },
        ],
      },
      fieldName: 'status',
      label: '状态',
      defaultValue: 2,
    },
  ],
  showDefaultActions: false,
};
