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

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

import { Table, Tag } from 'ant-design-vue';

import StatisticsReconciliation from '#/views/finance/reconciliation/components/statistics.vue';
import { getInvoicePriceApi } from '#/views/finance/reconciliation/api/invoice-price';

const loading = ref(false);
const storeId = ref(0);
const storeName = ref('');
const searchTime = ref<[string, string]>(['', '']);
const metrics = ref<Record<string, number> | null>(null);
const drugItems = ref<any[]>([]);

const [Drawer, drawerApi] = useVbenDrawer({
  onOpenChange(isOpen) {
    if (isOpen) {
      fetchData();
    } else {
      metrics.value = null;
      drugItems.value = [];
    }
  },
});

const statistics = computed(() => {
  if (!metrics.value) return null;
  const m = metrics.value;
  return [
    { title: '开票合计', value: m.invoice_total, icon: 'mdi:cash-multiple', color: 'text-blue-600', unit: '¥' },
    { title: '中药供货价', value: m.herbal_supply_price, icon: 'mdi:leaf', color: 'text-green-600', unit: '¥' },
    {
      title: '西药供货价',
      value: Number(m.medicine_supply_price || 0) + Number(m.granule_supply_price || 0),
      icon: 'mdi:pharmacy',
      color: 'text-purple-600',
      unit: '¥',
    },
    { title: '中药代煎费', value: m.herbal_decoct_fee, icon: 'mdi:fire', color: 'text-orange-600', unit: '¥' },
    { title: '中药运费', value: m.herbal_express_fee, icon: 'skill-icons:expressjs-dark', color: 'text-orange-500', unit: '¥' },
    {
      title: '西药运费',
      value: Number(m.medicine_express_fee || 0) + Number(m.granule_express_fee || 0),
      icon: 'mdi:truck',
      color: 'text-indigo-600',
      unit: '¥',
    },
  ];
});

const drugColumns = [
  { title: '药名', dataIndex: 'drug_name', key: 'drug_name', width: 160, ellipsis: true },
  { title: '药品编号', dataIndex: 'drug_number', key: 'drug_number', width: 120 },
  { title: '类型', dataIndex: 'type_txt', key: 'type_txt', width: 100 },
  { title: '数量', dataIndex: 'number', key: 'number', width: 80 },
  { title: '供货单价', dataIndex: 'market_price', key: 'market_price', width: 100 },
  { title: '供货总额', dataIndex: 'total_supply_price', key: 'total_supply_price', width: 110 },
];

/** 拉取开票价格与药品供货明细 */
async function fetchData() {
  const data = drawerApi.getData<{
    store_id: number;
    store_name: string;
    search_time: [string, string];
  }>();
  if (!data?.store_id || !data.search_time?.[0]) {
    return;
  }
  storeId.value = data.store_id;
  storeName.value = data.store_name;
  searchTime.value = data.search_time;
  loading.value = true;
  try {
    const res = await getInvoicePriceApi({
      store_id: data.store_id,
      search_time: data.search_time,
    });
    metrics.value = res.metrics ?? null;
    drugItems.value = res.drug_items ?? [];
  } finally {
    loading.value = false;
  }
}

defineExpose({
  open(payload: { store_id: number; store_name: string; search_time: [string, string] }) {
    drawerApi.setData(payload);
    drawerApi.open();
  },
});
</script>

<template>
  <Drawer
    :title="`开票价格 - ${storeName}`"
    class="w-[900px]"
  >
    <div class="mb-2 text-sm text-muted-foreground">
      统计区间：{{ searchTime[0] }} ~ {{ searchTime[1] }}
      <Tag color="blue" class="ml-2">诊所 ID: {{ storeId }}</Tag>
    </div>
    <div class="mb-3 rounded border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-600">
      口径说明：西药供货价/运费含服务包、保健食品、医疗器械、非药品等所有非中药；已取消独立「颗粒药」栏目。
    </div>
    <StatisticsReconciliation
      v-if="statistics"
      :statistics="statistics"
    />
    <div class="mt-4 mb-2 font-medium">药品供货明细</div>
    <Table
      :columns="drugColumns"
      :data-source="drugItems"
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      row-key="drug_id"
      size="small"
      bordered
      :scroll="{ x: 700 }"
    />
  </Drawer>
</template>
