<script lang="ts" setup>
/**
 * 金方缺失药品弹窗
 * 展示导入/药方设置产生的不存在药名；点击药名可选择「添加药材」或「写入别名表」
 */
import { ref } from 'vue';

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

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

import {
  getGoldenFormulaMissingDrugList,
  recheckGoldenFormulaMissingDrug,
  resolveGoldenFormulaMissingDrug,
} from '../api';
import { MISSING_DRUG_STATUS_OPTIONS } from '../config/constants';
import ResolveMissingDrugPanel from './ResolveMissingDrugPanel.vue';

const loading = ref(false);
const rechecking = ref(false);
const resolving = ref(false);
const items = ref<any[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(20);
const statusFilter = ref<number | undefined>(0);
const selectedRowKeys = ref<number[]>([]);

/** 处理面板状态 */
const resolveOpen = ref(false);
const resolveMissingId = ref(0);
const resolveDrugName = ref('');

const columns = [
  { title: '药名', dataIndex: 'drug_name', key: 'drug_name' },
  { title: '出现次数', dataIndex: 'hit_count', key: 'hit_count', width: 100 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 170 },
  { title: '更新时间', dataIndex: 'updated_at', key: 'updated_at', width: 170 },
];

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  class: 'w-[860px]',
  showConfirmButton: false,
  onCancel() {
    modalApi.close();
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      items.value = [];
      total.value = 0;
      page.value = 1;
      selectedRowKeys.value = [];
      statusFilter.value = 0;
      resolveOpen.value = false;
      return;
    }
    await loadList();
  },
});

/**
 * 拉取缺失药品分页列表
 */
async function loadList() {
  loading.value = true;
  selectedRowKeys.value = [];
  try {
    const params: Record<string, any> = {
      page: page.value,
      pageSize: pageSize.value,
    };
    if (statusFilter.value !== undefined && statusFilter.value !== null) {
      params.status = statusFilter.value;
    }
    const res = await getGoldenFormulaMissingDrugList(params);
    items.value = Array.isArray(res?.items) ? res.items : [];
    total.value = Number(res?.total || 0);
  } catch (e: any) {
    items.value = [];
    total.value = 0;
    message.error(e?.message || '加载失败');
  } finally {
    loading.value = false;
  }
}

/** 表格分页变更 */
function onTableChange(pag: any) {
  page.value = Number(pag?.current || 1);
  pageSize.value = Number(pag?.pageSize || 20);
  loadList();
}

/** 状态筛选变更后回到第一页 */
function onStatusChange() {
  page.value = 1;
  loadList();
}

/**
 * 重新校验：药品库已存在的自动标已解决
 */
async function handleRecheck() {
  rechecking.value = true;
  try {
    const res = await recheckGoldenFormulaMissingDrug();
    message.success(
      `校验 ${Number(res?.checked || 0)} 条，自动解决 ${Number(res?.resolved || 0)} 条`,
    );
    await loadList();
  } catch (e: any) {
    message.error(e?.message || '重新校验失败');
  } finally {
    rechecking.value = false;
  }
}

/**
 * 批量标记已解决（当前勾选）
 */
async function handleResolve() {
  if (!selectedRowKeys.value.length) {
    message.warning('请先勾选待处理记录');
    return;
  }
  resolving.value = true;
  try {
    const res = await resolveGoldenFormulaMissingDrug({
      ids: selectedRowKeys.value,
    });
    message.success(`已标记 ${Number(res?.resolved || 0)} 条为已解决`);
    await loadList();
  } catch (e: any) {
    message.error(e?.message || '操作失败');
  } finally {
    resolving.value = false;
  }
}

/** 勾选变更 */
function onSelectChange(keys: (string | number)[]) {
  selectedRowKeys.value = keys.map((k) => Number(k));
}

/**
 * 点击待处理药名：打开「添加药材 / 挂别名」选择面板
 */
function openResolve(record: any) {
  if (Number(record?.status) === 1) {
    message.info('该药名已解决');
    return;
  }
  resolveMissingId.value = Number(record?.id || 0);
  resolveDrugName.value = String(record?.drug_name || '').trim();
  if (!resolveDrugName.value) {
    message.warning('药名为空');
    return;
  }
  resolveOpen.value = true;
}
</script>
<template>
  <Modal title="缺失药品">
    <div class="gf-missing-toolbar">
      <div class="gf-missing-filters">
        <span class="gf-missing-label">状态</span>
        <Select
          v-model:value="statusFilter"
          allow-clear
          placeholder="全部"
          style="width: 140px"
          :options="MISSING_DRUG_STATUS_OPTIONS"
          @change="onStatusChange"
        />
      </div>
      <div class="gf-missing-actions">
        <Button :loading="rechecking" @click="handleRecheck">重新校验</Button>
        <Button
          type="primary"
          :loading="resolving"
          :disabled="!selectedRowKeys.length"
          @click="handleResolve"
        >
          标记已解决
        </Button>
      </div>
    </div>
    <p class="gf-missing-hint">
      点击待处理药名，可选择「添加药材」「放入别名表」或「替换为已有药材（保留旧名）」
    </p>
    <Table
      :columns="columns"
      :data-source="items"
      :loading="loading"
      row-key="id"
      size="small"
      bordered
      :row-selection="{
        selectedRowKeys,
        onChange: onSelectChange,
      }"
      :pagination="{
        current: page,
        pageSize,
        total,
        showSizeChanger: true,
        showTotal: (t: number) => `共 ${t} 条`,
      }"
      @change="onTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'drug_name'">
          <a
            v-if="record.status !== 1"
            class="gf-missing-name"
            @click.prevent="openResolve(record)"
          >
            {{ record.drug_name }}
          </a>
          <span v-else>{{ record.drug_name }}</span>
        </template>
        <template v-else-if="column.key === 'status'">
          <Tag v-if="record.status === 1" color="success">已解决</Tag>
          <Tag v-else color="error">待处理</Tag>
        </template>
      </template>
    </Table>
    <ResolveMissingDrugPanel
      v-model:open="resolveOpen"
      :missing-id="resolveMissingId"
      :drug-name="resolveDrugName"
      @done="loadList"
    />
  </Modal>
</template>
<style scoped>
.gf-missing-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  gap: 12px;
}
.gf-missing-filters {
  display: flex;
  align-items: center;
  gap: 8px;
}
.gf-missing-label {
  color: hsl(var(--muted-foreground));
  font-size: 13px;
}
.gf-missing-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}
.gf-missing-hint {
  margin: 0 0 12px;
  font-size: 12px;
  color: hsl(var(--muted-foreground));
}
.gf-missing-name {
  color: hsl(var(--destructive));
  font-weight: 600;
  cursor: pointer;
}
.gf-missing-name:hover {
  text-decoration: underline;
}
</style>
