layui.use(['form', 'layer', 'table', 'laytpl', 'treeTable'], function () {
    const form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table,
        treeTable = layui.treeTable;

    // 常量定义
    const TABLE_ID = 'listTable';
    const DEFAULT_LIMIT = 15;
    const PAGE_SIZES = [10, 15, 20, 25];

    /**
     * 格式化时间显示
     * @param {Date|string|number} tempDate - 时间
     * @returns {string} 格式化后的时间字符串
     */
    function formatTime(tempDate) {
        if (!tempDate) return '';

        const d = new Date(tempDate);
        if (isNaN(d.getTime())) return '';

        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hours = String(d.getHours()).padStart(2, '0');
        const minutes = String(d.getMinutes()).padStart(2, '0');
        const seconds = String(d.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    // 表格配置
    const tableConfig = {
        elem: '#list',
        url: '/upms/permission/queryPage',
        method: 'POST',
        contentType: 'application/json;charset=utf-8',
        cellMinWidth: 95,
        page: true,
        height: 'full-125',
        limits: PAGE_SIZES,
        limit: DEFAULT_LIMIT,
        id: TABLE_ID,
        request: {
            pageName: 'pageNo',
            limitName: 'pageRows'
        },
        response: {
            statusName: 'code',
            statusCode: 200,
            msgName: 'msg',
            countName: 'totalRows',
            dataName: 'data'
        },
        parseData: function (res) {
            return {
                code: res.code,
                msg: res.msg,
                totalRows: res.data?.totalRows || 0,
                data: res.data?.dataList || []
            };
        },
        cols: [[
            { type: 'checkbox', fixed: 'left', width: 50 },
            {field: 'privilegeName', title: '权限名称',width : "20%"},
            {field: 'privilegeCode', title: '权限标识'},
            {
                field: 'privilegeType', title: '权限类型', minWidth: 100, align: "center", templet: function (d) {
                    if (d.privilegeType == "0") {
                        return "父节点";
                    } else if (d.privilegeType == "1") {
                        return "子节点";
                    } else {
                        return "异常节点";
                    }
                }
            },
            {field: 'creator', title: '创建人', minWidth: 100, align: "center"},
            {
                field: 'createTime', title: '创建时间', minWidth: 100, align: "center", templet: function (d) {
                    return formatTime(d.createTime);
                }
            },
            {
                field: 'updateTime', title: '更新时间', align: 'center', minWidth: 150, templet: function (d) {
                    return formatTime(d.updateTime);
                }
            },
            {
                title: '操作',
                minWidth: 200,
                templet: '#listBar',
                fixed: 'right',
                align: 'center',
                toolBar: '#listBar'
            }
        ]]
    };

    /**
     * 打开编辑弹窗
     * @param {Object} editData - 编辑的数据，为空时表示新增
     */
    function openEditDialog(editData = null) {
        const title = editData ? '修改权限' : '添加权限';
        const index = layui.layer.open({
            title,
            type: 2,
            content: '/upms/permission/edit.html',
            area: ['100%', '100%'],
            success: function (layero, index) {
                const body = layui.layer.getChildFrame('body', index);
                if (editData) {
                    // 填充表单数据
                    body.find('#id').val(editData.id);
                    body.find('.userName').val(editData.userName);
                    body.find('.loginName').val(editData.loginName);
                    body.find('.userAddress').val(editData.userAddress);
                    body.find('.userIdCard').val(editData.userIdCard);
                    body.find('.userMobilePhone').val(editData.userMobilPhone);
                    body.find('.userEmail').val(editData.userEmail);
                    body.find('.userNickName').val(editData.userNickName);
                    body.find('.remark').val(editData.remark);
                    body.find(`.dncnet input[value="${editData.dncnet}"]`).prop('checked', true);
                    body.find(`.userStatus input[value="${editData.userStatus}"]`).prop('checked', true);
                    body.find(`.userType input[value="${editData.userType}"]`).prop('checked', true);
                    body.find(`.userGender input[value="${editData.userGender}"]`).prop('checked', true);
                    body.find('.userGrade').val(editData.userGrade);
                    body.find('.userDesc').text(editData.userDesc);
                    form.render();
                }

                setTimeout(() => {
                    layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500);
            }
        });

        // 存储弹窗索引用于响应式调整
        window.sessionStorage.setItem('dialogIndex', index);

        // 响应窗口大小变化
        $(window).off('resize.dialogResize').on('resize.dialogResize', () => {
            layer.full(window.sessionStorage.getItem('dialogIndex'));
        });
    }

    // 重置处理
    function handleReset() {
        // 1. 清空搜索框
        $('.privilegeName').val('');
        $('.privilegeCode').val('');


        // 2. 重置表单元素（如果有其他表单元素）
        resetFormElements();

        // 3. 可选：显示重置成功提示
        //layui.layer.msg("搜索条件已重置", { icon: 1, time: 1000 });
    }

    // 重置表单元素
    function resetFormElements() {
        // 重置下拉框
        $("select").each(function() {
            var $select = $(this);
            var defaultValue = $select.data('default-value') || $select.find("option:first").val();
            $select.val(defaultValue);
        });

        // 重置单选/复选框
        $("input[type='radio'], input[type='checkbox']").each(function() {
            var $input = $(this);
            if ($input.prop('defaultChecked')) {
                $input.prop('checked', true);
            } else {
                $input.prop('checked', false);
            }
        });

        // 重置其他输入框
        $("input[type='text'], input[type='number'], textarea").not(".searchVal").each(function() {
            var $input = $(this);
            var defaultValue = $input.data('default-value') || '';
            $input.val(defaultValue);
        });

        // 重新渲染表单
        form.render();
    }

    // 渲染表格
    const tableIns = table.render(tableConfig);

    // 搜索功能
    $('.search_btn').on('click', function () {
        table.reload(TABLE_ID, {
            page: { curr: 1 },
            where: {
                privilegeName: $('#privilegeName').val(),
                privilegeCode: $('#privilegeCode').val(),
                parentId: $('#parentId').val(),
                privilegeType: $('#privilegeType').val(),
                privilegeLevel: $('#privilegeLevel').val()
            }
        });
    });
    // 刷新
    $('.refresh').click(() => location.reload());

    $('.reset_btn').click(() => handleReset());

    // 添加功能
    $('.add_btn').click(() => openEditDialog());

    function treeList(){
        const setting = {
            check: {
                enable: true // 启用复选框功能
            },
            view: {
                showIcon: false // 不显示图标，可根据需要调整其他视图设置
            }
        };

        $.ajax({
            url: '/upms/permission/queryTreeList',
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            timeout: 30000, // 30秒超时
            success: function (res) {
                const permissionData = res.data;
                $.fn.zTree.init($("#permissionTree"), setting, permissionData);
            },
            error: function (xhr, status, error) {
                let errorMsg = '请求失败，请稍后重试';

                if (status === 'timeout') {
                    errorMsg = '请求超时，请稍后重试';
                } else if (xhr.status === 403) {
                    errorMsg = '权限不足，无法执行此操作';
                } else if (xhr.status === 500) {
                    errorMsg = '服务器内部错误';
                }
            }
        });
    }

    $(function(){
        treeList();
    });
});