<template>
    <div class="p-2">
        <el-button type="primary" plain size="large" @click="goBack">返回</el-button>
        <el-card shadow="never">
            <el-form ref="educationTemplateFormRef" :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="deptIdList">
                            <el-tree-select v-model="form.deptIdList" :data="treeData" :props="treeProps"  multiple placeholder="请选择" check-strictly node-key="id" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="疾病标签" prop="diseaseLableId">
                            <el-select v-model="form.labelList" multiple placeholder="请选择" style="width: 100%;" :disabled="true" @click="labelDialogVisible = true" class="custom-label-select" value-key="labelId">
                                <el-option v-for="item in form.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-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" :rows="5"  placeholder="请输入" />
                        </el-form-item>
                    </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>
            <div class="flex justify-center gap-2 mt-4">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
            </div>
        </el-card>
        <DiseaseLabel v-model="labelDialogVisible" :initial-selected-labels="form.labelList || []" @confirm="onLabelConfirm" />
    </div>
</template>

<script setup lang="ts">
    import { getCurrentInstance, ref, reactive, onMounted } from 'vue';
    import { useRouter, useRoute } from 'vue-router';
    import { addEducationTemplate, updateEducationTemplate, getEducationTemplate } from '@/api/parameter/basicPublicTemplate/nutritionEducationTemplate';
    import { EducationTemplateForm } from '@/api/parameter/basicPublicTemplate/nutritionEducationTemplate/types';
    import { listDept } from '@/api/system/dept';
    import DiseaseLabel from '@/views/warehouse/nutriProduct/labelDialog.vue';
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const router = useRouter();
    const route = useRoute();
    const educationTemplateFormRef = ref();
    const buttonLoading = ref(false);
    const loading = ref(false);
    const treeData = ref([]);
    const labelDialogVisible = ref(false); // 疾病标签

    const treeProps = ref({
        value: 'deptId',
        label: 'deptName',
        children: 'children'
    });

    const initFormData: EducationTemplateForm = {
        id: undefined,
        templateName: undefined,
        deptId: undefined,
        deptIdList: [],
        labelList: [],
        diseaseLabelId: undefined,
        description: undefined,
        content: undefined,
        contentStr: undefined,
        updateDept: undefined
    };

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

    const rules = {
        templateName: [
            { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        deptId: [
            { required: true, message: "适用科室不能为空", trigger: "change" }
        ],
        deiseaseLableId: [
            { required: true, message: "疾病标签不能为空", trigger: "change" }
        ],
        description: [
            { required: true, message: "模板描述不能为空", trigger: "blur" }
        ],
        content: [
            { required: true, message: "正文不能为空", trigger: "blur" }
        ]
    };

    /** 获取部门列表 */
    const getDeptList = async () => {
        loading.value = true;
        try {
            const res = await listDept({
                pageNum: 1,
                pageSize: 100
            });
            if (!res.data) {
                console.warn("部门数据为空");
                treeData.value = [];
                return;
            }

            const processedData = proxy ?.handleTree(res.data, 'deptId');
            if (!processedData) {
                console.warn("树形数据处理失败");
                treeData.value = [];
                return;
            }

            treeData.value = processedData;
        } catch (error) {
            console.error('获取部门列表失败:', error);
            treeData.value = [];
        } finally {
            loading.value = false;
        }
    };

    // 标签确认回调
    function onLabelConfirm(selectedLabels: Array < { labelId: string | number;labelName: string } > ) {        
        form.value.labelList = selectedLabels;
    }

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

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

    /** 提交按钮 */
    const submitForm = () => {
        educationTemplateFormRef.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 updateEducationTemplate(form.value);
                    } else {
                        form.value.contentStr = window.btoa(encodeURIComponent(form.value.content))
                        console.log('form.value', JSON.stringify(form.value));
                        
                        await addEducationTemplate(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 getEducationTemplate(id);
            Object.assign(form.value, res.data);
        } catch (error) {
            console.error('获取详情失败', error);
            proxy ?.$modal.msgError("获取详情失败");
        }
    };

    onMounted(async () => {
        await getDeptList();
        const id = route.query.id;
        if (id) {
            await getDetail(id as string);
        }
    });
</script>