<template>
    <div class="p-2">
        <!-- 处方模板类型选择菜单 -->
        <el-card shadow="hover" class="mb-4">
            <div class="template-header">
                <div class="template-title">
                    <el-icon class="title-icon">
                        <User />
                    </el-icon>
                    <span class="title-text">个人模板</span>
                </div>
                <el-radio-group v-model="queryParams.type" @change="handleTypeChange"
                    class="prescription-type-selector">
                    <el-radio-button :label="2">预包装处方模板</el-radio-button>
                    <el-radio-button :label="3">配置处方模板</el-radio-button>
                    <el-radio-button :label="4">长嘱处方模板</el-radio-button>
                </el-radio-group>
            </div>
        </el-card>

        <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 label="模板名称" prop="templateName">
                            <el-input v-model="queryParams.templateName" placeholder="请输入模板名称" clearable
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="模板描述" prop="templateDescription">
                            <el-input v-model="queryParams.templateDescription" placeholder="请输入模板描述" clearable
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="处方科室" prop="prescriptionDepartmentName">
                            <el-input v-model="queryParams.prescriptionDepartmentName" placeholder="请输入处方科室" clearable
                                @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="['system:personalEnteralNutritionTemplate:add']">新增模板</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                            v-hasPermi="['system:personalEnteralNutritionTemplate:edit']">修改</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                            v-hasPermi="['system:personalEnteralNutritionTemplate:remove']">删除</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="Download" @click="handleExport"
                            v-hasPermi="['system:personalEnteralNutritionTemplate:export']">导出</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table v-loading="loading" border :data="personalEnteralNutritionTemplateList"
                @selection-change="handleSelectionChange" class="personal-template-table">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="模板名称" align="center" prop="templateName" min-width="150">
                    <template #default="scope">
                        <div class="template-name-cell">
                            <el-icon class="personal-icon">
                                <UserFilled />
                            </el-icon>
                            <span class="template-name">{{ scope.row.templateName }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="模板描述" align="center" prop="templateDescription" min-width="200"
                    show-overflow-tooltip />
                <el-table-column label="处方类型" align="center" prop="prescriptionType" width="120">
                    <template #default="scope">
                        <el-tag :type="getPrescriptionTypeTagType(scope.row.prescriptionType)" effect="light">
                            {{ getPrescriptionTypeText(scope.row.prescriptionType) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="处方科室" align="center" prop="prescriptionDepartmentName" min-width="120"
                    show-overflow-tooltip />
                <el-table-column label="状态" align="center" prop="status" width="80">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'" effect="light">
                            {{ scope.row.status === '0' ? '正常' : '停用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" prop="createTime" width="150">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="创建者" align="center" prop="createBy" width="120" show-overflow-tooltip />
                <el-table-column label="更新者" align="center" prop="updateBy" width="120" show-overflow-tooltip />
                <el-table-column label="最后编辑时间" align="center" prop="updateTime" width="150">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160"
                    fixed="right">
                    <template #default="scope">
                        <el-tooltip content="查看详情" placement="top">
                            <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="修改" placement="top">
                            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                                v-hasPermi="['system:personalEnteralNutritionTemplate:edit']"></el-button>
                        </el-tooltip>
                        <el-tooltip content="复制" placement="top">
                            <el-button link type="warning" icon="CopyDocument"
                                @click="handleCopy(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
                                v-hasPermi="['system:personalEnteralNutritionTemplate:remove']"></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>

        <!-- 模板详情查看对话框 -->
        <el-dialog :title="viewDialog.title" v-model="viewDialog.visible" width="80%" append-to-body
            class="template-detail-dialog">
            <div class="template-detail-content" v-if="viewTemplateData">
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="模板名称">
                        <div class="template-name-cell">
                            <el-icon class="personal-icon">
                                <UserFilled />
                            </el-icon>
                            <span class="template-name">{{ viewTemplateData.templateName }}</span>
                        </div>
                    </el-descriptions-item>
                    <el-descriptions-item label="处方类型">
                        <el-tag :type="getPrescriptionTypeTagType(viewTemplateData.prescriptionType)" effect="light">
                            {{ getPrescriptionTypeText(viewTemplateData.prescriptionType) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="模板描述" :span="2">{{ viewTemplateData.templateDescription
                    }}</el-descriptions-item>
                    <el-descriptions-item label="处方科室">{{ viewTemplateData.prescriptionDepartmentName
                    }}</el-descriptions-item>
                    <el-descriptions-item label="状态">
                        <el-tag :type="viewTemplateData.status === '0' ? 'success' : 'danger'" effect="light">
                            {{ viewTemplateData.status === '0' ? '正常' : '停用' }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="创建时间">
                        {{ parseTime(viewTemplateData.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                    </el-descriptions-item>
                    <el-descriptions-item label="创建者">{{ viewTemplateData.createBy || '未知' }}</el-descriptions-item>
                    <el-descriptions-item label="更新者">{{ viewTemplateData.updateBy || '未知' }}</el-descriptions-item>
                    <el-descriptions-item label="最后编辑时间">
                        {{ parseTime(viewTemplateData.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
                    </el-descriptions-item>
                </el-descriptions>
                <div class="template-content-section">
                    <h4>模板内容：</h4>
                    <div class="content-preview">
                        <pre>{{ formatTemplateContent(viewTemplateData.content) }}</pre>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="viewDialog.visible = false">关闭</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 添加或修改个人肠内处方模板对话框 -->
        <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
            <el-form ref="personalEnteralNutritionTemplateFormRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="模板名称" prop="templateName">
                    <el-input v-model="form.templateName" placeholder="请输入模板名称" />
                </el-form-item>
                <el-form-item label="模板描述" prop="templateDescription">
                    <el-input v-model="form.templateDescription" type="textarea" :rows="3" placeholder="请输入模板描述" />
                </el-form-item>
                <el-form-item label="处方类型" prop="prescriptionType">
                    <el-select v-model="form.prescriptionType" placeholder="请选择处方类型" style="width: 100%">
                        <el-option label="预包装处方模板" value="2" />
                        <el-option label="配置处方模板" value="3" />
                        <el-option label="长嘱处方模板" value="4" />
                    </el-select>
                </el-form-item>
                <el-form-item label="处方科室ID" prop="prescriptionId">
                    <el-input v-model="form.prescriptionId" placeholder="请输入处方科室ID" />
                </el-form-item>
                <el-form-item label="营养产品信息">
                    <editor v-model="form.content" :min-height="192" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio label="0">正常</el-radio>
                        <el-radio label="1">停用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="PersonalEnteralNutritionTemplate" lang="ts">
import { listPersonalEnteralNutritionTemplate, getPersonalEnteralNutritionTemplate, delPersonalEnteralNutritionTemplate, addPersonalEnteralNutritionTemplate, updatePersonalEnteralNutritionTemplate } from '@/api/parameter/personalTemplate/enteralNutritionTemplate';
import { PersonalEnteralNutritionTemplateVO, PersonalEnteralNutritionTemplateQuery, PersonalEnteralNutritionTemplateForm } from '@/api/parameter/personalTemplate/enteralNutritionTemplate/types';
import { useRouter, useRoute } from 'vue-router';
import { User, UserFilled } from '@element-plus/icons-vue';

const router = useRouter();
const route = useRoute();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const personalEnteralNutritionTemplateList = ref<PersonalEnteralNutritionTemplateVO[]>([]);
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 queryFormRef = ref<ElFormInstance>();
const personalEnteralNutritionTemplateFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const viewDialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const viewTemplateData = ref<PersonalEnteralNutritionTemplateVO | null>(null);

const initFormData: PersonalEnteralNutritionTemplateForm = {
    id: undefined,
    templateName: undefined,
    templateDescription: undefined,
    prescriptionType: undefined,
    prescriptionId: undefined,
    content: undefined,
    status: '0',
    delFlag: undefined,
    templateType: 0 // 0表示个人模板
}

const data = reactive<PageData<PersonalEnteralNutritionTemplateForm, PersonalEnteralNutritionTemplateQuery>>({
    form: { ...initFormData },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: undefined,
        templateDescription: undefined,
        type: 2,
        prescriptionType: undefined,
        prescriptionId: undefined,
        prescriptionDepartmentName: undefined,
        content: undefined,
        status: undefined,
        templateType: 0, // 设置为个人模板类型
        params: {}
    },
    rules: {
        templateName: [
            { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        prescriptionType: [
            { required: true, message: "处方类型不能为空", trigger: "change" }
        ]
    }
});

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

// 获取处方类型显示文本
const getPrescriptionTypeText = (type: string) => {
    switch (type) {
        case '2':
            return '预包装处方';
        case '3':
            return '配置处方';
        case '4':
            return '长嘱处方';
        default:
            return '未知类型';
    }
};

// 获取处方类型标签样式
const getPrescriptionTypeTagType = (type: string) => {
    switch (type) {
        case '2':
            return 'primary';
        case '3':
            return 'success';
        case '4':
            return 'warning';
        default:
            return 'info';
    }
};

// 格式化模板内容用于显示
const formatTemplateContent = (content: string) => {
    try {
        const parsed = JSON.parse(content);
        return JSON.stringify(parsed, null, 2);
    } catch {
        return content;
    }
};

/** 查询个人肠内处方模板列表 */
const getList = async () => {
    loading.value = true;
    try {
        const res = await listPersonalEnteralNutritionTemplate(queryParams.value);
        personalEnteralNutritionTemplateList.value = res.rows;
        total.value = res.total;
    } catch (error) {
        console.error('获取个人模板列表失败:', error);
        personalEnteralNutritionTemplateList.value = [];
        total.value = 0;
    } finally {
        loading.value = false;
    }
}

/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
}

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

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

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

/** 处方模板类型变更处理 */
const handleTypeChange = (type: number) => {
    queryParams.value.type = type;
    queryParams.value.pageNum = 1;
    getList();
}

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

/** 新增按钮操作 */
const handleAdd = () => {
    router.push({
        path: '/argManage/enteralNutritionTemplateAdd',
        query: {
            type: queryParams.value.type,
            action: 'add',
            templateType: 0  // 标识为个人模板
        }
    });
}

/** 查看模板详情 */
const handleView = async (row: PersonalEnteralNutritionTemplateVO) => {
    try {
        const res = await getPersonalEnteralNutritionTemplate(row.id);
        viewTemplateData.value = res.data;
        viewDialog.visible = true;
        viewDialog.title = `查看模板详情 - ${row.templateName}`;
    } catch (error) {
        console.error('获取模板详情失败:', error);
        proxy?.$modal.msgError("获取模板详情失败");
    }
}

/** 复制模板 */
const handleCopy = async (row: PersonalEnteralNutritionTemplateVO) => {
    router.push({
        path: '/argManage/enteralNutritionTemplateAdd',
        query: {
            copyId: row.id,  // 使用copyId标识复制操作
            type: queryParams.value.type,
            action: 'add',
            templateType: 0  // 标识为个人模板
        }
    });
}

/** 修改按钮操作 */
const handleUpdate = async (row?: PersonalEnteralNutritionTemplateVO) => {
    router.push({
        path: '/argManage/enteralNutritionTemplateAdd',
        query: {
            id: row?.id || ids.value[0],
            type: queryParams.value.type,
            action: 'update',
            templateType: 0  // 标识为个人模板
        }
    });
}

/** 提交按钮 */
const submitForm = () => {
    personalEnteralNutritionTemplateFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            try {
                // 确保设置为个人模板
                form.value.templateType = 0;

                if (form.value.id) {
                    await updatePersonalEnteralNutritionTemplate(form.value);
                } else {
                    await addPersonalEnteralNutritionTemplate(form.value);
                }
                proxy?.$modal.msgSuccess("操作成功");
                dialog.visible = false;
                await getList();
            } catch (error) {
                console.error('提交失败:', error);
                proxy?.$modal.msgError("操作失败");
            } finally {
                buttonLoading.value = false;
            }
        }
    });
}

/** 删除按钮操作 */
const handleDelete = async (row?: PersonalEnteralNutritionTemplateVO) => {
    const _ids = row?.id || ids.value;
    try {
        await proxy?.$modal.confirm('是否确认删除个人模板编号为"' + _ids + '"的数据项？');
        await delPersonalEnteralNutritionTemplate(_ids);
        proxy?.$modal.msgSuccess("删除成功");
        await getList();
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error);
            proxy?.$modal.msgError("删除失败");
        }
    }
}

/** 导出按钮操作 */
const handleExport = () => {
    // 使用与基础公共模板相同的导出接口，通过templateType=0过滤个人模板
    const exportParams = { ...queryParams.value, templateType: 0 };
    proxy?.download('parameter/basicPublicTemplate/enteralNutritionTemplate/export', exportParams, `personal_enteral_nutrition_template_${new Date().getTime()}.xlsx`)
}

// 初始化状态锁，防止重复初始化
const isInitializing = ref(false)

/** 页面初始化函数 */
const initializePage = async () => {
    // 防止重复初始化
    if (isInitializing.value) {
        console.log('个人模板页面正在初始化中，跳过重复初始化')
        return
    }

    try {
        isInitializing.value = true
        console.log('个人肠内处方模板列表页面初始化')

        // 重置选择状态
        ids.value = []
        single.value = true
        multiple.value = true

        // 重置分页到第一页（保持搜索条件和处方类型）
        queryParams.value.pageNum = 1

        // 显示加载状态
        loading.value = true

        // 重新获取数据
        await getList()

        console.log('个人模板页面初始化完成')
    } catch (error) {
        console.error('个人模板页面初始化失败:', error)
        // 确保加载状态被重置
        loading.value = false
    } finally {
        // 延迟重置锁，避免快速连续的路由变化
        setTimeout(() => {
            isInitializing.value = false
        }, 300)
    }
}

// 监听路由变化 - 检测从其他页面跳转回来
watch(() => route.fullPath, async (newFullPath, oldFullPath) => {
    // 当前页面的路径模式
    const isCurrentListPage = newFullPath.includes('personalTemplate/enteralNutritionTemplate') &&
        !newFullPath.includes('Add') &&
        !newFullPath.includes('Edit')

    // 上一个页面是否为非列表页
    const wasNotListPage = !oldFullPath ||
        !oldFullPath.includes('personalTemplate/enteralNutritionTemplate') ||
        oldFullPath.includes('Add') ||
        oldFullPath.includes('Edit')

    // 如果从非列表页跳转到列表页，则重新初始化
    if (newFullPath !== oldFullPath && isCurrentListPage && wasNotListPage) {
        console.log('检测到从其他页面跳转回个人模板列表页，重新初始化')
        console.log('旧路径:', oldFullPath)
        console.log('新路径:', newFullPath)
        await initializePage()
    }
}, { flush: 'post' })

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

<style scoped>
.template-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
}

.template-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 600;
    color: #409eff;
}

.title-icon {
    font-size: 18px;
}

.prescription-type-selector {
    display: flex;
    justify-content: center;
    align-items: center;
}

.prescription-type-selector .el-radio-button {
    margin: 0 4px;
}

.prescription-type-selector .el-radio-button__inner {
    padding: 8px 20px;
    font-weight: 500;
    border-radius: 6px;
    transition: all 0.3s ease;
}

.prescription-type-selector .el-radio-button__inner:hover {
    color: var(--el-color-primary);
    border-color: var(--el-color-primary);
}

.prescription-type-selector .el-radio-button.is-active .el-radio-button__inner {
    background-color: var(--el-color-primary);
    border-color: var(--el-color-primary);
    color: #fff;
    box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

.personal-template-table {
    --el-table-header-bg-color: #f8fafc;
}

.template-name-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}

.personal-icon {
    color: #409eff;
    font-size: 16px;
}

.template-name {
    font-weight: 500;
}

.template-detail-dialog .template-detail-content {
    padding: 20px 0;
}

.template-content-section {
    margin-top: 24px;
}

.template-content-section h4 {
    margin-bottom: 12px;
    color: #303133;
    font-weight: 600;
}

.content-preview {
    background-color: #f5f7fa;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 16px;
    max-height: 300px;
    overflow-y: auto;
}

.content-preview pre {
    margin: 0;
    font-family: 'Courier New', monospace;
    font-size: 12px;
    line-height: 1.5;
    color: #606266;
    white-space: pre-wrap;
    word-wrap: break-word;
}

.mb-4 {
    margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .template-header {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;
    }

    .prescription-type-selector {
        width: 100%;
        justify-content: flex-start;
        flex-wrap: wrap;
    }

    .prescription-type-selector .el-radio-button {
        margin: 4px;
    }
}
</style>