<script lang="ts" setup>
import { computed, ref } from 'vue';

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

import { InputNumber, message, Radio, RadioGroup } from 'ant-design-vue';

import SkuEditor, { type SkuItem } from './SkuEditor.vue';
import {
  getSpecialPrescriptionPriceConfig,
  saveSpecialPrescriptionPriceConfig,
} from '../api';

/** 药品占位价条目（固定价方案各药味恒为 0） */
interface DrugPriceItem {
  drug_id: number;
  buy_price: number;
  sell_price: number;
}

const gridApi = ref<any>();
const configId = ref(0);
const configName = ref('');
const priceCalcScheme = ref(3);
const buyPricePerDose = ref(0);
const salePricePerDose = ref(0);
const skus = ref<SkuItem[]>([]);
const isFreeShipping = ref(0);
const freeShippingMinDoses = ref(0);
const skuEditorRef = ref<InstanceType<typeof SkuEditor>>();

/** 处方药味明细，仅用于保存时生成全 0 的 drug_prices */
const prescriptionDetailCache = ref<any[]>([]);

const showFixedPriceBlock = computed(() => priceCalcScheme.value === 1);
/** 是否已配置 SKU（有 SKU 时以 SKU 包邮为准） */
const hasSkus = computed(() => skus.value.length > 0);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: true,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (configId.value <= 0) {
      return;
    }
    const payload: Record<string, any> = {
      id: configId.value,
      price_calc_scheme: priceCalcScheme.value,
      is_free_shipping: isFreeShipping.value,
      free_shipping_min_doses: freeShippingMinDoses.value,
      skus: skuEditorRef.value?.getSkusPayload() || skus.value,
    };
    if (priceCalcScheme.value === 1) {
      payload.buy_price_per_dose = buyPricePerDose.value;
      payload.sale_price_per_dose = salePricePerDose.value;
      // 固定价：各药味单价恒为 0，套餐价由单帖价或 SKU 总价承载
      const zeroPrices = buildZeroDrugPrices();
      payload.drug_prices = zeroPrices;
      const skuDrugPrices: Array<{ sku_id: number; drug_prices: DrugPriceItem[] }> = [];
      skus.value.forEach((sku) => {
        const skuId = Number(sku.id || 0);
        if (skuId > 0) {
          skuDrugPrices.push({ sku_id: skuId, drug_prices: zeroPrices });
        }
      });
      payload.sku_drug_prices = skuDrugPrices;
    }
    modalApi.setState({ loading: true, confirmLoading: true });
    saveSpecialPrescriptionPriceConfig(payload)
      .then(() => {
        message.success('价格配置保存成功');
        gridApi.value?.reload();
        modalApi.close();
      })
      .finally(() => {
        modalApi.setState({ loading: false, confirmLoading: false });
      });
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values, gridApi: grid } = modalApi.getData<Record<string, any>>();
      gridApi.value = grid;
      configId.value = values?.id || 0;
      if (!configId.value) {
        return;
      }
      getSpecialPrescriptionPriceConfig(configId.value).then((res: any) => {
        if (!res) return;
        configName.value = res.name || '';
        priceCalcScheme.value = res.price_calc_scheme ?? 3;
        buyPricePerDose.value = res.buy_price_per_dose ?? 0;
        salePricePerDose.value = res.sale_price_per_dose ?? res.price_per_dose ?? 0;
        isFreeShipping.value = res.is_free_shipping ?? 0;
        freeShippingMinDoses.value = res.free_shipping_min_doses ?? 0;
        skus.value = res.skus || [];
        skuEditorRef.value?.setSkus(res.skus || []);
        prescriptionDetailCache.value = res.prescription_detail || [];
      });
    }
  },
});

/** 构建全 0 药味单价列表（-102 占位计价，不在 UI 配置分摊） */
function buildZeroDrugPrices(): DrugPriceItem[] {
  return (prescriptionDetailCache.value || []).map((recipe) => ({
    drug_id: Number(recipe.drug_id || recipe.id),
    buy_price: 0,
    sell_price: 0,
  }));
}
</script>

<template>
  <Modal :title="`价格配置 - ${configName}`" class="w-[90%]">
    <div class="price-config-modal">
      <div class="section-title">价格计算方案</div>
      <RadioGroup v-model:value="priceCalcScheme">
        <Radio :value="1">固定单价（含 SKU 快捷选贴）</Radio>
        <Radio :value="3">门店浮动</Radio>
      </RadioGroup>

      <div class="mt-4 shipping-config">
        <div class="section-title">包邮配置</div>
        <template v-if="hasSkus">
          <div class="shipping-tip">
            已配置 SKU，下单选用 SKU 时以各 SKU「是否包邮」为准（SKU 优先于特色方配置）
          </div>
        </template>
        <template v-else>
          <div class="shipping-row">
            <span class="label">是否包邮</span>
            <RadioGroup v-model:value="isFreeShipping">
              <Radio :value="0">不包邮</Radio>
              <Radio :value="1">包邮</Radio>
            </RadioGroup>
          </div>
          <div v-if="isFreeShipping === 1" class="shipping-row mt-2">
            <span class="label">包邮条件（剂数）</span>
            <InputNumber
              v-model:value="freeShippingMinDoses"
              :min="0"
              :precision="0"
              placeholder="0 表示始终包邮"
              style="width: 160px"
            />
            <span class="shipping-hint">大于该剂数才包邮，0 表示始终包邮</span>
          </div>
        </template>
      </div>

      <div v-if="showFixedPriceBlock" class="mt-4 fixed-price-block">
        <div class="section-title">单帖价格</div>
        <div class="price-row">
          <div class="price-field">
            <span class="label">一贴供货价</span>
            <InputNumber
              v-model:value="buyPricePerDose"
              :min="0"
              :precision="2"
              style="width: 100%"
            />
          </div>
          <div class="price-field">
            <span class="label">一贴销售价</span>
            <InputNumber
              v-model:value="salePricePerDose"
              :min="0"
              :precision="2"
              style="width: 100%"
            />
          </div>
        </div>
        <div class="fixed-price-tip">
          未选 SKU 时按「单帖价 × 贴数」计价；已选 SKU 时使用下方 SKU 套餐总价。药味单价固定 ¥0，下单时由系统写入套餐占位行。
        </div>
        <SkuEditor ref="skuEditorRef" v-model="skus" />
      </div>

      <div v-else class="mt-4 store-float-tip">
        门店浮动方案无需配置药品分摊，SKU 仍可配置快捷选贴数。
        <div class="section-title mt-4">SKU 规格</div>
        <SkuEditor ref="skuEditorRef" v-model="skus" />
      </div>
    </div>
  </Modal>
</template>

<style scoped>
.section-title {
  font-weight: 600;
  margin-bottom: 12px;
  color: hsl(var(--foreground));
}

.fixed-price-block {
  max-width: 960px;
}

.price-row {
  display: flex;
  align-items: flex-end;
  gap: 16px;
  flex-wrap: wrap;
}

.price-field {
  width: 160px;
}

.price-field .label {
  display: block;
  margin-bottom: 4px;
  color: hsl(var(--muted-foreground));
  font-size: 13px;
}

.fixed-price-tip {
  color: hsl(var(--muted-foreground));
  font-size: 13px;
  line-height: 1.6;
  margin: 12px 0 16px;
}

.store-float-tip {
  color: hsl(var(--muted-foreground));
  font-size: 13px;
}

.shipping-config {
  padding: 12px;
  background: hsl(var(--muted) / 0.3);
  border-radius: 8px;
  border: 1px solid hsl(var(--border));
}

.shipping-row {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.shipping-row .label {
  color: hsl(var(--muted-foreground));
  font-size: 13px;
  min-width: 100px;
}

.shipping-tip,
.shipping-hint {
  color: hsl(var(--muted-foreground));
  font-size: 12px;
}
</style>
