<template>
  <div class="p-2">
    <div v-show="type === 'list'">
      <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div v-show="showSearch" class="mb-[10px]">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true">
              <el-form-item>
                <el-date-picker v-model="queryParams.dateRange" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
              </el-form-item>
              <el-form-item label="看诊类型">
                <el-select v-model="queryParams.type" class="spec-unit-select">
                  <el-option v-for="dict in treatment_user_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-input v-model="queryParams.searchValue" placeholder="姓名/门诊/住院号" style="width: 240px; " clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </transition>
      <el-card shadow="never">
        <template #header>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['patients:nutritionEducation:add']">新增营养宣教</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button disabled>打印已选病历</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </template>
        <el-table v-loading="loading" border :data="educationList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="时间" align="center" prop="createTime" />
          <el-table-column label="看诊类型" align="center" prop="createTime">
            <template #default="scope">
              <span>{{ scope.row.patientType == 1 ? '门诊' : '住院' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="科室" align="center" prop="deptName" />
          <el-table-column label="门诊/住院号" align="center" prop="outpatientNo" />
          <el-table-column label="营养宣教标题" align="center" prop="educationTitle" />
          <el-table-column label="内容描述" align="center" prop="description">
            <template #default="scope">
              <div class="description-cell" @mouseenter="showTooltip($event, scope.row.description)" @mouseleave="hideTooltip">
                {{ scope.row.description }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="正文" align="center" prop="content">
            <template #default="scope">
              <div class="description-cell" @mouseenter="showTooltip($event, scope.row.content)" @mouseleave="hideTooltip">
                {{ stripHtml(scope.row.content) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="宣教医生/护士" align="center" prop="createByUser" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="详情" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleDetail(scope.row)">详情</el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-card>
    </div>
    <div v-show="type === 'addForm'">
      <!-- 添加或修改营养宣教对话框 -->
      <el-button type="primary" @click="handleBack">返回</el-button> <span style="margin-left: 20px;">新增营养宣教</span> 
      <el-form ref="educationFormRef" :model="form" :rules="rules" label-width="120px" style="margin-top: 20px;">
        <el-form-item label="科室:" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入科室" :disabled="true" style="width: 30%;" />
        </el-form-item>
        <el-form-item label="营养宣教标题:" prop="educationTitle">
          <el-input v-model="form.educationTitle" placeholder="请输入营养宣教标题" style="width: 30%;" />
          <el-button style="margin-left: 10px;" type="primary" @click="showTemplateDialog = true">导入模板</el-button>
        </el-form-item>
        <el-form-item label="描述:" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="5" placeholder="请输入内容" style="width: 30%;" />
        </el-form-item>
        <el-form-item label="正文:">
          <editor v-model="form.content" :min-height="192" style="width: 75%;" />
        </el-form-item>
      </el-form>
      <EducationTemplateDialog v-model:visible="showTemplateDialog" @select="onTemplateSelect" />
      <div class="dialog-footer" style="text-align: center; margin-top: 100px">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">提 交</el-button>
      </div>
    </div>
    <Teleport to="body">
      <Transition name="fade">
        <div v-if="tooltipVisible" class="custom-tooltip" :style="tooltipStyle">
          {{ tooltipContent }}
        </div>
      </Transition>
    </Teleport>
    <detail-dialog v-model="showDetailDialog" :detail="currentDetail" />
  </div>
</template>

<script setup name="Education" lang="ts">
    import { listEducation, getEducation, delEducation, addEducation, updateEducation } from '@/api/patients/nutritionEducation';
    import { EducationVO, EducationQuery, EducationForm } from '@/api/patients/nutritionEducation/types';
    const EducationTemplateDialog = defineAsyncComponent(() => import('./educationTemplateDialog.vue'));
    import DetailDialog from './detailDialog.vue';
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const { treatment_user_type } = toRefs < any > (proxy ?.useDict('treatment_user_type'));

    const educationList = ref < EducationVO[] > ([]);
    const buttonLoading = ref(false);
    const loading = ref(true);
    const type = ref('list');
    const showSearch = ref(true);
    const ids = ref < Array < string | number >> ([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const showTemplateDialog = ref(false);
    const showDetailDialog = ref(false);
    const currentDetail = ref({});
     const emit = defineEmits(['change'])
    const queryFormRef = ref < ElFormInstance > ();
    const educationFormRef = ref < ElFormInstance > ();

    const dialog = reactive < DialogOption > ({
        visible: false,
        title: ''
    });
    // 声明接收的 props
    const props = defineProps({
        patientInfo: {
            type: Object,
            required: true,
            default: () => ({
                id: '',
                name: '',
                age: '',
                deptId: '',
                gender: ''
            })
        }
    });
    const initFormData: EducationForm = {
        id: undefined,
        patientId: props.patientInfo ?.id,
        educationTitle: undefined,
        educationTemplateId: undefined,
        description: undefined,
        content: undefined,
        contentStr: undefined,
        type: props.patientInfo ?.type,
        deptId: props.patientInfo ?.deptId,
        deptName: undefined,
        outpatientNo: props.patientInfo ?.outpatientNo,
    }
    const data = reactive < PageData < EducationForm,
        EducationQuery >> ({
            form: { ...initFormData },
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                patientId: props.patientInfo ?.id,
                dateRange: undefined,
                searchValue: undefined,
                params: {}
            },
            rules: {
                id: [
                    { required: true, message: "不能为空", trigger: "blur" }
                ],
                patientId: [
                    { required: true, message: "患者id不能为空", trigger: "blur" }
                ],
            }
        });

    const { queryParams, form, rules } = toRefs(data);

    // 监听患者ID变化，自动同步到表单和查询参数
    watch(
        () => props.patientInfo.id,
        (newId) => {
            form.value.patientId = newId;
            queryParams.value.patientId = newId;
        }, { immediate: true }
    );
    /** 查询营养宣教列表 */
    const getList = async () => {
        loading.value = true;
        const res = await listEducation(queryParams.value);
        educationList.value = res.rows;
        total.value = res.total;
        loading.value = false;
    }
    // 添加tooltip相关的状态和方法
    const tooltipVisible = ref(false);
    const tooltipContent = ref('');
    const tooltipStyle = ref({
        left: '0px',
        top: '0px'
    });
    const hideTooltip = () => {
        tooltipVisible.value = false;
    };
    const showTooltip = (event: MouseEvent, content: string) => {
        const target = event.target as HTMLElement;
        const rect = target.getBoundingClientRect();

        tooltipContent.value = content;
        tooltipStyle.value = {
            left: `${rect.left + window.scrollX}px`,
            top: `${rect.bottom + window.scrollY + 5}px`
        };
        tooltipVisible.value = true;
    };
    const onTemplateSelect = async (data) => {
        form.value.content = data.template;
        form.value.educationTitle = data.label;
        form.value.educationTemplateId = data.id;
        form.value.description = data.description;

    };

    /** 取消按钮 */
    const cancel = () => {
        reset();
        dialog.visible = false;
    }
    const handleDetail = (row) => {
        currentDetail.value = row;
        currentDetail.value.content = stripHtml(currentDetail.value.content);
        showDetailDialog.value = true;
    }

    function stripHtml(html) {
        const div = document.createElement('div');
        div.innerHTML = html;
        return div.textContent || div.innerText || '';
    }

    const handleBack = () => {
        type.value = 'list';
    }
    const handleCancel = () => {
        type.value = 'list';
    };

    /** 表单重置 */
    const reset = () => {
        form.value = {
            ...initFormData,
            patientId: props.patientInfo ?.id // 用最新id
        };
        educationFormRef.value ?.resetFields();
    }

    /** 搜索按钮操作 */
    const handleQuery = () => {
        queryParams.value.pageNum = 1;
        getList();
    }
    // 字典label工具
    function getDictLabel(dictList: any[], value: string) {
        if (!dictList || !Array.isArray(dictList)) return value || '--';
        const found = dictList.find(item => item.value === value);
        return found ? found.label : value || '--';
    }
    /** 重置按钮操作 */
    const resetQuery = () => {
        queryFormRef.value ?.resetFields();
        queryParams.value.dateRange = undefined;
        queryParams.value.type = undefined;
        queryParams.value.searchValue = undefined;
        handleQuery();
    }

    /** 多选框选中数据 */
    const handleSelectionChange = (selection: EducationVO[]) => {
        ids.value = selection.map(item => item.id);
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    }

    /** 新增按钮操作 */
    const handleAdd = () => {
        reset();
        type.value = 'addForm';
        form.value.deptName = props.patientInfo ?.deptName;
        form.value.deptId = props.patientInfo ?.deptId;
        form.value.patientId = props.patientInfo ?.id;
        dialog.visible = true;
        dialog.title = "添加营养宣教";
    }

    /** 修改按钮操作 */
    const handleUpdate = async (row ? : EducationVO) => {
        reset();
        const _id = row ?.id || ids.value[0]
        const res = await getEducation(_id);
        Object.assign(form.value, res.data);
        dialog.visible = true;
        dialog.title = "修改营养宣教";
    }

    /** 提交按钮 */
    const submitForm = () => {
        educationFormRef.value ?.validate(async (valid: boolean) => {
            if (valid) {
                buttonLoading.value = true;
                if (form.value.id) {
                    form.value.contentStr = window.btoa(encodeURIComponent(form.value.content))
                    await updateEducation(form.value).finally(() => buttonLoading.value = false);
                } else {
                    form.value.contentStr = window.btoa(encodeURIComponent(form.value.content))
                    await addEducation(form.value).finally(() => buttonLoading.value = false);
                }
                proxy ?.$modal.msgSuccess("操作成功");
                dialog.visible = false;
                await getList();
                type.value = 'list';
            }
        });
    }

    /** 删除按钮操作 */
    const handleDelete = async (row ? : EducationVO) => {
        const _ids = row ?.id || ids.value;
        await proxy ?.$modal.confirm('是否确认删除营养宣教编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
        await delEducation(_ids);
        type.value = 'list';
        proxy ?.$modal.msgSuccess("删除成功");
        await getList();
    }

    /** 导出按钮操作 */
    const handleExport = () => {
        proxy ?.download('patients/nutritionEducation/export', {
            ...queryParams.value
        }, `education_${new Date().getTime()}.xlsx`)
    }

    onMounted(() => {
        getList();
    });
</script>

<style scoped>
    .description-cell {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        line-height: 1.5;
        max-height: 3em;
        text-align: left;
        padding: 0 8px;
        cursor: pointer;
    }

    .custom-tooltip {
        position: fixed;
        z-index: 9999;
        background: white;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        padding: 12px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        max-width: 400px;
        line-height: 1.5;
        font-size: 14px;
        word-break: break-all;
        text-align: left;
    }

    .fade-enter-active,
    .fade-leave-active {
        transition: opacity 0.2s ease;
    }

    .fade-enter-from,
    .fade-leave-to {
        opacity: 0;
    }
</style>