<template>

    <div class="p-2">
        <el-button type="primary" plain size="large" @click="goBack">返回</el-button>
        <el-card shadow="never">
            <el-form ref="resultTemplateFormRef" :model="form" :rules="rules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="模板名称" prop="templateName">
                            <el-input v-model="form.templateName" placeholder="请输入模板名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="类型" prop="templateTypeId">
                            <el-select v-model="form.templateTypeId" placeholder="请选择">
                                <el-option v-for="item in templateTypeList" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-button type="primary" plain icon="Plus" @click="handleAddType">新增类型</el-button>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="模板描述" prop="description">
                            <el-input v-model="form.description" type="textarea" placeholder="请输入模板描述" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-button type="primary" plain @click="handleParamDetail">参数说明</el-button>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="20">
                        <el-form-item label="正文" prop="content">
                            <Editor v-model="form.content" :min-height="200" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-dialog title="参数说明" v-model="detailDialog.visible" width="30%" :close-on-click-modal="false" append-to-body>
                <div class="detail-container">
                    <div class="detail-row">
                        <div class="detail-label">会诊目的</div>
                        <div class="detail-content">${purpose}</div>
                    </div>
                    <div class="detail-row">
                        <div class="detail-label">身高</div>
                        <div class="detail-content">${height}</div>
                    </div>
                    <div class="detail-row">
                        <div class="detail-label">体重</div>
                        <div class="detail-content">${weight}</div>
                    </div>
                    <div class="detail-row">
                        <div class="detail-label">BMI</div>
                        <div class="detail-content">${bmi}</div>
                    </div>
                    <div class="detail-row">
                        <div class="detail-label">近6个月体重变化</div>
                        <div class="detail-content">${lossWeight}</div>
                    </div>
                    <div class="detail-row">
                        <div class="detail-label">体重下降率</div>
                        <div class="detail-content">${lossWeightRate}</div>
                    </div>
                    <div class="detail-row">
                        <div class="detail-label">24h 摄入情况：能量</div>
                        <div class="detail-content">${totalFood24retrospectCalories}</div>
                    </div>
                    <div class="detail-row">
                        <div class="detail-label">24h 摄入情况：蛋白质</div>
                        <div class="detail-content">${totalFood24retrospectProtein}</div>
                    </div>
                    <div class="detail-row">
                        <div class="detail-label">白蛋白</div>
                        <div class="detail-content">${alb}</div>
                    </div>
                     <div class="detail-row">
                        <div class="detail-label">前白蛋白</div>
                        <div class="detail-content">${beforeAlb}</div>
                    </div>
                     <div class="detail-row">
                        <div class="detail-label">血红蛋白</div>
                        <div class="detail-content">${hgb}</div>
                    </div>
                     <div class="detail-row">
                        <div class="detail-label">营养风险筛查</div>
                        <div class="detail-content">${nrs2002Score} ${nrs2002Conclusion}</div>
                    </div>
                     <div class="detail-row">
                        <div class="detail-label">营养不良评定</div>
                        <div class="detail-content">${glimResult}</div>
                    </div>
                     <div class="detail-row">
                        <div class="detail-label">途径</div>
                        <div class="detail-content">${way}</div>
                    </div>
                     <div class="detail-row">
                        <div class="detail-label">经口膳食：能量</div>
                        <div class="detail-content">${totalCalories}</div>
                    </div>
                     <div class="detail-row">
                        <div class="detail-label">经口膳食：蛋白质</div>
                        <div class="detail-content">${totalProtein}</div>
                    </div>
                </div>
                <template #footer>
                    <div class="dialog-footer" style="text-align: center">
                        <el-button size="large" @click="detailDialog.visible = false">关闭</el-button>
                    </div>
                </template>
            </el-dialog>
            <div class="flex justify-center gap-2 mt-4">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
            </div>

        </el-card>
        <!-- 添加模板类型管理弹窗 -->
        <ResultTemplateTypeDialog ref="resultTemplateTypeDialogRef" @success="getTemplateTypeList" />

    </div>
</template>

<script setup lang="ts">
    import { getCurrentInstance, ref, reactive, onMounted } from 'vue';
    import { useRouter, useRoute } from 'vue-router';
    import {
        addResultTemplate,
        updateResultTemplate,
        getResultTemplate
    } from '@/api/parameter/basicPublicTemplate/consultantResultTemplate';
    import { ResultTemplateForm } from '@/api/parameter/basicPublicTemplate/consultantResultTemplate/types';
    import ResultTemplateTypeDialog from '../consultantResultTemplateType/resultTemplateTypeDialog.vue';
    import { listResultTemplateType } from '@/api/parameter/basicPublicTemplate/consultantResultTemplateType';
    import type { ResultTemplateTypeQuery } from '@/api/parameter/basicPublicTemplate/consultantResultTemplateType/types';

    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const router = useRouter();
    const route = useRoute();
    const resultTemplateTypeDialogRef = ref();
    const resultTemplateFormRef = ref();
    const buttonLoading = ref(false);

    interface ResultTemplateTypeOption {
        value: string | number;
        label: string;
    }

    const detailDialog = reactive < DialogOption > ({
        visible: false
    });

    const templateTypeList = ref(JSON.parse(route.query.templateTypeList as string || '[]'));

    const initFormData: ResultTemplateForm = {
        id: undefined,
        templateName: undefined,
        description: undefined,
        templateTypeId: undefined,
        content: undefined,
        contentStr: undefined
    }

    const form = ref < ResultTemplateForm > ({ ...initFormData });

    const rules = {
        templateName: [
            { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        templateTypeId: [
            { required: true, message: "类型不能为空", trigger: "change" }
        ],
        description: [
            { required: true, message: "模板描述不能为空", trigger: "blur" }
        ],
        content: [
            { required: true, message: "正文不能为空", trigger: "blur" }
        ]
    };

    /** 获取会诊模板类型列表 */
    const getTemplateTypeList = async () => {
        try {
            const params: ResultTemplateTypeQuery = {
                pageNum: 1,
                pageSize: 100,
                templateType: undefined,
                params: {}
            };
            const res = await listResultTemplateType(params);
            templateTypeList.value = res.rows.map(item => ({
                value: item.id,
                label: item.templateType
            }));
        } catch (error) {
            proxy ?.$modal.msgError("获取类型列表失败");
            console.error("获取类型列表失败:", error);
        }
    }

    /** 新增类型按钮操作 */
    const handleAddType = () => {
        resultTemplateTypeDialogRef.value.open();
    };

    const handleParamDetail = () => {
        detailDialog.visible = true; // 打开弹窗
    };

    // 返回按钮
    const goBack = () => {
        router.back();
    };

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

    /** 取消按钮 */
    const cancel = () => {
        router.back();
    }

    /** 提交按钮 */
    const submitForm = () => {
        resultTemplateFormRef.value ?.validate(async (valid: boolean) => {
            if (valid) {
                buttonLoading.value = true;
                try {
                    if (form.value.id) {
                        form.value.contentStr = window.btoa(encodeURIComponent(form.value.content))
                        await updateResultTemplate(form.value);
                    } else {
                        form.value.contentStr = window.btoa(encodeURIComponent(form.value.content))
                        await addResultTemplate(form.value);
                    }
                    proxy ?.$modal.msgSuccess("操作成功");
                    router.back();
                } catch (error) {
                    console.error('提交失败', error);
                } finally {
                    buttonLoading.value = false;
                }
            }
        });
    }

    /** 获取详情 */
    const getDetail = async (id: string | number) => {
        try {
            const res = await getResultTemplate(id);
            Object.assign(form.value, res.data);
        } catch (error) {
            console.error('获取详情失败', error);
            proxy ?.$modal.msgError("获取详情失败");
        }
    }

    onMounted(async () => {
        await getTemplateTypeList();
        const id = route.query.id;
        const copyData = route.query.copyData;

        if (id) {
            await getDetail(id as string);
        } else if (copyData) {
            try {
                const parsedData = JSON.parse(copyData as string);
                Object.assign(form.value, parsedData);
            } catch (error) {
                console.error('解析复制数据失败', error);
                proxy ?.$modal.msgError("解析复制数据失败");
            }
        }
    });
</script>
<style scoped>
 .detail-container {
        background: #fff;
    }

    .detail-row {
        display: flex;
        border-bottom: 1px solid #dcdfe6;
    }
     .detail-row:last-child {
        border-bottom: none;
    }

    .detail-label {
        width: 50%;
        padding: 12px 20px;
        background: #f5f7fa;
        border-right: 1px solid #dcdfe6;
        box-sizing: border-box;
    }

    .detail-content {
        width: 50%;
        padding: 12px 20px;
        box-sizing: border-box;
    }
    </style>