<script lang="ts" setup>
/**
 * 常用快捷标签（诊断 / 医嘱 / 病历词条）
 * - 正文已包含该文案时高亮（is-active）
 * - 点击：已在正文则移除，否则追加（由父级 onEntryPick 统一 toggle）
 */
import { computed, onMounted, ref, watch } from 'vue';

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

import {
  fetchDoctorOrderListCached,
  fetchMyDiseaseListCached,
  fetchMyEntriesByField,
  invalidateCommonChipsCache,
} from '../utils/commonChipsCache';

const props = withDefaults(
  defineProps<{
    /** diagnosis=常用诊断；doctor_order=常用医嘱；entry=常用词条 */
    source: 'diagnosis' | 'doctor_order' | 'entry';
    /** entry 时必填 */
    fieldCode?: string;
    /** 当前字段正文，用于高亮已选 */
    fieldValue?: string;
    limit?: number;
    disabled?: boolean;
  }>(),
  {
    fieldCode: '',
    fieldValue: '',
    limit: 12,
    disabled: false,
  },
);

const emit = defineEmits<{
  select: [text: string];
}>();

type ChipItem = { id: string | number; text: string };

const chips = ref<ChipItem[]>([]);
const loading = ref(false);

/** 文案是否已出现在字段值中（逗号分段或整行/包含） */
function textInField(fieldValue: string, text: string) {
  const t = String(text || '').trim();
  if (!t) return false;
  const v = String(fieldValue || '');
  if (!v) return false;
  if (v.split('，').map((s) => s.trim()).includes(t)) return true;
  if (v.split('\n').map((s) => s.trim()).includes(t)) return true;
  return v.includes(t);
}

const activeSet = computed(() => {
  const set = new Set<string>();
  const v = props.fieldValue || '';
  for (const c of chips.value) {
    if (textInField(v, c.text)) set.add(c.text);
  }
  return set;
});

/**
 * 拉取常用项（诊断/医嘱/词条均走模块缓存，进页多实例只打一次网）
 */
async function loadChips() {
  loading.value = true;
  try {
    if (props.source === 'diagnosis') {
      const list = await fetchMyDiseaseListCached();
      chips.value = (list || [])
        .map((item: any) => {
          const d = item?.disease || item;
          const text = String(d?.name || '').trim();
          return text ? { id: d?.id ?? item?.id, text } : null;
        })
        .filter(Boolean)
        .slice(0, props.limit) as ChipItem[];
      return;
    }
    if (props.source === 'entry') {
      if (!props.fieldCode) {
        chips.value = [];
        return;
      }
      // 全量 my-entry-list 一次，再按 field_code 本地切片
      const list = await fetchMyEntriesByField(props.fieldCode, props.limit);
      chips.value = (list || [])
        .map((item: any) => {
          const text = String(item?.content || item?.title || '').trim();
          return text
            ? { id: item?.id ?? item?.entry_id ?? text, text }
            : null;
        })
        .filter(Boolean)
        .slice(0, props.limit) as ChipItem[];
      return;
    }
    const res = await fetchDoctorOrderListCached();
    const my = (res?.my || [])
      .map((item: any) => {
        const text = String(item?.content || '').trim();
        return text ? { id: item?.id ?? text, text } : null;
      })
      .filter(Boolean) as ChipItem[];
    if (my.length > 0) {
      chips.value = my.slice(0, props.limit);
      return;
    }
    chips.value = (res?.common || [])
      .map((item: any) => {
        const text = String(item?.name || item?.content || '').trim();
        return text ? { id: item?.id ?? text, text } : null;
      })
      .filter(Boolean)
      .slice(0, props.limit) as ChipItem[];
  } finally {
    loading.value = false;
  }
}

/** 强制刷新：清缓存后重拉（新增/删除常用后用） */
async function reloadChips() {
  invalidateCommonChipsCache(props.source);
  await loadChips();
}

function onPick(item: ChipItem) {
  if (props.disabled || !item?.text) return;
  emit('select', item.text);
}

const labelText = computed(() => {
  if (props.source === 'diagnosis') return '常用诊断';
  if (props.source === 'doctor_order') return '常用医嘱';
  return '常用词条';
});

watch(
  () => [props.source, props.fieldCode] as const,
  () => {
    loadChips();
  },
);

onMounted(() => {
  loadChips();
});

defineExpose({ reload: reloadChips });
</script>
<template>
  <div v-if="chips.length > 0" class="dx-order-chips">
    <span class="dx-order-chips__label">{{ labelText }}</span>
    <div class="dx-order-chips__list">
      <Tag
        v-for="item in chips"
        :key="`${item.id}_${item.text}`"
        class="dx-order-chips__tag"
        :class="{
          'is-disabled': disabled,
          'is-active': activeSet.has(item.text),
        }"
        :color="activeSet.has(item.text) ? 'success' : 'processing'"
        @click="onPick(item)"
      >
        {{ item.text }}
      </Tag>
    </div>
  </div>
</template>
<style scoped>
.dx-order-chips {
  margin-top: 8px;
}
.dx-order-chips__label {
  display: block;
  margin-bottom: 6px;
  font-size: 12px;
  color: hsl(var(--muted-foreground));
}
.dx-order-chips__list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.dx-order-chips__tag {
  cursor: pointer;
  user-select: none;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
}
.dx-order-chips__tag.is-active {
  font-weight: 600;
}
.dx-order-chips__tag.is-disabled {
  cursor: not-allowed;
  opacity: 0.55;
}
</style>
