<script lang="ts" setup>
/**
 * 医生设置页面
 *
 * @description 医生个人中心，包含个人资料、常用方、常用医嘱、常用诊断等功能
 * @author 系统
 * @date 2024
 */
import { onMounted, ref } from 'vue';

import { EllipsisText, Page, useVbenModal } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';

// 常用方编辑弹窗组件
import EditCommonPrescriptionModal from './components/EditCommonPrescriptionModal.vue';
// 常用方新增弹窗组件
import AddCommonPrescriptionModal from './components/AddCommonPrescriptionModal.vue';
// 签名查看和更新弹窗组件
import SignatureModal from './components/SignatureModal.vue';

import {
  Button,
  Card,
  Empty,
  Input,
  InputGroup,
  InputNumber,
  Modal,
  notification,
  Popconfirm,
  RadioButton,
  RadioGroup,
  Rate,
  Switch,
  Tag,
} from 'ant-design-vue';

import {
  createDoctorOrderApi,
  deleteCommonPrescriptionApi,
  getCommonPrescriptionListApi,
  getDoctorMyDiseaseListApi,
  getDoctorMyDoctorOrderApi,
  getDoctorMyInfoApi,
  saveRegisterNumApi,
  saveServicePriceApi,
} from '#/views/doctor/settings/api';
import type { CommonPrescriptionResponse } from '#/views/doctor/settings/api';
import {
  deleteMyMedicalRecordEntry,
  getMyMedicalRecordEntryList,
} from '#/views/doctor/medical-record/api';
import { MEDICAL_RECORD_FIELD_OPTIONS } from '#/views/doctor/medical-record/config/constants';
import SensitiveText from '#/components/sensitive-text/SensitiveText.vue';

const userInfoStore = useUserStore();

// 映射数据（示例）
const identityMap = { 1: '中医', 2: '西医' };

// Tab状态持久化
const TAB_STORAGE_KEY = 'xk_doctor_settings_tab';
const savedTab = localStorage.getItem(TAB_STORAGE_KEY);
const activeTabBar = ref(savedTab ? Number(savedTab) : 1);

/**
 * Tab栏配置
 * - 1: 个人资料
 * - 3: 常用方（新增）
 * - 4: 常用医嘱
 * - 5: 常用诊断
 * - 6: 常用词条
 */
const tabBar = [
  {
    value: 1,
    label: '个人资料',
  },
  {
    value: 3,
    label: '常用方',
  },
  {
    value: 4,
    label: '常用医嘱',
  },
  {
    value: 5,
    label: '常用诊断',
  },
  {
    value: 6,
    label: '常用词条',
  },
];

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString();
};
const data = ref();
/**
 * 获取当前登录医生信息
 */
const getMyInfo = () => {
  getDoctorMyInfoApi({}).then((res) => {
    data.value = res;
  });
};
/**
 * 保存挂号服务
 */
const saveServicePrice = () => {
  saveServicePriceApi({
    status: data.value.service.register_status,
    price: data.value.service.register_price,
  }).then(() => {
    notification.success({
      message: '保存成功',
      duration: 2,
    });
    // getMyInfo();
  });
};
/**
 * 保存每日号源上限
 * register_num 在医生信息表（yii_doctor_info）上，与挂号开关/价格（yii_doctor_service）分表，
 * 所以单独走 save-register-num 接口；0 表示不放号（患者端显示约满）
 */
const saveRegisterNum = () => {
  saveRegisterNumApi({
    register_num: data.value.register_num,
  }).then(() => {
    notification.success({
      message: '保存成功',
      duration: 2,
    });
  });
};

const getDoctorMyDoctorOrder = () => {
  getDoctorMyDoctorOrderApi().then((res) => {
    doctorOrder.value = res;
  });
};
/**
 * 诊断列表
 */
const doctorMyDiseaseList = ref([]);
const getDoctorMyDiseaseList = () => {
  getDoctorMyDiseaseListApi().then((res) => {
    doctorMyDiseaseList.value = res;
  });
};

/** 常用词条（医生维度） */
const myEntryCommonList = ref<any[]>([]);
const getMyEntryCommonList = () => {
  getMyMedicalRecordEntryList({ limit: 200 })
    .then((res) => {
      myEntryCommonList.value = Array.isArray(res) ? res : [];
    })
    .catch(() => {
      myEntryCommonList.value = [];
    });
};
const fieldCodeLabel = (code: string) => {
  const hit = MEDICAL_RECORD_FIELD_OPTIONS.find((o) => o.value === code);
  return hit?.label || code || '-';
};
const removeMyEntryCommon = (id: number) => {
  deleteMyMedicalRecordEntry(id).then(() => {
    notification.success({ message: '已移除常用词条' });
    getMyEntryCommonList();
  });
};

// ==================== 常用方相关 ====================

/**
 * 常用方数据
 * @description 包含西药、中药、颗粒药三种类型的常用方列表
 */
const commonPrescriptionData = ref<CommonPrescriptionResponse | null>(null);

/**
 * 常用方加载状态
 */
const commonPrescriptionLoading = ref(false);

/**
 * 获取常用方列表
 * @description 获取当前医生的所有常用方
 */
const getCommonPrescriptionList = async () => {
  commonPrescriptionLoading.value = true;
  try {
    const res = await getCommonPrescriptionListApi();
    commonPrescriptionData.value = res;
  } catch (error) {
    console.error('获取常用方列表失败:', error);
  } finally {
    commonPrescriptionLoading.value = false;
  }
};

/**
 * 删除常用方
 * @param id 常用方ID
 * @param type 类型：west-西药，chinese-中药，granular-颗粒药
 */
const handleDeleteCommonPrescription = async (id: number, type: string) => {
  try {
    await deleteCommonPrescriptionApi(id, type);
    notification.success({
      message: '删除成功',
      duration: 2,
    });
    // 刷新列表
    getCommonPrescriptionList();
  } catch (error) {
    notification.error({
      message: '删除失败',
      duration: 2,
    });
  }
};

/**
 * 获取药品名称列表（用于展示）
 * @param recipes 药品列表
 * @param nameField 名称字段
 */
const getDrugNames = (recipes: any[], nameField = 'drug_name') => {
  if (!recipes || recipes.length === 0) return '暂无药品';
  return recipes.map((item) => item[nameField] || item.name).join('、');
};

const formatField = (value?: string | null) => (value?.trim() ? value : '—');

const getDrugCount = (recipes: any[]) => recipes?.length || 0;

// ==================== 常用方编辑弹窗 ====================

const [EditCommonPrescriptionModals, EditCommonPrescriptionModalApi] =
  useVbenModal({
    connectedComponent: EditCommonPrescriptionModal,
  });

// ==================== 常用方新增弹窗 ====================

const [AddCommonPrescriptionModals, AddCommonPrescriptionModalApi] =
  useVbenModal({
    connectedComponent: AddCommonPrescriptionModal,
  });

// ==================== 签名查看和更新弹窗 ====================

const [SignatureModals, SignatureModalApi] = useVbenModal({
  connectedComponent: SignatureModal,
});

/**
 * 打开新增常用方弹窗
 */
const handleAddCommonPrescription = () => {
  AddCommonPrescriptionModalApi.setData({
    onSave: () => {
      // 刷新列表
      getCommonPrescriptionList();
    },
  });
  AddCommonPrescriptionModalApi.open();
};

/**
 * 打开编辑常用方弹窗
 * @param prescription 常用方信息
 * @param recipes 药品列表
 * @param type 类型：west-西药，chinese-中药，granular-颗粒药
 */
const handleEditCommonPrescription = (
  prescription: any,
  recipes: any[],
  type: 'west' | 'chinese' | 'granular',
) => {
  EditCommonPrescriptionModalApi.setData({
    prescription,
    recipes,
    type,
    onSave: () => {
      // 刷新列表
      getCommonPrescriptionList();
    },
  });
  EditCommonPrescriptionModalApi.open();
};

/**
 * 医嘱列表
 */
const doctorOrder = ref([]);

/**
 * Tab切换事件处理
 * @description 根据当前选中的Tab加载对应的数据
 */
const tabBarChange = () => {
  // 保存当前tab到localStorage
  localStorage.setItem(TAB_STORAGE_KEY, String(activeTabBar.value));
  
  switch (activeTabBar.value) {
    case 1: {
      // 个人资料
      getMyInfo();
      break;
    }
    case 3: {
      // 常用方
      getCommonPrescriptionList();
      break;
    }
    case 4: {
      // 常用医嘱
      getDoctorMyDoctorOrder();
      break;
    }
    case 5: {
      // 常用诊断
      getDoctorMyDiseaseList();
      break;
    }
    case 6: {
      // 常用词条
      getMyEntryCommonList();
      break;
    }
  }
};
// 初始化时加载基础数据和当前tab对应的数据
onMounted(() => {
  getMyInfo(); // 基础数据（个人资料）始终需要
  // 如果当前tab不是1，还需要加载对应tab的数据
  if (activeTabBar.value !== 1) {
    tabBarChange();
  }
});

const doctorOrderContent = ref('');
/**
 * 创建医嘱
 */
const createDoctorOrder = () => {
  createDoctorOrderApi(doctorOrderContent.value).then((res) => {
    doctorOrderContent.value = '';
    getDoctorMyDoctorOrder();
    notification.success({
      message: '添加成功',
      duration: 2,
    });
  });
};

/**
 * 打开签名查看和更新弹窗
 */
const handleViewSignature = () => {
  const signature = data.value?.identity_info?.sign_image || '';
  SignatureModalApi.setData({
    signature,
    onSuccess: () => {
      // 刷新医生信息
      getMyInfo();
    },
  });
  SignatureModalApi.open();
};
</script>

<template>
  <Page
    :title="`${userInfoStore.userInfo?.nick_name}的个人中心`"
    auto-content-height
  >
    <div class="pb-2">
      <RadioGroup
        v-model:value="activeTabBar"
        button-style="solid"
        @change="tabBarChange"
      >
        <RadioButton
          v-for="item in tabBar"
          :key="item.value"
          :value="item.value"
        >
          {{ item.label }}
        </RadioButton>
      </RadioGroup>
    </div>
    <Card v-if="data && activeTabBar === 1" title="个人资料">
      <!-- 头部信息 -->
      <div class="mb-8 flex flex-col gap-6 md:flex-row md:gap-8">
        <div class="relative">
          <img
            :src="data?.avatar"
            alt="医生头像"
            class="h-24 w-24 rounded-full border-4 border-white object-cover shadow-lg md:h-32 md:w-32"
          />
          <Button
            type="primary"
            size="small"
            class="absolute bottom-0 right-0"
            @click="handleViewSignature"
          >
            查看签名
          </Button>
        </div>

        <div class="flex-1">
          <div class="mb-3 flex items-center gap-4">
            <h1 class="text-2xl font-bold md:text-3xl">
              {{ data.name }}
              <span
                v-if="data.star"
                class="ml-2 rounded-full bg-amber-100 px-3 py-1 text-sm text-amber-700"
              >
                {{ data.title.name }}
              </span>
            </h1>
            <p class="flex items-center gap-2">
              <PhoneIcon class="h-5 w-5" />
              <SensitiveText :record="data" field="mobile" />
            </p>
            <p class="flex items-center gap-2">
              <CalendarIcon class="h-5 w-5" />
              入驻时间：{{ formatDate(data.created_at) }}
            </p>
          </div>

          <div class="flex flex-wrap gap-2">
            <Tag color="#455cda">{{ data.title.name }}</Tag>
            <Tag color="#455cda">{{ identityMap[data.identity] }}</Tag>
            <Tag color="#455cda">{{ data.depart.name }}</Tag>
          </div>

          <!--          <div class="mt-4 space-y-1 flex">-->
          <!--            签名：-->
          <!--            <img :src="`data:image/jpeg;base64,${data.identity_info.sign_image}`" style="width: 120px; height: 60px; background-color: white" alt="医生签名" />-->
          <!--          </div>-->

          <div class="mt-4 space-y-1">
            诊所：
            <span v-for="item in data.stores">
              <Tag v-if="item.store?.name" class="mt-2" color="#455cda">{{
                item.store?.name
              }}</Tag>
            </span>
          </div>
        </div>
        <div class="flex-1">
          <div class="mb-3 flex items-center gap-4">
            挂号服务
            <Switch
              v-model:checked="data.service.register_status"
              :checked-value="1"
              :un-checked-value="0"
            />
            <InputNumber
              v-if="data.service.register_status === 1"
              v-model:value="data.service.register_price"
              style="min-width: 100px"
              @keydown.enter="saveServicePrice"
            >
              <template #addonAfter> 元 </template>
            </InputNumber>
            <Button type="primary" @click="saveServicePrice">保存</Button>
            【{{ data.service.register_status === 1 ? '开启' : '关闭' }}】
          </div>

          <!-- 每日号源上限：挂号防超卖的额度来源，0 表示不放号（患者端显示约满） -->
          <div class="mb-3 flex items-center gap-4">
            每日号源上限
            <InputNumber
              v-model:value="data.register_num"
              :min="0"
              :max="999"
              :precision="0"
              style="min-width: 100px"
              @keydown.enter="saveRegisterNum"
            >
              <template #addonAfter> 个/天 </template>
            </InputNumber>
            <Button type="primary" @click="saveRegisterNum">保存</Button>
          </div>

          <div class="flex flex-wrap gap-2"></div>

          <div class="mt-4 space-y-1"></div>
        </div>
      </div>

      <!-- 主要内容 -->
      <div class="grid gap-8 md:grid-cols-2">
        <!-- 左侧内容 -->
        <div class="space-y-6">
          <h3 class="border-l-4 border-blue-500 pl-3 text-lg font-semibold">
            擅长领域
          </h3>
          <EllipsisText :line="3" :tooltip="false" expand>
            <div
              class="prose max-w-none whitespace-pre-wrap"
              style="text-indent: 2em"
            >
              {{ data.good_at }}
            </div>
          </EllipsisText>

          <h3 class="border-l-4 border-blue-500 pl-3 text-lg font-semibold">
            医生简介
          </h3>
          <EllipsisText :line="3" :tooltip="false" expand>
            <div
              class="prose max-w-none whitespace-pre-wrap"
              style="text-indent: 2em"
            >
              {{ data.intro }}
            </div>
          </EllipsisText>
        </div>

        <!-- 右侧数据 -->
        <div class="space-y-6">
          <h3 class="border-l-4 border-blue-500 pl-3 text-lg font-semibold">
            执业数据
          </h3>

          <div class="flex flex-wrap space-y-4">
            <div
              class="flex w-1/2 items-center justify-between rounded-lg bg-gray-50 p-4 dark:bg-[#020817]"
            >
              <span class="">问诊量</span>
              <span
                class="font-semibold text-blue-600"
                style="font-weight: bold"
                >{{ data.inquiries }}</span>
            </div>

            <div
              class="flex w-1/2 items-center justify-between rounded-lg bg-gray-50 p-4 dark:bg-[#020817]"
              style="margin-top: 0;"
            >
              <span class="">综合评分</span>
              <Rate :value="data.grade" disabled style="color: #455cda" />
            </div>

            <div
              class="flex w-1/2 items-center justify-between rounded-lg bg-gray-50 p-4 dark:bg-[#020817]"
              style="margin-top: 0;"
            >
              <span class="">平均回复</span>
              <span
                class="font-semibold text-blue-600"
                style="font-weight: bold"
              >
                {{ data.average_response }} 小时
              </span>
            </div>
          </div>
          <div class="space-y-4">
<!--            <div class="space-y-2 rounded-lg bg-gray-50 p-4 dark:bg-[#020817]">-->
<!--              <div class="flex justify-between text-sm">-->
<!--                <span class="">好评率</span>-->
<!--                <span class="font-medium">{{ parseFloat(data.applause_rate) }}%</span>-->
<!--              </div>-->
<!--              <div class="h-2 overflow-hidden rounded-full bg-gray-200">-->
<!--                <div-->
<!--                  :style="{ width: `${parseFloat(data.applause_rate)}%` }"-->
<!--                  class="h-full bg-blue-500 transition-all duration-500"-->
<!--                ></div>-->
<!--              </div>-->
<!--            </div>-->

            <div class="space-y-2 rounded-lg bg-gray-50 p-4 dark:bg-[#020817]">
              <div class="flex justify-between text-sm">
                <span>接诊率{{ parseFloat(data.reception_rate) }}</span>
                <span class="font-medium">{{ parseFloat(data.reception_rate) }}%</span>
              </div>
              <div class="h-2 overflow-hidden rounded-full bg-gray-200">
                <div
                  :style="{ width: `${parseFloat(data.reception_rate)}%` }"
                  class="h-full bg-green-500 transition-all duration-500"
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Card>
    <Card v-else-if="data && activeTabBar === 2" title="我的处方" />
    <!-- 常用方Tab内容 -->
    <Card v-else-if="activeTabBar === 3">
      <template #title>
        <div class="flex items-center justify-between">
          <span>常用方</span>
          <Button type="primary" @click="handleAddCommonPrescription">
            新增常用方
          </Button>
        </div>
      </template>
      <div v-if="commonPrescriptionLoading" class="text-center py-8">
        加载中...
      </div>
      <div v-else-if="!commonPrescriptionData" class="text-center py-8">
        <Empty description="暂无数据" />
      </div>
      <div v-else>
        <!-- 西药常用方 -->
        <div
          v-if="
            commonPrescriptionData.west_prescription &&
            commonPrescriptionData.west_prescription.length > 0
          "
          class="mb-6"
        >
          <h3 class="mb-4 border-l-4 border-blue-500 pl-3 text-lg font-semibold">
            西药常用方
          </h3>
          <div
            v-for="(item, index) in commonPrescriptionData.west_prescription"
            :key="item.id"
            class="mb-3 rounded-lg border border-border bg-muted/30 p-4"
          >
            <div
              class="mb-3 flex items-center justify-between gap-3 border-b border-border pb-3"
            >
              <div class="flex min-w-0 flex-1 items-center gap-2">
                <span class="truncate font-medium">{{
                  item.name || `西药处方 ${index + 1}`
                }}</span>
                <Tag color="blue"
                  >{{ getDrugCount(commonPrescriptionData.west[index]) }}种药品</Tag
                >
              </div>
              <div class="flex shrink-0 gap-2">
                <Button
                  type="primary"
                  size="small"
                  @click="
                    handleEditCommonPrescription(
                      item,
                      commonPrescriptionData.west[index],
                      'west',
                    )
                  "
                >
                  编辑
                </Button>
                <Popconfirm
                  title="确定要删除这个常用方吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="handleDeleteCommonPrescription(item.id, 'west')"
                >
                  <Button type="primary" danger size="small">删除</Button>
                </Popconfirm>
              </div>
            </div>
            <div class="space-y-2 text-sm leading-relaxed">
              <p>
                <span class="font-medium text-muted-foreground">临床诊断：</span>
                {{ formatField(item.clinical_diagnose) }}
              </p>
              <p>
                <span class="font-medium text-muted-foreground">医嘱：</span>
                {{ formatField(item.doctor_order) }}
              </p>
              <p>
                <span class="font-medium text-muted-foreground">药品：</span>
                {{ getDrugNames(commonPrescriptionData.west[index]) }}
              </p>
            </div>
          </div>
        </div>

        <!-- 中药常用方 -->
        <div
          v-if="
            commonPrescriptionData.chin_prescription &&
            commonPrescriptionData.chin_prescription.length > 0
          "
          class="mb-6"
        >
          <h3 class="mb-4 border-l-4 border-green-500 pl-3 text-lg font-semibold">
            中药常用方
          </h3>
          <div
            v-for="(item, index) in commonPrescriptionData.chin_prescription"
            :key="item.id"
            class="mb-3 rounded-lg border border-border bg-muted/30 p-4"
          >
            <div
              class="mb-3 flex items-center justify-between gap-3 border-b border-border pb-3"
            >
              <div class="flex min-w-0 flex-1 items-center gap-2">
                <span class="truncate font-medium">{{
                  item.name || `中药处方 ${index + 1}`
                }}</span>
                <Tag color="green"
                  >{{ getDrugCount(commonPrescriptionData.chinese[index]) }}种药品</Tag
                >
              </div>
              <div class="flex shrink-0 gap-2">
                <Button
                  type="primary"
                  size="small"
                  @click="
                    handleEditCommonPrescription(
                      item,
                      commonPrescriptionData.chinese[index],
                      'chinese',
                    )
                  "
                >
                  编辑
                </Button>
                <Popconfirm
                  title="确定要删除这个常用方吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="handleDeleteCommonPrescription(item.id, 'chinese')"
                >
                  <Button type="primary" danger size="small">删除</Button>
                </Popconfirm>
              </div>
            </div>
            <div class="space-y-2 text-sm leading-relaxed">
              <p>
                <span class="font-medium text-muted-foreground">临床诊断：</span>
                {{ formatField(item.clinical_diagnose) }}
              </p>
              <p>
                <span class="font-medium text-muted-foreground">医嘱：</span>
                {{ formatField(item.doctor_order) }}
              </p>
              <p>
                <span class="font-medium text-muted-foreground">调配方式：</span>
                {{ item.rule_type === 1 ? '自制剂' : '委托调剂' }}
                <span class="ml-4">剂量：{{ item.dosage || 7 }}天/剂</span>
                <span class="ml-4">频次：{{ item.day_dosage || 2 }}次/天</span>
              </p>
              <p v-if="item.rule_type === 2">
                <span class="font-medium text-muted-foreground">委托调剂配置：</span>
                <span v-if="item.process_rule_name">制剂：{{ item.process_rule_name }}</span>
                <span v-if="item.child_process_rule_name" class="ml-4">煎法：{{ item.child_process_rule_name }}</span>
                <span v-if="item.process_rule_note_name" class="ml-4">备注：{{ item.process_rule_note_name }}</span>
              </p>
              <p>
                <span class="font-medium text-muted-foreground">药品：</span>
                {{ getDrugNames(commonPrescriptionData.chinese[index], 'drug_name') }}
              </p>
            </div>
          </div>
        </div>

        <!-- 颗粒药常用方 -->
        <div
          v-if="
            commonPrescriptionData.granular_prescription &&
            commonPrescriptionData.granular_prescription.length > 0
          "
          class="mb-6"
        >
          <h3 class="mb-4 border-l-4 border-orange-500 pl-3 text-lg font-semibold">
            颗粒药常用方
          </h3>
          <div
            v-for="(item, index) in commonPrescriptionData.granular_prescription"
            :key="item.id"
            class="mb-3 rounded-lg border border-border bg-muted/30 p-4"
          >
            <div
              class="mb-3 flex items-center justify-between gap-3 border-b border-border pb-3"
            >
              <div class="flex min-w-0 flex-1 items-center gap-2">
                <span class="truncate font-medium">{{
                  item.name || `颗粒药处方 ${index + 1}`
                }}</span>
                <Tag color="orange"
                  >{{ getDrugCount(commonPrescriptionData.granular[index]) }}种药品</Tag
                >
              </div>
              <div class="flex shrink-0 gap-2">
                <Button
                  type="primary"
                  size="small"
                  @click="
                    handleEditCommonPrescription(
                      item,
                      commonPrescriptionData.granular[index],
                      'granular',
                    )
                  "
                >
                  编辑
                </Button>
                <Popconfirm
                  title="确定要删除这个常用方吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="handleDeleteCommonPrescription(item.id, 'granular')"
                >
                  <Button type="primary" danger size="small">删除</Button>
                </Popconfirm>
              </div>
            </div>
            <div class="space-y-2 text-sm leading-relaxed">
              <p>
                <span class="font-medium text-muted-foreground">临床诊断：</span>
                {{ formatField(item.clinical_diagnose) }}
              </p>
              <p>
                <span class="font-medium text-muted-foreground">医嘱：</span>
                {{ formatField(item.doctor_order) }}
              </p>
              <p>
                <span class="font-medium text-muted-foreground">药品：</span>
                {{ getDrugNames(commonPrescriptionData.granular[index], 'name') }}
              </p>
            </div>
          </div>
        </div>

        <!-- 无数据提示 -->
        <div
          v-if="
            (!commonPrescriptionData.west_prescription ||
              commonPrescriptionData.west_prescription.length === 0) &&
            (!commonPrescriptionData.chin_prescription ||
              commonPrescriptionData.chin_prescription.length === 0) &&
            (!commonPrescriptionData.granular_prescription ||
              commonPrescriptionData.granular_prescription.length === 0)
          "
          class="text-center py-8"
        >
          <Empty description="暂无常用方，请在开处方时保存常用方" />
        </div>
      </div>
    </Card>
    <Card v-else-if="doctorOrder && activeTabBar === 4" title="常用医嘱">
      <div class="w-full">
        <InputGroup>
          <Input
            v-model:value="doctorOrderContent"
            style="width: calc(100% - 200px)"
            @keydown.enter="createDoctorOrder"
          />
          <Button type="primary" @click="createDoctorOrder">添加</Button>
        </InputGroup>
      </div>
      <div class="mt-10">
        <Button
          v-for="item in doctorOrder"
          style="margin: 0 10px"
          type="primary"
        >
          {{ item.content }}
        </Button>
      </div>
    </Card>
    <Card v-else-if="data && activeTabBar === 5" title="常用诊断">
      <Button
        v-for="item in doctorMyDiseaseList"
        style="margin: 0 10px"
        type="primary"
      >
        {{ item.disease.name }}
      </Button>
    </Card>
    <Card v-else-if="data && activeTabBar === 6" title="常用词条">
      <div class="mb-3 text-sm text-gray-500">
        在病历接诊气泡中点「加常用」可收藏；此处可移除。点击标签本身无操作。
      </div>
      <Empty v-if="!myEntryCommonList.length" description="暂无常用词条" />
      <div v-else class="flex flex-wrap gap-2">
        <Tag
          v-for="item in myEntryCommonList"
          :key="item.id"
          color="processing"
          class="mb-2"
        >
          <span class="mr-1 text-xs opacity-70">{{ fieldCodeLabel(item.field_code) }}</span>
          {{ item.title || item.content }}
          <Popconfirm
            title="确定从常用词条中移除吗？"
            @confirm="removeMyEntryCommon(item.id)"
          >
            <a class="ml-2 text-red-500" @click.stop>移除</a>
          </Popconfirm>
        </Tag>
      </div>
    </Card>

    <!-- 常用方编辑弹窗 -->
    <EditCommonPrescriptionModals />
    <!-- 常用方新增弹窗 -->
    <AddCommonPrescriptionModals />
    <!-- 签名查看和更新弹窗 -->
    <SignatureModals />
  </Page>
</template>
<style lang="scss" scoped>
/* 自定义小标签样式 */
//.pill-info {
//  @apply rounded-full bg-gray-100 px-3 py-1 text-sm ;
//}

/* 优化行高 */
.prose {
  @apply leading-relaxed;
}

/* 悬停动画 */
.hover-animate {
  @apply transition-transform duration-300 hover:scale-[1.02];
}
</style>
