<script lang="ts" setup>
/**
 * 病历文本域双击放大编辑弹窗
 * - 内嵌关键字搜索气泡 + 常用快捷（诊断/医嘱）
 * - 确认或弹窗内文本域再双击：写回并关闭
 * - 禁止点遮罩关闭，避免误丢编辑内容
 */
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { Textarea } from 'ant-design-vue';

import CommonDxOrderChips from './CommonDxOrderChips.vue';
import EntryKeywordBubble, {
  type MedicalRecordEntryItem,
} from './EntryKeywordBubble.vue';

const draft = ref('');
const fieldLabel = ref('编辑内容');
const onConfirmCb = ref<((v: string) => void) | null>(null);
type ExpandBubbleSource =
  | 'entry'
  | 'diagnosis'
  | 'doctor_order'
  | 'tcm_disease'
  | 'tcm_syndrome'
  | 'tcm_method';
const source = ref<ExpandBubbleSource>('entry');
const fieldCode = ref('');
const storeId = ref(0);
const showChips = ref(false);
/** 气泡内展示常用|我的（与系统配置 mr_common_display_mode 对齐） */
const showCommonInBubble = ref(false);
const joinMode = ref<'comma' | 'newline' | 'replace'>('newline');
const readonly = ref(false);

const [Modal, modalApi] = useVbenModal({
  title: '编辑',
  class: 'w-[780px]',
  draggable: true,
  closeOnClickModal: false,
  onConfirm() {
    confirmAndClose();
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      draft.value = '';
      onConfirmCb.value = null;
      source.value = 'entry';
      fieldCode.value = '';
      showChips.value = false;
      showCommonInBubble.value = false;
      return;
    }
    const data = modalApi.getData<{
      title?: string;
      value?: string;
      onConfirm?: (v: string) => void;
      source?: ExpandBubbleSource;
      fieldCode?: string;
      storeId?: number;
      showChips?: boolean;
      showCommonInBubble?: boolean;
      joinMode?: 'comma' | 'newline' | 'replace';
      readonly?: boolean;
    }>();
    fieldLabel.value = data?.title || '编辑内容';
    draft.value = data?.value || '';
    onConfirmCb.value = data?.onConfirm || null;
    source.value = data?.source || 'entry';
    fieldCode.value = data?.fieldCode || '';
    storeId.value = Number(data?.storeId || 0);
    showChips.value = !!data?.showChips;
    showCommonInBubble.value = !!data?.showCommonInBubble;
    joinMode.value = data?.joinMode || 'newline';
    readonly.value = !!data?.readonly;
    modalApi.setState({ title: fieldLabel.value });
  },
});

const showBubble = computed(() => {
  if (readonly.value) return false;
  if (source.value === 'entry') return !!fieldCode.value;
  return (
    source.value === 'diagnosis' ||
    source.value === 'doctor_order' ||
    source.value === 'tcm_disease' ||
    source.value === 'tcm_syndrome' ||
    source.value === 'tcm_method'
  );
});

/** 中文逗号拼接，去重 */
function appendCommaText(base: string, add: string) {
  if (!add) return base || '';
  const parts = (base || '').split('，').map((s) => s.trim()).filter(Boolean);
  if (parts.includes(add)) return parts.join('，');
  parts.push(add);
  return parts.join('，');
}

function removeCommaText(base: string, remove: string) {
  if (!base || !remove) return base || '';
  return (base || '')
    .split('，')
    .map((s) => s.trim())
    .filter((s) => s && s !== remove)
    .join('，');
}

function appendNewline(base: string, add: string) {
  if (!add) return base || '';
  if (!base) return add;
  return `${base}${base.endsWith('\n') ? '' : '\n'}${add}`;
}

function removeNewline(base: string, remove: string) {
  if (!base || !remove) return base || '';
  const lines = base.split('\n');
  const idx = lines.findIndex((l) => l.trim() === remove.trim());
  if (idx >= 0) {
    lines.splice(idx, 1);
    return lines.join('\n');
  }
  const i = base.indexOf(remove);
  if (i < 0) return base;
  return `${base.slice(0, i)}${base.slice(i + remove.length)}`
    .replace(/\n{3,}/g, '\n\n')
    .replace(/^\n+|\n+$/g, '');
}

function containsText(base: string, text: string) {
  const t = String(text || '').trim();
  if (!t) return false;
  const v = String(base || '');
  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);
}

/** 气泡/快捷写入草稿（已有则删除，实现选择/取消） */
function applyPick(text: string) {
  const t = String(text || '').trim();
  if (!t || readonly.value) return;
  if (joinMode.value === 'replace') {
    draft.value = String(draft.value || '').trim() === t ? '' : t;
    return;
  }
  if (joinMode.value === 'comma') {
    draft.value = containsText(draft.value, t)
      ? removeCommaText(draft.value, t)
      : appendCommaText(draft.value, t);
    return;
  }
  draft.value = containsText(draft.value, t)
    ? removeNewline(draft.value, t)
    : appendNewline(draft.value, t);
}

function onBubbleSelect(item: MedicalRecordEntryItem) {
  applyPick(item.content || item.title || '');
}

function confirmAndClose() {
  onConfirmCb.value?.(draft.value);
  modalApi.close();
}
</script>
<template>
  <Modal>
    <div class="py-2">
      <div v-if="showBubble" class="mb-2">
        <EntryKeywordBubble
          :source="source"
          :field-code="fieldCode"
          :store-id="storeId"
          :placeholder="
            source === 'diagnosis'
              ? '诊断关键字/首拼'
              : source === 'doctor_order'
                ? '医嘱关键字/首拼'
                : source === 'tcm_disease' ||
                    source === 'tcm_syndrome' ||
                    source === 'tcm_method'
                  ? `${fieldLabel}关键字/首拼/全拼`
                  : '词条关键字/首拼'
          "
          :disabled="readonly"
          :show-common-in-bubble="showCommonInBubble"
          @select="onBubbleSelect"
        />
      </div>
      <Textarea
        v-model:value="draft"
        :rows="12"
        :placeholder="fieldLabel"
        :disabled="readonly"
        class="w-full"
        allow-clear
        @dblclick="confirmAndClose"
      />
      <CommonDxOrderChips
        v-if="
          showChips &&
          (source === 'diagnosis' ||
            source === 'doctor_order' ||
            source === 'entry')
        "
        :source="
          source === 'diagnosis'
            ? 'diagnosis'
            : source === 'doctor_order'
              ? 'doctor_order'
              : 'entry'
        "
        :field-code="fieldCode"
        :field-value="draft"
        :disabled="readonly"
        @select="applyPick"
      />
      <div class="mt-2 text-xs text-muted-foreground">
        可先搜索/点常用写入；双击文本域或点确定写回关闭；Ctrl+Enter 在主面板切换模块
      </div>
    </div>
  </Modal>
</template>
