<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.dateRange" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />

                        </el-form-item>
                        <el-form-item label="创建人科室">
                            <el-tree-select v-model="queryParams.createDept" :data="treeData" :props="treeProps" placeholder="请选择" check-strictly node-key="id" @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="适用科室">
                            <el-tree-select v-model="queryParams.deptId" :data="treeData" :props="treeProps" placeholder="请选择" check-strictly node-key="id" @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item prop="searchValue">
                            <el-input v-model="queryParams.searchValue" placeholder="模板名称/模板描述/创建人/最后编辑人" clearable style="width:300px" @keyup.enter="handleQuery" />
                        </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:educationTemplate:add']">新增模板</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>
            <el-table v-loading="loading" border :data="educationTemplateList" @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">
                    <template #default="scope">
                        <div class="description-cell" @mouseenter="showTooltip($event, scope.row.description)" @mouseleave="hideTooltip">
                            {{ scope.row.description }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="适用科室" align="center" prop="deptName" />
                <el-table-column label="创建时间" align="center" prop="createTime" />
                <el-table-column label="创建人姓名" align="center" prop="createByUser" />
                <el-table-column label="创建人科室" align="center" prop="createDeptName" />
                <el-table-column label="最后编辑时间" align="center" prop="updateTime" />
                <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-tooltip content="修改" placement="top">
                            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['basicPublicTemplate:educationTemplate:edit']">编辑</el-button>
                        </el-tooltip>
                        <el-tooltip content="详情" placement="top">
                            <el-button link type="primary" @click="handleDetail(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>
    <Teleport to="body">
        <Transition name="fade">
            <div v-if="tooltipVisible" class="custom-tooltip" :style="tooltipStyle">
                {{ tooltipContent }}
            </div>
        </Transition>
    </Teleport>
</template>

<script setup name="EducationTemplate" lang="ts">
    import { listEducationTemplate, getEducationTemplate, delEducationTemplate } from '@/api/parameter/basicPublicTemplate/nutritionEducationTemplate';
    import { EducationTemplateVO, EducationTemplateQuery } from '@/api/parameter/basicPublicTemplate/nutritionEducationTemplate/types';
    import { listDept } from '@/api/system/dept';
    import { useRouter } from 'vue-router';
    import type { DeptQuery } from '@/api/system/dept/types';

    const router = useRouter();
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;

    const educationTemplateList = ref < EducationTemplateVO[] > ([]);
    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 treeData = ref([]);
    const treeProps = ref({
        value: 'deptId',
        label: 'deptName',
        children: 'children'
    });

    const queryFormRef = ref < ElFormInstance > ();

    const data = reactive({
        queryParams: {
            pageNum: 1,
            pageSize: 10,
            searchValue: undefined,
            deptId: undefined,
            dateRange: undefined,
            createDept: undefined,
            params: {}
        } as EducationTemplateQuery
    });

    const initQueryParams = () => {
        queryParams.value = {
            pageNum: 1,
            pageSize: 10,
            searchValue: undefined,
            deptId: undefined,
            dateRange: undefined,
            createDept: undefined,
            params: {}
        };
    };

    const { queryParams } = toRefs(data);

    // 添加tooltip相关的状态和方法
    const tooltipVisible = ref(false);
    const tooltipContent = ref('');
    const tooltipStyle = ref({
        left: '0px',
        top: '0px'
    });

    const showTooltip = (event: MouseEvent, content: string) => {
        const target = event.target as HTMLElement;
        const rect = target.getBoundingClientRect();

        tooltipContent.value = content;
        tooltipStyle.value = {
            left: `${rect.left + window.scrollX}px`,
            top: `${rect.bottom + window.scrollY + 5}px`
        };
        tooltipVisible.value = true;
    };

    const hideTooltip = () => {
        tooltipVisible.value = false;
    };

    /** 查询营养宣教模板列表 */
    const getList = async () => {
        loading.value = true;
        const res = await listEducationTemplate(queryParams.value);
        educationTemplateList.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({
                    pageNum: 1,
                    pageSize: 100
                }as DeptQuery);
            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 handleQuery = () => {
        queryParams.value.pageNum = 1;
        getList();
    }

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

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

    /** 新增按钮操作 */
    const handleAdd = () => {
        router.push('/argManage/nutritionEducationTemplateAdd');
    }

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

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

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

    /** 导出按钮操作 */
    const handleExport = () => {
        proxy ?.download('system/educationTemplate/export', {
            ...queryParams.value
        }, `educationTemplate_${new Date().getTime()}.xlsx`)
    }

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

<style scoped>
    .description-cell {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        line-height: 1.5;
        max-height: 3em;
        text-align: left;
        padding: 0 8px;
        cursor: pointer;
    }

    .custom-tooltip {
        position: fixed;
        z-index: 9999;
        background: white;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        padding: 12px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        max-width: 400px;
        line-height: 1.5;
        font-size: 14px;
        word-break: break-all;
        text-align: left;
    }

    .fade-enter-active,
    .fade-leave-active {
        transition: opacity 0.2s ease;
    }

    .fade-enter-from,
    .fade-leave-to {
        opacity: 0;
    }
</style>