<script lang="ts" setup>
/**
 * 药品详情弹窗
 * 一级 Tab：基础信息（原详情+别名）/ 仓库信息（总仓+门店改价）
 */
import { computed, ref } from 'vue';

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

import {
  Button,
  Descriptions,
  DescriptionsItem,
  Empty,
  Image,
  Input,
  Popconfirm,
  Spin,
  Tabs,
  Tag,
  message,
} from 'ant-design-vue';

import DrugWarehousePanel from './drug-warehouse-panel.vue';
import {
  addDrugAlias,
  deleteDrugAlias,
  getDrugAliasDetail,
} from './drug-alias-api';

type AliasRow = {
  id?: number;
  alias: string;
  pinyin_simple?: string;
  pinyin_full?: string;
  pinyin_display?: string;
  search_digits?: string;
};

const loading = ref(false);
const adding = ref(false);
const deletingId = ref(0);
const drug = ref<Record<string, any>>({});
const aliases = ref<AliasRow[]>([]);
const canManage = ref(false);
/** 新增输入框 */
const newAlias = ref('');
const gridApiRef = ref<any>(null);
/** 一级 Tab：基础信息 / 仓库信息 */
const mainTab = ref('basic');
const warehousePanelRef = ref<InstanceType<typeof DrugWarehousePanel> | null>(
  null,
);

const titleText = computed(
  () => `药品详情${drug.value?.drug_name ? ` · ${drug.value.drug_name}` : ''}`,
);

const aliasCountText = computed(() => `共 ${aliases.value.length} 条`);

const drugId = computed(() => Number(drug.value?.id || 0));

/**
 * 用接口结果回填本地状态
 */
function applyDetail(res: any) {
  drug.value = res?.drug || {};
  aliases.value = Array.isArray(res?.aliases) ? res.aliases : [];
  canManage.value = !!res?.can_manage;
}

/**
 * 加载基础详情
 */
async function loadDetail(id: number) {
  loading.value = true;
  newAlias.value = '';
  try {
    const res = await getDrugAliasDetail(id);
    applyDetail(res);
  } catch (e) {
    console.error(e);
    drug.value = {};
    aliases.value = [];
    canManage.value = false;
  } finally {
    loading.value = false;
  }
}

const [Modal, modalApi] = useVbenModal({
  class: 'w-[900px]',
  draggable: true,
  fullscreenButton: false,
  showConfirmButton: false,
  cancelText: '关闭',
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      newAlias.value = '';
      mainTab.value = 'basic';
      return;
    }
    const data = modalApi.getData<{
      drug_id?: number;
      id?: number;
      gridApi?: any;
    }>();
    gridApiRef.value = data?.gridApi || null;
    const id = Number(data?.drug_id || data?.id || 0);
    mainTab.value = 'basic';
    if (id > 0) {
      void loadDetail(id);
    }
  },
});

/**
 * 切换到仓库信息时刷新一次，避免打开后数据过期
 */
function onMainTabChange(key: string | number) {
  if (key === 'warehouse' && drugId.value > 0) {
    warehousePanelRef.value?.reload?.();
  }
}

/**
 * 添加一条别名（支持一次输入多个，按分隔符拆）
 */
async function handleAddAlias() {
  const id = Number(drug.value?.id || 0);
  if (!id || !canManage.value) return;
  const parts = String(newAlias.value || '')
    .split(/[\n,，、;；|]+/)
    .map((s) => s.trim())
    .filter(Boolean);
  if (parts.length === 0) {
    message.warning('请输入别名');
    return;
  }
  adding.value = true;
  try {
    let lastRes: any = null;
    for (const part of parts) {
      lastRes = await addDrugAlias(id, part);
    }
    if (lastRes) applyDetail(lastRes);
    newAlias.value = '';
    message.success(parts.length > 1 ? `已添加 ${parts.length} 条别名` : '已添加');
    gridApiRef.value?.query?.();
  } finally {
    adding.value = false;
  }
}

/**
 * 删除一条别名
 */
async function handleDeleteAlias(row: AliasRow) {
  const id = Number(drug.value?.id || 0);
  const aliasId = Number(row?.id || 0);
  if (!id || !aliasId || !canManage.value) return;
  deletingId.value = aliasId;
  try {
    const res = await deleteDrugAlias(id, aliasId);
    applyDetail(res);
    message.success('已删除');
    gridApiRef.value?.query?.();
  } finally {
    deletingId.value = 0;
  }
}
</script>

<template>
  <Modal :title="titleText">
    <Spin :spinning="loading">
      <div v-if="drug?.id" class="drug-detail">
        <div class="drug-detail__head">
          <Image
            v-if="drug.image"
            :src="drug.image"
            :width="64"
            :height="64"
            class="drug-detail__img"
          />
          <div v-else class="drug-detail__img drug-detail__img--empty">无图</div>
          <div class="drug-detail__head-text">
            <div class="drug-detail__name">{{ drug.drug_name || '-' }}</div>
            <div class="drug-detail__meta">
              ID：{{ drug.id }}
              <span v-if="drug.drug_number"> · 编号：{{ drug.drug_number }}</span>
            </div>
          </div>
        </div>

        <Tabs
          v-model:active-key="mainTab"
          class="mt-3"
          @change="onMainTabChange"
        >
          <Tabs.TabPane key="basic" tab="基础信息">
            <Descriptions bordered size="small" :column="2">
              <DescriptionsItem label="拼音首拼">
                {{ drug.pinyin_simple || '-' }}
              </DescriptionsItem>
              <DescriptionsItem label="拼音全拼">
                {{ drug.pinyin_full || '-' }}
              </DescriptionsItem>
              <DescriptionsItem label="检索数字">
                {{ drug.search_digits || '-' }}
              </DescriptionsItem>
              <DescriptionsItem label="规格">
                {{ drug.specification || '-' }}
              </DescriptionsItem>
              <DescriptionsItem label="单位">
                {{ drug.unit_name || '-' }}
              </DescriptionsItem>
              <DescriptionsItem label="供应商">
                {{ drug.supplier_name || '-' }}
              </DescriptionsItem>
            </Descriptions>

            <div class="drug-detail__alias-head">
              <div class="drug-detail__alias-title">
                别名
                <Tag v-if="canManage" color="processing" class="ml-1">可维护</Tag>
                <Tag v-else class="ml-1">只读</Tag>
                <span class="drug-detail__alias-count">{{ aliasCountText }}</span>
              </div>
            </div>

            <div v-if="canManage" class="drug-detail__alias-add">
              <Input
                v-model:value="newAlias"
                allow-clear
                placeholder="输入别名后回车添加；多个可用顿号/逗号分隔"
                :disabled="adding"
                @press-enter="handleAddAlias"
              />
              <Button
                type="primary"
                class="ml-2"
                :loading="adding"
                @click="handleAddAlias"
              >
                添加
              </Button>
            </div>

            <div class="drug-detail__alias-list">
              <Empty
                v-if="aliases.length === 0"
                :image="Empty.PRESENTED_IMAGE_SIMPLE"
                description="暂无别名"
              />
              <div
                v-for="(a, idx) in aliases"
                :key="`${a.id || idx}_${a.alias}`"
                class="drug-detail__alias-row"
              >
                <div class="drug-detail__alias-main">
                  <span class="drug-detail__alias-name">{{ a.alias }}</span>
                  <span class="drug-detail__alias-py">
                    {{ a.pinyin_display || a.pinyin_simple || '-' }}
                  </span>
                </div>
                <Popconfirm
                  v-if="canManage"
                  title="确认删除该别名？"
                  ok-text="删除"
                  cancel-text="取消"
                  @confirm="handleDeleteAlias(a)"
                >
                  <Button
                    type="link"
                    danger
                    size="small"
                    :loading="deletingId === Number(a.id || 0)"
                  >
                    删除
                  </Button>
                </Popconfirm>
              </div>
            </div>
          </Tabs.TabPane>
          <Tabs.TabPane key="warehouse" tab="仓库信息">
            <DrugWarehousePanel ref="warehousePanelRef" :drug-id="drugId" />
          </Tabs.TabPane>
        </Tabs>
      </div>
      <Empty v-else-if="!loading" description="未找到药品" />
    </Spin>
  </Modal>
</template>

<style scoped>
.drug-detail__head {
  display: flex;
  gap: 12px;
  align-items: center;
}
.drug-detail__img {
  border-radius: 6px;
  object-fit: cover;
  flex-shrink: 0;
}
.drug-detail__img--empty {
  width: 64px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: hsl(var(--muted-foreground));
  background: hsl(var(--muted) / 0.3);
  border: 1px solid hsl(var(--border));
}
.drug-detail__name {
  font-size: 16px;
  font-weight: 600;
  line-height: 1.4;
}
.drug-detail__meta {
  margin-top: 4px;
  font-size: 12px;
  color: hsl(var(--muted-foreground));
}
.drug-detail__alias-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 16px;
  margin-bottom: 8px;
}
.drug-detail__alias-title {
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
.drug-detail__alias-count {
  margin-left: 6px;
  font-size: 12px;
  font-weight: 400;
  color: hsl(var(--muted-foreground));
}
.drug-detail__alias-add {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.drug-detail__alias-list {
  border: 1px solid hsl(var(--border));
  border-radius: 6px;
  min-height: 80px;
  max-height: 320px;
  overflow-y: auto;
}
.drug-detail__alias-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  padding: 8px 10px;
  border-bottom: 1px solid hsl(var(--border) / 0.7);
  font-size: 13px;
}
.drug-detail__alias-row:last-child {
  border-bottom: none;
}
.drug-detail__alias-main {
  min-width: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.drug-detail__alias-name {
  font-weight: 500;
  word-break: break-all;
}
.drug-detail__alias-py {
  color: hsl(var(--muted-foreground));
  font-size: 12px;
}
</style>
