<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="form.visitType" 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="id" v-if="true" />
                    <el-table-column label="时间" align="center" prop="createTime" />
                    <el-table-column label="诊断依据" align="center" prop="diagnosisBasis" />
                    <el-table-column label="看诊类型" align="center" prop="diagnosisType" />
                    <el-table-column label="门诊/住院号" align="center" prop="outpatientNumber" />
                    <el-table-column label="营养诊断" align="center" prop="nutritionalDiagnosis" />
                    <el-table-column label="诊断医生" align="center" prop="diagnosisDoctor" />
                    <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="handleUpdate(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="labelList" multiple placeholder="请选择" style="width: 100%;" :disabled="true" @click="labelDialogVisible = true" class="custom-label-select" value-key="labelId">
                        <el-option v-for="item in labelList" :key="item.labelId" :label="item.labelName" :value="item">
                            <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.consultationContent" 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="labelList || []" @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>
</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';
    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 labelList = ref([]);
    const detailData = ref({});
    const labelDialogVisible = ref(false);

    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,
        treatmentUserId: props.patientInfo ?.id, // Initialize with patient ID
        consultantTemplateId: undefined,
        diagnosisLableId: undefined,
        diagnosisBasisId: undefined,
        medicalOrder: undefined,
        consultationContent: undefined,
    }

    const data = reactive < PageData < DiagnosisForm,
        DiagnosisQuery >> ({
            form: { ...initFormData },
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                visitType: undefined,
                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);

    /** 查询营养诊断列表 */
    const getList = async () => {
        loading.value = true;
        const res = await listDiagnosis(queryParams.value);
        diagnosisList.value = res.rows;
        console.log("diagnosisList", JSON.stringify(diagnosisList.value));

        total.value = res.total;
        loading.value = false;
    }
    // 详情按钮处理
    const getTreatmentUser = async () => {
        try {
            // 获取患者详细信息
            const res = await fetchTreatmentUser(props.patientInfo ?.id);
            detailData.value = res.data;
        } catch (error) {

        }
    };

    /** 取消按钮 */
    const cancel = () => {
        reset();
        dialog.visible = false;
    }
    // 标签确认回调
    function onLabelConfirm(selectedLabels: Array < { labelId: string | number;labelName: string } > ) {
        labelList.value = selectedLabels;
    }
    const onTemplateSelect = async (templateContent) => {
        if (!templateContent) return;

        try {
            // 获取患者详细信息
            const res = await fetchTreatmentUser(props.patientInfo ?.id);
            const patientDetail = res.data || {};

            console.log('Template content:', templateContent);
            console.log('Patient details:', patientDetail);

            // 替换模板中的占位符
            let processedContent = templateContent;

            // 定义替换规则（根据实际字段进行调整）
            const replacements = {
                '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 || '',
                'purpose': patientDetail.purpose || '',
                'lossWeight': patientDetail.lossWeight || '',
                'totalCalories': patientDetail.totalCalories || '',
                'totalProtein': patientDetail.totalProtein || '',
                'lossWeightRate': patientDetail.lossWeightRate || '',
                'totalFood24retrospectProtein': patientDetail.totalFood24retrospectProtein || '',
                'totalFood24retrospectCalories': patientDetail.totalFood24retrospectCalories || '',


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

            console.log('Replacements:', replacements);

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

            console.log('Processed content:', processedContent);

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

    /** 表单重置 */
    const reset = () => {
        form.value = { ...initFormData };
        diagnosisFormRef.value ?.resetFields();
    }

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

    /** 重置按钮操作 */
    const resetQuery = () => {
        queryFormRef.value ?.resetFields();
        handleQuery();
    }

    /** 多选框选中数据 */
    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.consultationContent = '';
    }

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

    /** 提交按钮 */
    const submitForm = () => {
        diagnosisFormRef.value ?.validate(async (valid: boolean) => {
            if (valid) {
                buttonLoading.value = true;
                if (form.value.id) {
                    await updateDiagnosis(form.value).finally(() => buttonLoading.value = false);
                } else {
                    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();
    }



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