<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" @click="handleAdd">新增营养诊断</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="diagnosisList" @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="diagnosisBasis">
                        <template #default="scope">
                            <span>{{getDictLabel(treatment_user_type ,scope.row.diagnosisBasis )|| '--' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="看诊类型" align="center" prop="type">
                        <template #default="scope">
                            <span>{{getDictLabel(treatment_user_type ,scope.row.type )|| '--' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="门诊/住院号" align="center" prop="outpatientNo" />
                    <el-table-column label="营养诊断" align="center" prop="diagnosisLabelStr" width="350" />
                    <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-form ref="diagnosisFormRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="营养诊断:" prop="diagnosisLableId">
                    <el-select v-model="form.labelList" multiple placeholder="请选择" style="width: 100%;" :disabled="true" @click="labelDialogVisible = true" class="custom-label-select">
                        <el-option v-for="item in labelOptions" :key="item.labelId" :label="item.labelName" :value="item.labelId">
                            <el-tag type="info" size="small">{{ item.labelName }}</el-tag>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="营养诊断依据:" prop="diagnosisBasisId">
                    <el-input v-model="form.diagnosisBasisId" placeholder="请输入营养筛查/评估结果" clearable />
                </el-form-item>
                <el-form-item label="营养会诊结论:">
                    <div class="consultation-toolbar">
                        <el-button type="danger" plain @click="clearContent">清空记录</el-button>
                        <el-button @click="showTemplateDialog = true">导入模板</el-button>
                    </div>
                </el-form-item>
                <el-form-item>
                    <Editor v-model="form.consultantResult" placeholder="请输入内容..." style="min-height: 200px; width: 100%;" />
                </el-form-item>
                <el-form-item label="营养医嘱:" prop="medicalOrder">
                    <el-input v-model="form.medicalOrder" placeholder="请输入" clearable />
                </el-form-item>

            </el-form>
            <LabelDialog v-model="labelDialogVisible" :initial-selected-labels="labelOptions || []" @confirm="onLabelConfirm" />
            <ConsultantTemplateDialog 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>
        <!-- 详情弹窗始终挂载在最外层div内 -->
        <detail-dialog v-model="showDetailDialog" :detail="currentDetail" />
    </div>
</template>

<script setup name="Diagnosis" lang="ts">
    import { listDiagnosis, getDiagnosis, delDiagnosis, addDiagnosis, updateDiagnosis } from '@/api/patients/diagnosis';
    import { DiagnosisVO, DiagnosisQuery, DiagnosisForm } from '@/api/patients/diagnosis/types';
    import { getTreatmentUser as fetchTreatmentUser } from '@/api/workbench/treatmentUser';
    import LabelDialog from '@/views/warehouse/nutriProduct/labelDialog.vue';
    import { getDiseaseLabel } from '@/api/system/diseaseLabel'; // 新增: 导入获取标签详情API
    import { log } from 'console';
    import DetailDialog from './detailDialog.vue';
    import { watch } from 'vue';
    const emit = defineEmits(['change'])
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;

    const ConsultantTemplateDialog = defineAsyncComponent(() => import('./consultantTemplateDialog.vue'));
    const { treatment_user_type } = toRefs < any > (proxy ?.useDict('treatment_user_type'));


    const diagnosisList = ref < DiagnosisVO[] > ([]);
    const buttonLoading = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref < Array < string | number >> ([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const type = ref('list');
    const labelDialogVisible = ref(false);
    const labelOptions = ref < any[] > ([]); // 新增: 用于存储可选标签对象
    const showDetailDialog = ref(false);
    const currentDetail = ref({});

    const queryFormRef = ref < ElFormInstance > ();
    const diagnosisFormRef = ref < ElFormInstance > ();
    const showTemplateDialog = ref(false);

    const dialog = reactive < DialogOption > ({
        visible: false,
        title: ''
    });

    // 声明接收的 props
    const props = defineProps({
        patientInfo: {
            type: Object,
            required: true,
            default: () => ({
                id: '',
                name: '',
                age: '',
                gender: ''
            })
        }
    });

    const initFormData: DiagnosisForm = {
        id: undefined,
        labelList: [],
        treatmentUserId: props.patientInfo ?.id,
        consultantTemplateId: undefined,
        diagnosisLableId: undefined,
        diagnosisBasisId: undefined,
        medicalOrder: undefined,
        consultantResult: undefined,
        consultantResultStr: undefined,
    }

    const data = reactive < PageData < DiagnosisForm,
        DiagnosisQuery >> ({
            form: { ...initFormData },
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                visitType: undefined,
                treatmentUserId: props.patientInfo ?.id,
                dateRange: undefined,
                searchValue: undefined,
                params: {}
            },
            rules: {
                diagnosisLableId: [
                    { required: false, message: "营养诊断不能为空", trigger: ['blur', 'change'] }
                ],
                medicalOrder: [
                    { required: true, message: "医嘱不能为空", trigger: "blur" }
                ],
            }
        });

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

    // 监听患者ID变化，自动同步到表单和查询参数
    watch(
        () => props.patientInfo.id,
        (newId) => {
            form.value.treatmentUserId = newId;
            queryParams.value.treatmentUserId = newId;
        }, { immediate: true }
    );

    /** 查询营养诊断列表 */
    const getList = async () => {
        loading.value = true;
        try {
            const res = await listDiagnosis(queryParams.value);
            diagnosisList.value = res.rows || [];
            total.value = res.total || 0;
        } catch (error) {
            proxy ?.$modal.msgError('获取列表失败');
            diagnosisList.value = [];
        }
        loading.value = false;
    }

    /** 取消按钮 */
    const cancel = () => {
        reset();
        dialog.visible = false;
    }
    // 标签确认回调
    function onLabelConfirm(selectedLabels: Array < { labelId: string | number;labelName: string } > ) {
        form.value.labelList = selectedLabels.map(l => l.labelId); // 只存labelId
        labelOptions.value = selectedLabels; // 用于el-option展示labelName
    }
    const onTemplateSelect = async (data) => {
        form.value.consultantTemplateId = data.id;
        let templateContent = data.template;
        console.log(JSON.stringify(data));

        if (!templateContent) return;

        try {
            // 获取患者详细信息
            const res = await fetchTreatmentUser(props.patientInfo ?.id);
            const patientDetail = res.data as any || {};
            form.value.consultantTemplateId = data.id;
            // 替换模板中的占位符
            let processedContent = templateContent;

            // 定义替换规则（根据实际字段进行调整）
            const replacements = {
                'purpose': patientDetail.type == 1 ? '住院' : '门诊' || '',
                'height': patientDetail.height || '',
                'weight': patientDetail.weight || '',
                'bmi': patientDetail.bmi || '',
                'alb': patientDetail.alb || '',
                'hgb': patientDetail.hgb || '',
                'nrs2002Score': patientDetail.nrs2002Score || '',
                'nrs2002Conclusion': patientDetail.nrs2002Conclusion || '',
                'beforeAlb': patientDetail.beforeAlb || '',
                'way': patientDetail.way || '',
                'glimResult': patientDetail.glimResult || '',
                'lossWeight': patientDetail.lossWeight || '',
                'totalCalories': patientDetail.totalCalories || '',
                'totalProtein': patientDetail.totalProtein || '',
                'lossWeightRate': patientDetail.lossWeightRate || '',
                'totalFood24retrospectProtein': patientDetail.totalFood24retrospectProtein || '',
                'totalFood24retrospectCalories': patientDetail.totalFood24retrospectCalories || '',


                // 可以根据需要添加更多替换规则
            };

            // 执行替换
            for (const [key, value] of Object.entries(replacements)) {
                const placeholder = '${' + key + '}';
                console.log(`Replacing ${placeholder} with ${value}`);
                processedContent = processedContent.split(placeholder).join(value);
            }

            // 将处理后的内容赋值给表单
            form.value.consultantResult = processedContent;
        } catch (error) {
            console.error('获取患者详情失败:', error);
            proxy ?.$modal.msgError('获取患者详情失败');
            // 如果获取详情失败，仍然使用原始模板
            form.value.consultantResult = templateContent;
        }
    };

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

    /** 搜索按钮操作 */
    const handleQuery = () => {
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    const resetQuery = () => {
        queryFormRef.value ?.resetFields();
        queryParams.value.dateRange = undefined;
        queryParams.value.type = undefined;
        queryParams.value.searchValue = undefined;
        queryParams.value.pageNum = 1;
        queryParams.value.pageSize = 10;
        handleQuery();
    }
    // 字典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 handleSelectionChange = (selection: DiagnosisVO[]) => {
        ids.value = selection.map(item => item.id);
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    }

    /** 新增按钮操作 */
    const handleAdd = () => {
        reset();
        type.value = 'addForm';
        form.value.treatmentUserId = props.patientInfo ?.id;
    }
    const handleCancel = () => {
        type.value = 'list';
    };
    const clearContent = () => {
        form.value.consultantResult = '';
    }

    /** 修改按钮操作 */
    const handleUpdate = async (row ? : DiagnosisVO) => {
        reset();
        const _id = row ?.id || ids.value[0]
        const res = await getDiagnosis(_id);
        Object.assign(form.value, res.data);
        // 适配labelList为labelId数组时，需获取完整标签对象
        if (Array.isArray(form.value.labelList) && form.value.labelList.length > 0 && typeof form.value.labelList[0] !== 'object') {
            // 批量获取标签详情
            const labelIds = form.value.labelList;
            const labelDetailPromises = labelIds.map(id => getDiseaseLabel(id).then(r => r.data));
            labelOptions.value = await Promise.all(labelDetailPromises);
        } else {
            labelOptions.value = form.value.labelList || [];
        }
        dialog.visible = true;
        dialog.title = "修改营养诊断";
    }

    /** 提交按钮 */
    const submitForm = () => {
        diagnosisFormRef.value ?.validate(async (valid: boolean) => {
            if (valid) {
                buttonLoading.value = true;
                if (form.value.id) {
                    form.value.consultantResultStr = window.btoa(encodeURIComponent(form.value.consultantResult))
                    await updateDiagnosis(form.value).finally(() => buttonLoading.value = false);
                } else {

                    form.value.consultantResultStr = window.btoa(encodeURIComponent(form.value.consultantResult))
                    await addDiagnosis(form.value).finally(() => buttonLoading.value = false);
                }
                proxy ?.$modal.msgSuccess("操作成功");
                dialog.visible = false;
                await getList();
                type.value = 'list';
            }
        });
    }

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

    const handleDetail = (row: any) => {
        currentDetail.value = row as any;
        currentDetail.value.consultantResult = stripHtml((currentDetail.value as any).consultantResult);
        showDetailDialog.value = true;
    };

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

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