<template>
    <div class="p-2">
        <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" label-width="120px">
                        <el-form-item label="开始时间">
                            <el-date-picker v-model="queryParams.startTime" type="datetime" placeholder="选择开始时间" clearable />
                            <el-date-picker v-model="queryParams.endTime" type="datetime" placeholder="选择结束时间" clearable />
                        </el-form-item>
                        <el-form-item label="创建人科室">
                            <el-tree-select v-model="queryParams.createBy" :data="treeData" :props="treeProps" placeholder="请选择" check-strictly node-key="id" @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="类型">
                            <el-select v-model="queryParams.templateTypeId" placeholder="请选择" clearable>
                                <el-option v-for="item in templateTypeList" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-input v-model="queryParams.searchValue" style="width: 300px;" placeholder="模板名称/模板描述/创建人/最后编辑人" 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="['basicPublicTemplate:consultantResultTemplate:add']">新增模板</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAddType">新增类型</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table v-loading="loading" border :data="resultTemplateList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="模板名称" align="center" prop="templateName" />
                <el-table-column label="模板描述" align="center" prop="description" />
                <el-table-column label="类型" align="center" prop="templateTypeId">
                    <template #default="{ row }">
                        {{ getTemplateTypeName(row.templateTypeId) }}
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
                <el-table-column label="创建人姓名" align="center" prop="createByUser" />
                <el-table-column label="创建人科室" align="center" prop="createDeptName" />
                <el-table-column label="最后修改时间" align="center" prop="updateTime" width="180" />
                <el-table-column label="最后修改人姓名" align="center" prop="updateByUser" />
                <el-table-column label="最后修改人科室" align="center" prop="updateDeptName" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['basicPublicTemplate:consultantResultTemplate:edit']">编辑</el-button>
                        <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
                        <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['basicPublicTemplate:consultantResultTemplate:remove']">删除</el-button>
                    </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>

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

<script setup name="ResultTemplate" lang="ts">
    import {
        listResultTemplate,
        getResultTemplate,
        delResultTemplate,
        addResultTemplate,
        updateResultTemplate
    } from '@/api/parameter/basicPublicTemplate/consultantResultTemplate';
    import { ResultTemplateVO, ResultTemplateQuery, ResultTemplateForm } from '@/api/parameter/basicPublicTemplate/consultantResultTemplate/types';
    import { listResultTemplateType } from '@/api/parameter/basicPublicTemplate/consultantResultTemplateType';
    import type { ResultTemplateTypeQuery } from '@/api/parameter/basicPublicTemplate/consultantResultTemplateType/types';
    import ResultTemplateTypeDialog from '../consultantResultTemplateType/resultTemplateTypeDialog.vue';
    import { listDept } from '@/api/system/dept'; // 部门列表

    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const resultTemplateList = ref < ResultTemplateVO[] > ([]);
    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);
    import { useRouter } from 'vue-router';
    const treeData = ref([]); // 定义 treeData
    import { json } from 'stream/consumers';
    const router = useRouter();
    const queryFormRef = ref < ElFormInstance > ();
    const resultTemplateFormRef = ref < ElFormInstance > ();
    const resultTemplateTypeDialogRef = ref();

    interface ResultTemplateTypeOption {
        value: string | number;
        label: string;
    }
    const treeProps = ref({
        value: 'deptId', // 对应部门的 deptId
        label: 'deptName', // 对应部门的 deptName
        children: 'children' // 保持原有的父子结构
    });
    const templateTypeList = ref < ResultTemplateTypeOption[] > ([]);

    const dialog = reactive < DialogOption > ({
        visible: false,
        title: ''
    });
    const initFormData: ResultTemplateForm = {
        id: undefined,
        templateName: undefined,
        description: undefined,
        templateTypeId: undefined,
        content: undefined,
        createBy: undefined,
        createDept: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateDept: undefined,
        updateTime: undefined,
        searchValue: undefined,
        createDeptName: undefined,
        updateDeptName: undefined,

    }

    const initQueryParams = {
        pageNum: 1,
        pageSize: 10,
        searchValue: undefined,
        createBy: undefined,
        templateTypeId: undefined,
        startTime: undefined,
        endTime: undefined,
        params: {}
    }

    const data = reactive < PageData < ResultTemplateForm,
        ResultTemplateQuery >> ({
            form: { ...initFormData },

            queryParams: { ...initQueryParams },
            rules: {
                templateName: [
                    { required: true, message: "模板名称不能为空", trigger: "blur" }
                ],
                templateTypeId: [
                    { required: true, message: "类型不能为空", trigger: "change" }
                ],
                description: [
                    { required: true, message: "模板描述不能为空", trigger: "blur" }
                ]
            }
        });

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

    /** 获取类型名称 */
    const getTemplateTypeName = (typeId: string | number) => {
        const type = templateTypeList.value.find(t => t.value === typeId);
        return type ? type.label : '';
    };

    /** 查询会诊结果模板列表 */
    const getList = async () => {
        loading.value = true;
        const res = await listResultTemplate(queryParams.value);
        resultTemplateList.value = res.rows;
        // 获取部门数据
        const deptMap = new Map();
        treeData.value.forEach(dept => {
            deptMap.set(dept.deptId, dept.deptName);
            if (dept.children) {
                dept.children.forEach(child => {
                    deptMap.set(child.deptId, child.deptName);
                });
            }
        });
        total.value = res.total;
        loading.value = false;
    }

    const getDeptList = async () => {
        loading.value = true;
        try {
            const res = await listDept({});
            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;
        }
    };

    /** 获取会诊模板类型列表 */
    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 handleAdd = () => {
        router.push({
            path: '/argManage/consultantResultTemplateAdd',
            query: {
                templateTypeList: JSON.stringify(templateTypeList.value), // 序列化数组数据
            },
        });
    };
    /** 取消按钮 */
    const cancel = () => {
        reset();
        dialog.visible = false;
    }

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

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

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

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

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

    /** 查看详情按钮操作 */
    const handleDetail = (row: ResultTemplateVO) => {
        router.push({
            path: '/argManage/consultantResultTemplateDetail',
            query: { id: row.id }
        });
    };


    /** 修改按钮操作 */
    const handleUpdate = (row ? : ResultTemplateVO) => {
        const id = row ?.id || ids.value[0];
        router.push({
            path: '/argManage/consultantResultTemplateAdd',
            query: { id }
        });
    }


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

    /** 删除按钮操作 */
    const handleDelete = async (row ? : ResultTemplateVO) => {
        const _ids = row ?.id || ids.value;
        try {
            await proxy ?.$modal.confirm('是否确认删除该模板？');
            await delResultTemplate(_ids);
            proxy ?.$modal.msgSuccess("删除成功");
            await getList();
        } catch (error) {
            console.error('删除失败', error);
        }
    }

    onMounted(() => {
        getList();
        getDeptList(); // 初始化时加载部门数据
        getTemplateTypeList();
    });
</script>