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

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

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

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

/** 药品分摊价条目 */
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 chineseDrugEditorRef = ref<InstanceType<typeof ChineseDrugEditor>>();
const skuEditorRef = ref<InstanceType<typeof SkuEditor>>();

/** 当前分摊视图：0=单帖，>0=SKU id */
const activeSkuId = ref(0);
/** 各 scope 分摊价缓存 sku_id -> prices[] */
const drugPricesCache = ref<Record<number, DrugPriceItem[]>>({});
const prescriptionDetailCache = ref<any[]>([]);
const prescriptionDosage = ref(7);
const prescriptionDayDosage = ref(2);

const showFixedPriceBlock = computed(() => priceCalcScheme.value === 1);

/** 左侧标题：单帖或 SKU 名称 */
const allocationTitle = computed(() => {
  if (activeSkuId.value <= 0) {
    return '单帖均摊价格';
  }
  const sku = skus.value.find((item) => Number(item.id) === Number(activeSkuId.value));
  const name = sku?.sku_name || `${sku?.dose_count || ''}贴`;
  return `${name} 均摊价格`;
});

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: true,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (configId.value <= 0) {
      return;
    }
    persistCurrentScopePrices();
    const payload: Record<string, any> = {
      id: configId.value,
      price_calc_scheme: priceCalcScheme.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;
      payload.drug_prices = drugPricesCache.value[0] || [];
      const skuDrugPrices: Array<{ sku_id: number; drug_prices: DrugPriceItem[] }> = [];
      Object.keys(drugPricesCache.value).forEach((key) => {
        const skuId = Number(key);
        if (skuId > 0 && drugPricesCache.value[skuId]?.length) {
          skuDrugPrices.push({
            sku_id: skuId,
            drug_prices: drugPricesCache.value[skuId],
          });
        }
      });
      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;
      activeSkuId.value = 0;
      drugPricesCache.value = {};
      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;
        skus.value = res.skus || [];
        skuEditorRef.value?.setSkus(res.skus || []);

        prescriptionDetailCache.value = res.prescription_detail || [];
        const first = prescriptionDetailCache.value[0];
        prescriptionDosage.value = first?.dosage ?? 7;
        prescriptionDayDosage.value = first?.consumption ?? 2;

        drugPricesCache.value[0] = (res.drug_prices || []).map((item: any) => ({
          drug_id: Number(item.drug_id),
          buy_price: Number(item.buy_price || 0),
          sell_price: Number(item.sell_price || item.price || 0),
        }));
        const bySku = res.drug_prices_by_sku || {};
        Object.keys(bySku).forEach((skuKey) => {
          drugPricesCache.value[Number(skuKey)] = (bySku[skuKey] || []).map((item: any) => ({
            drug_id: Number(item.drug_id),
            buy_price: Number(item.buy_price || 0),
            sell_price: Number(item.sell_price || item.price || 0),
          }));
        });

        nextTick(() => {
          switchAllocationView(0);
        });
      });
    }
  },
});

watch(priceCalcScheme, (scheme) => {
  if (scheme === 1) {
    nextTick(() => switchAllocationView(activeSkuId.value));
  }
});

/** 将编辑器当前分摊写入缓存 */
function persistCurrentScopePrices() {
  const prices = chineseDrugEditorRef.value?.getDrugPricesPayload() || [];
  drugPricesCache.value[activeSkuId.value] = prices.map((item) => ({
    drug_id: Number(item.drug_id),
    buy_price: Number(item.buy_price || 0),
    sell_price: Number(item.sell_price || 0),
  }));
}

/** 切换单帖 / SKU 分摊视图 */
function switchAllocationView(skuId: number) {
  persistCurrentScopePrices();
  activeSkuId.value = skuId;
  const prices = drugPricesCache.value[skuId] || drugPricesCache.value[0] || [];
  chineseDrugEditorRef.value?.loadDrugs(
    prescriptionDetailCache.value,
    prescriptionDosage.value,
    prescriptionDayDosage.value,
    prices,
  );
}

function handleSkuSelectForPrice(skuId: number) {
  switchAllocationView(skuId);
}

function backToDoseAllocation() {
  switchAllocationView(0);
}

/** 自动均分：单帖用 per_dose，SKU 用套餐总价 */
async function handleDistributePrices() {
  const drugs = chineseDrugEditorRef.value?.getDrugsForDistribute() || [];
  if (drugs.length === 0) {
    message.warning('请先配置特色方药品');
    return;
  }
  let buyPrice = buyPricePerDose.value;
  let salePrice = salePricePerDose.value;
  if (activeSkuId.value > 0) {
    const sku = skus.value.find((item) => Number(item.id) === Number(activeSkuId.value));
    if (!sku) {
      message.warning('请先保存 SKU 后再均分');
      return;
    }
    const dose = Math.max(1, Number(sku.dose_count || 1));
    buyPrice = Number(sku.buy_price || 0) / dose;
    salePrice = Number(sku.sale_price || 0) / dose;
  }
  try {
    const result = await distributeDrugPricesApi({
      drugs,
      buy_price_per_dose: buyPrice,
      sale_price_per_dose: salePrice,
      buy_price: buyPrice,
      sale_price: salePrice,
    });
    chineseDrugEditorRef.value?.applyDistributedPrices(result || []);
    persistCurrentScopePrices();
    message.success('已自动均分药品单价');
  } catch (error) {
    console.error(error);
  }
}
</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 v-if="showFixedPriceBlock" class="mt-4">
        <Row :gutter="16">
          <Col :span="12">
            <div class="allocation-panel">
              <div class="allocation-header">
                <span class="allocation-title">{{ allocationTitle }}</span>
                <Button
                  v-if="activeSkuId > 0"
                  type="link"
                  size="small"
                  @click="backToDoseAllocation"
                >
                  返回单帖均摊
                </Button>
              </div>
              <ChineseDrugEditor
                ref="chineseDrugEditorRef"
                :price-editable="true"
                :structure-readonly="true"
              />
            </div>
          </Col>
          <Col :span="12">
            <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>
              <Button type="primary" ghost @click="handleDistributePrices">
                自动均分药品单价
              </Button>
            </div>
            <div class="section-title mt-4">SKU 规格（点击行查看分摊）</div>
            <SkuEditor
              ref="skuEditorRef"
              v-model="skus"
              :selected-price-sku-id="activeSkuId"
              @select-for-price="handleSkuSelectForPrice"
            />
          </Col>
        </Row>
      </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;
}

.allocation-panel {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 12px;
  min-height: 360px;
}

.allocation-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.allocation-title {
  font-weight: 600;
  font-size: 15px;
  color: #333;
}

.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: #666;
  font-size: 13px;
}

.store-float-tip {
  color: #666;
  font-size: 13px;
}
</style>
