<template>
    <div class="strategy-manage pd10" :style="height" style="overflow-y: auto;">
       
        <!-- 折叠面板 -->
        <el-collapse v-model="activeNames" >
            <!-- 客户端配置 -->
            <el-collapse-item title="客户端配置" name="1">
                <div style="width: 500px">
                    <el-form ref="formRef" :model="form" label-width="auto" :rules="rules">                       
                        <el-form-item label="认证令牌时效(秒):" prop="accessTokenValidity">
                            <el-input-number
                                v-model.number="form.accessTokenValidity"
                                :min="10"
                                style="width: 100%"
                            ></el-input-number>
                        </el-form-item>
                        <el-form-item label="刷新令牌时效(秒):" prop="refreshTokenValidity">
                            <el-input-number
                                v-model.number="form.refreshTokenValidity"
                                :min="10"
                                style="width: 100%"
                            ></el-input-number>
                        </el-form-item>
                    </el-form>
                </div>
                <el-button @click="AddClick()" type="primary" :icon="Check" >保存</el-button>
                  
            </el-collapse-item>

             <el-collapse-item :title="item.name"  v-for="(item, index) in column" :key="index" :name="String(index + 2)" >
                <div class="mb10">
                    <el-button 
                        type="primary" 
                        icon="el-icon-Plus" 
                        @click="addForm()"
                        v-if="item.name === '系统配置'"
                    >
                    新增类型</el-button>
                </div>
                <div style="height: 200px">
                    <vxe-table
                        height="auto"
                        :data="configForm[item.key]"
                        v-bind="defaultAttribute"
                    >
                        <vxe-column
                            v-for="(k, index) in item.child"
                            :key="index"
                            :field="k.field"
                            :title="k.title"
                        ></vxe-column>
                        <vxe-column title="操作" width="150px">
                            <template #default="{ row }">
                                <el-button type="text"  @click="sysActive(row)" v-if="item.key =='getSystemList' && row.state == '未激活'">激活</el-button>
                                <el-button type="text"  @click="editConfig(item, row)">编辑</el-button>
                                <el-button type="text"  @click="sysDelete(row)" v-if="item.key =='getSystemList'">删除</el-button>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </div>
            </el-collapse-item>
        </el-collapse>


        <el-dialog v-model="dialogVisible" title="编辑用户配置" width="500px">
                    <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="auto">
                        <el-form-item label="密码有效期(月):" prop="passwordExpirationMonth">
                            <el-input-number
                                v-model.number="editForm.passwordExpirationMonth"
                                :min="1"
                                :max="6"
                                style="width: 100%"
                            ></el-input-number>
                        </el-form-item>
                        <el-form-item label="密码错误次数限定(次):" prop="errorsCount">
                            <el-input-number
                                v-model.number="editForm.errorsCount"
                                :min="3"
                                :max="20"
                                style="width: 100%"
                            ></el-input-number>
                        </el-form-item>
                        <el-form-item label="验证密码错误次数时间范围(分钟):" prop="lockPwdCheck">
                            <el-input-number
                                v-model.number="editForm.lockPwdCheck"
                                :min="5"
                                :max="60"
                                style="width: 100%"
                            ></el-input-number>
                        </el-form-item>
                        <el-form-item label="用户锁定时间(分钟):" prop="releaseTime">
                            <el-input-number
                                v-model.number="editForm.releaseTime"
                                :min="30"
                                :max="60"
                                style="width: 100%"
                            ></el-input-number>
                        </el-form-item>
                        <el-form-item label="用户休眠(天):" prop="sleepDay">
                            <el-input-number
                                v-model.number="editForm.sleepDay"
                                :min="1"
                                :max="180"
                                style="width: 100%"
                            ></el-input-number>
                        </el-form-item>
                        <el-form-item label="用户注销(天):" prop="logoutDay">
                            <el-input-number
                                v-model.number="editForm.logoutDay"
                                :min="1"
                                :max="360"
                                style="width: 100%"
                            ></el-input-number>
                        </el-form-item>
                        <el-form-item label="最大并发数:" prop="maxUseUser">
                            <el-input-number
                                v-model.number="editForm.maxUseUser"
                                :min="10"
                                :max="99"
                                style="width: 100%"
                            ></el-input-number>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="saveEdit">确定</el-button>
                        </span>
                    </template>
        </el-dialog>

         <el-dialog v-model="systemDialogVisible" :title=sysTitle width="500px">
                    <el-form ref="sysFormRef" :model="sysForm" :rules="sysRules" label-width="auto">
                         <el-form-item label="系统类型:" prop="type">
                    <el-select v-model="sysForm.type" placeholder="请选择系统类型" style="width: 100%" filterable>
                       <el-option label="省级系统" value="0"></el-option>
                       <el-option label="企业系统" value="1"></el-option>
                       <el-option label="数据中心" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数据上报:" prop="dataReport" class="top">
                    <el-input style="width: 100%" v-model="sysForm.dataReport" placeholder="请输入数据上报"></el-input>
                </el-form-item>
                <el-form-item label="审计日志大小(M):" prop="logSize" class="top">
                    <el-input-number
                        style="width: 100%"
                        type="number"
                        v-model="sysForm.logSize"
                        :min="1024"
                        :max="20480"
                        placeholder="请输入审计日志大小"
                    ></el-input-number>
                </el-form-item>
                <el-form-item label="日志储存时间(月):" prop="logTime" class="top">
                    <el-input-number
                        style="width: 100%"
                        type="number"
                        v-model="sysForm.logTime"
                        :min="1"
                        :max="6"
                        placeholder="请输入日志储存时间不能大于6个月"
                    ></el-input-number>
                </el-form-item>
                <el-form-item label="激活状态:" class="top" prop="state">
                    <el-select
                        v-model="sysForm.state"
                        :disabled="flagtyoe == 'add' ? false : true"
                        placeholder="请选择"
                        style="width: 100%"
                        filterable
                    >
                        <el-option label="未激活" value="0"></el-option>
                         <el-option label="已激活" value="1"></el-option>
                    </el-select>
                </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="systemDialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="saveSystem">确定</el-button>
                        </span>
                    </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, MessageParams } from 'element-plus'
import { updateClientSessionConfig, getClientInfoByPath, ruleUpdate ,getUserConfig,getSystemList,activeSystemConfig,deleteSystemConfig,addSystemConfig,updateSystemConfig} from '@/api/admin/user.js'
import { Check } from '@element-plus/icons-vue'
import { mainHeight } from '@/utils/layout'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import {  ElMessageBox } from 'element-plus'

// 页面缓存
defineOptions({
    name: 'system-boot/strategyManage'
})

const height = mainHeight(20)

// 定义表单引用
const formRef = ref()
const editFormRef = ref()
const sysFormRef = ref()
const dialogVisible = ref(false)
const systemDialogVisible = ref(false)
const activeNames = ref(['1', '2', '3']) // 默认展开所有面板
const flagtyoe = ref('add') // 用于区分新增或编辑模式
const sysTitle = ref('新增系统配置')


// 定义表单数据
const form = reactive({
    accessTokenValidity: 0,
    refreshTokenValidity: 0,
})

// 定义表单验证规则
const rules = {
    accessTokenValidity: [{ required: true, message: '请填写会话超时时间', trigger: 'blur' }],
    refreshTokenValidity: [{ required: true, message: '请填写会话刷新时间', trigger: 'blur' }],
}

const editForm = ref({
    passwordExpirationMonth: 3,
    errorsCount: 5,
    lockPwdCheck: 30,
    releaseTime: 30,
    sleepDay: 3,
    logoutDay: 7,
    maxUseUser: 50,
    type: '',
})

const editRules = {
    passwordExpirationMonth: [{ required: true, message: '请输入密码有效期', trigger: 'blur' }],
    errorsCount: [{ required: true, message: '请输入密码错误次数限定', trigger: 'blur' }],
    lockPwdCheck: [{ required: true, message: '请输入验证密码错误次数时间范围', trigger: 'blur' }],
    releaseTime: [{ required: true, message: '请输入用户锁定时间', trigger: 'blur' }],
    sleepDay: [{ required: true, message: '请输入用户休眠时间', trigger: 'blur' }],
    logoutDay: [{ required: true, message: '请输入用户注销时间', trigger: 'blur' }],
    maxUseUser: [{ required: true, message: '请输入最大并发数', trigger: 'blur' }],
}

const sysForm = ref({
    type: '',
    dataReport: '',
    logSize: 1024,
    logTime: 1,
    state: '',
})

const sysRules = {
    type: [{ required: true, message: '请选择系统类型', trigger: 'change' }],
    dataReport: [{ required: true, message: '请输入数据上报', trigger: 'blur' }],
    logSize: [{ required: true, message: '请输入审计日志大小', trigger: 'blur' }],
    logTime: [{ required: true, message: '请输入日志储存时间', trigger: 'blur' }],
    state: [{ required: true, message: '请选择激活状态', trigger: 'change' }],
}

// 编辑配置项
const editConfig = (item: any, row: any) => {
    if(item.name == '用户配置'){
         dialogVisible.value = true
        Object.assign(editForm.value, row)
    }else{
        systemDialogVisible.value = true
        flagtyoe.value = 'edit'
        sysTitle.value = '编辑系统配置'
        Object.assign(sysForm.value, row)
    }
   
}

// 保存客户端配置
const AddClick = () => {
    formRef.value.validate((valid: any) => {
        if (valid) {
            updateClientSessionConfig(form).then((res: { data: any }) => {
                Object.assign(form, res.data)
                ElMessage.success(res.message)
                info(0)
            })
        }
    })
}

// 保存用户配置编辑
const saveEdit = () => {
    editFormRef.value.validate((valid: any) => {
        if (valid) {
            const formData = {
                ...editForm.value,
                type: parseUserType(editForm.value.type),
            }
            ruleUpdate(formData).then((res: any) => {
                ElMessage.success(res.message)
                dialogVisible.value = false
                info(1)
            })
        }
    })
}

const configForm = ref({
    getUserConfig: [], //用户配置
    getSystemList: [], //系统配置
})


const column = readonly([
    {
        name: '用户配置',
        key: 'getUserConfig',
        child: [
            { field: 'passwordExpirationMonth', title: '密码有效期(月)', width: '120' },
            { field: 'errorsCount', title: '密码错误次数限定', minWidth: '120' },
            { field: 'lockPwdCheck', title: '验证密码错误次数时间范围(天)', minWidth: '200' },
            { field: 'releaseTime', title: '用户锁定时间', width: '120' },
            { field: 'sleepDay', title: '用户休眠(天)', width: '120' },
            { field: 'logoutDay', title: '用户注销(天)', width: '120' },
            { field: 'maxUseUser', title: '最大并发数', width: '120' },
            {field: 'type',title: '用户类型',width: '120'},
        ]
    },
    {   
        name: '系统配置',
        key: 'getSystemList',
        child: [
            {
                title: '系统类型',
                field: 'type',
            },
            {
                title: '数据上报',
                field: 'dataReport'
            },
            {
                title: '审计日志大小(M)',
                field: 'logSize'
            },
            {
                title: '审计日志存储时间(月))',
                field: 'logTime'
            },
            {
                title: '状态',
                field: 'state',

            },
            {
                title: '创建用户',
                field: 'createBy'
            },
            {
                title: '创建时间',
                field: 'createTime'
            },
            {
                title: '更新用户',
                field: 'updateBy'
            },
            {
                title: '更新时间',
                field: 'updateTime'
            },
        ]
    }
])

// 获取客户端配置
 const info = async (type: number) => {
    if (type === 0) {
        // 获取客户端配置
        await getClientInfoByPath().then((res: { data: any }) => {
                Object.assign(form, res.data)
        })
    } else if (type === 1) {
         // 获取用户配置
         await getUserConfig().then((res: { data: { map: (arg0: (item: any) => any) => never[] } }) => {
            configForm.value.getUserConfig = res.data.map((item: any) => ({
                ...item,
                type: formatUserType(item.type) 
            }))
        })
    } else {
        // 获取系统配置
        await getSystemList().then((res: { data: { map: (arg0: (item: any) => any) => never[] } }) => {
            configForm.value.getSystemList = res.data.map((item: any) => ({
                ...item,
                type: formatSystemType(item.type),
                state: formatSystemState(item.state)
            }))
      })
    }
}

const formatUserType = (type: number) => {
    return type === 1 ? '正常用户' : '临时用户'
}

const formatSystemType = (type: number) => {
    return type === 0 ? '省级系统' : type === 1 ? '企业系统' : type === 2 ? '数据中心'  : '/'
}

const formatSystemState = (type: number) => {
    return type === 0 ? '未激活' : '已激活' 
}

// 将用户类型从中文转换为数字
const parseUserType = (type: string): number => {
    return type === '正常用户' ? 1 : 0
}

// 将系统类型从中文转换为数字
const parseSystemType = (type: string): number => {
    return type === '省级系统' ? 0 : type === '企业系统' ? 1 : type === '数据中心' ? 2 : -1
}

// 将系统状态从中文转换为数字
const parseSystemState = (state: string): number => {
    return state === '未激活' ? 0 : 1
}

// 新增 addForm 方法
const addForm = () => {
        // 初始化系统配置表单
        sysForm.value = {
            type: '',
            dataReport: '',
            logSize: 1024,
            logTime: 1,
            state: '',
        }
        flagtyoe.value = 'add' // 标记为新增模式
        sysTitle.value = '新增系统配置'
        systemDialogVisible.value = true // 打开系统配置弹窗
}

// 删除系统配置
const sysDelete = (row: any) => {
    let data = {
        id: row.id
    }
    ElMessageBox.confirm('此操作将永久删除该配置, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
    }).then(() => {
                deleteSystemConfig(data).then((res: any) => {
                ElMessage.success(res.message)
                info(2) // 刷新系统配置列表
            })
    })
    
}


// 激活系统配置
const sysActive = (row: any) => {
    // 构造请求参数
    const data = {
        id: row.id,
        type: parseSystemType(row.type),
        logSize: row.logSize,
        logTime: row.logTime,
        dataReport: row.dataReport,
        state: 1
    }

    // 弹出确认框
    ElMessageBox.confirm('此操作将激活该系统配置，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
    .then(() => {
        // 用户点击“确定”，执行激活操作
        activeSystemConfig(data).then((res: any) => {
            ElMessage.success(res.message)
            info(2) // 刷新系统配置列表
        }).catch((err: any) => {
            ElMessage.error('激活失败，请重试')
        })
    })
    
}

// 保存系统配置
const saveSystem = () => {
    sysFormRef.value.validate((valid: any) => {
        if (valid) {
            if (flagtyoe.value === 'add') {
                addSystemConfig(sysForm.value).then((res: any) => {
                    ElMessage.success(res.message)
                    systemDialogVisible.value = false
                    info(2)
                })
            } else {
                const formData = {
                    ...sysForm.value,
                    type: parseSystemType(sysForm.value.type),
                    state: parseSystemState(sysForm.value.state)
                }
                updateSystemConfig(formData).then((res: any) => {
                    ElMessage.success(res.message)
                    systemDialogVisible.value = false
                    info(2)
                })
            }
        }
    })
}



// 组件挂载时获取数据
onBeforeMount(() => {
    info(0)
    info(1)
    info(2)
})
</script>

<style lang="less" scoped>
.strategy-manage {
    background-color: #fff;
    margin: 10px;
}
/* 增大折叠面板标题字体 */
:deep(.el-collapse-item__header) {
    font-size: 20px; /* 设置字体大小 */
    font-weight: bold; /* 加粗字体 */
    //color: var(--el-color-primary); /* 可选：设置颜色 */
}

:deep(.el-form-item__label) {
    
    font-weight: 600;
}
</style>