layui.config({
    base: '/assets/lib/jplus/treeTable/'
}).use(['form', 'layer', 'table', 'laytpl', 'treeTable'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table,
        treeTable = layui.treeTable;

    //用户列表
    var tableIns = table.render({
        elem: '#list',
        url: '/cms/book/categories/queryPage',
        method: 'POST',
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        headers: {token: ''},
        cellMinWidth: 95,
        page: true,
        height: "full-125",
        limits: [10, 15, 20, 25],
        limit: 15,
        id: "listTable",
        request: {
            pageName: "pageNo",//重新定义当前页码参数名称
            limitName: "pageRows"//重新定义每页大小参数名称
        },
        response: {
            statusName: 'code', //数据状态的字段名称，默认：code
            statusCode: 200, //成功的状态码，默认：0
            msgName: 'msg',  //状态信息的字段名称，默认：msg
            countName: 'totalRows',  //数据总数的字段名称，默认：count
            dataName: 'data' //数据列表的字段名称，默认：data
        },
        where: {
            //请求的参数写在where
        },
        parseData: function (res) {
            return {
                "code": res.code,
                "msg": res.msg, //解析提示文本
                "totalRows": res.data.totalRows, //解析数据长度
                "data": res.data.dataList, //解析数据列表
            };
        },
        cols: [[
            {type: "checkbox", fixed: "left", width: 50},
            {field: 'categoryCode', title: '分类代码', minWidth: 100, align: "center"},
            {field: 'categoryName', title: '分类名称', minWidth: 100, align: "center"},
            {field: 'englishName', title: '英文名称', minWidth: 100, align: "center"},
            {
                field: 'parentId', title: '父级分类', align: 'center', templet: function (d) {
                    if (d.parentId == "0") {
                        return "顶级分类";
                    } else if (d.parentId == "1") {
                        return "一级分类";
                    } else if (d.parentId == "2") {
                        return "二级分类";
                    } else {
                        return "三级分类";
                    }
                }
            },
            {field: 'level', title: '层级', minWidth: 100, align: "center"},
            {field: 'sortOrder', title: '排序', minWidth: 100, align: "center"},
            {field: 'description', title: '分类描述', align: 'center'},
            {
                field: 'categoryStatus', title: '状态', align: 'center', templet: function (d) {
                    if (d.categoryStatus == "0") {
                        return "活跃";
                    } else if (d.categoryStatus == "1") {
                        return "归档";
                    }else {
                        return "未知状态";
                    }
                }
            },
            {
                field: 'isVisible', title: '是否可见', align: 'center', templet: function (d) {
                    if (d.isVisible == "Y") {
                        return "是";
                    } else if (d.isVisible == "N") {
                        return "否";
                    } else {
                        return "未知";
                    }
                }
            },
            {field: 'path', title: '分类路径', minWidth: 100, align: "center"},
            /*{field: 'userAvatar', title: '用户头像', minWidth:100, align:"center",templet:function(d){
                    return "<img src='"+d.userAvatar+"' style='width: 30px;height: 30px'>";
            }},*/
            {field: 'keywords', title: '关键词', minWidth: 100, align: "center"},
            {field: 'creator', title: '创建人', minWidth: 100, align: "center"},
            {field: 'modifier', title: '修改人', minWidth: 100, align: "center"},
            {
                field: 'createTime', title: '创建时间', minWidth: 100, align: "center", templet: function (d) {
                    return showTime(d.createTime);
                }
            },
            {
                field: 'updateTime', title: '修改时间', minWidth: 100, align: "center", templet: function (d) {
                    return showTime(d.updateTime);
                }
            },
            {title: '操作', minWidth: 200, templet: '#listBar', fixed: "right", align: "center", toolBar: '#listBar'}
        ]]
    });
    $(".search_category_btn").click(function () {
        var categoriesName = $("#search_value").val();
        console.log(categoriesName)
        renderCategoriesGrid();
        table.reload("listTable", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                categoriesName: $("#search_value").val()
            }
        })
    })

    $(".add_btn").click(function () {
        edit();
    })
    // 添加/修改
    function edit(edit) {
        let title = "添加分类";
        if (edit != null) {
            title = "修改分类";
        }
        const index = layui.layer.open({
            title: title,
            type: 2,
            content: "/silos/cms/book/category/edit.html",
            scrollbar: false,
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (edit) {
                    body.find(".uid").val(BigInt(edit.id).toString());
                    body.find(".userName").val(edit.userName);  //用户名
                    body.find(".loginName").val(edit.loginName);  //登录名
                    body.find(".userMobilePhone").val(edit.userMobilePhone);
                    body.find(".userNickName").val(edit.userNickName);
                    body.find(".userAddress").val(edit.userAddress);
                    body.find(".userEmail").val(edit.userEmail);  //邮箱
                    body.find(".userSex input[value=" + edit.userSex + "]").prop("checked", "checked");  //性别
                    body.find(".allowedNetworkType").val(edit.allowedNetworkType);
                    body.find(".userType").val(edit.userType);  //会员等级
                    body.find(".userStatus").val(edit.userStatus);    //用户状态
                    body.find(".userDescription").text(edit.userDescription);    //用户简介
                    body.find(".remark").text(edit.remark);
                    form.render();
                }
                setTimeout(function () {
                    layui.layer.tips('点击此处返回分类列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            }
        });
        layui.layer.full(index);
        window.sessionStorage.setItem("index", index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }
    //时间转换函数
    function showTime(tempDate) {
        var d = new Date(tempDate);
        var year = d.getFullYear();
        var month = d.getMonth();
        month++;
        var day = d.getDate();
        var hours = d.getHours();

        var minutes = d.getMinutes();
        var seconds = d.getSeconds();
        month = month < 10 ? "0" + month : month;
        day = day < 10 ? "0" + day : day;
        hours = hours < 10 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;


        var time = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        return time;
    }
    // 生成分类卡片（网格视图）
    function renderCategoriesGrid() {
        const categoriesGrid = document.getElementById('categoriesGrid');
        $.ajax({
            url: "/cms/book/categories/queryPage",
            type: "POST",
            dataType: "json",
            async: false,
            contentType: 'application/json;charset=UTF-8',
            data: JSON.stringify({
                pageNo:1,
                pageRows:100,
                categoriesName:$("#search_value").val()
            }),
            success: function (res) {
                const data = res.data.dataList;
                if (data.length === 0) {
                    categoriesGrid.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-tags"></i>
                        <h3>暂无分类</h3>
                        <p>点击"添加分类"按钮开始创建分类</p>
                    </div>
                `;
                    return;
                }

                categoriesGrid.innerHTML = data.map(category => `
                <div class="category-card" data-id="${category.id}">
                    <div class="category-header">
                        <div class="category-icon" style="background-color: ${category.categoryColor}">
                            <i class="${category.categoryIcon}"></i>
                        </div>
                        <div class="category-actions">
                            <div class="action-btn edit-btn" data-id="${category.id}">
                                <i class="fas fa-edit"></i>
                            </div>
                            <div class="action-btn delete-btn" data-id="${category.id}">
                                <i class="fas fa-trash"></i>
                            </div>
                        </div>
                    </div>
                    <div class="category-info">
                        <div class="category-code">${category.categoryCode}</div>
                        <h3 class="category-name">${category.categoryName}</h3>
                        <p class="category-description">${category.description}</p>
                        <div class="category-meta">
                            <span>${category.isVisible ? '可见' : '隐藏'}</span>
                        </div>
                    </div>
                </div>
            `).join('');
            },
            error: function (e) {
                console.log(e);
            }
        })
    }
    // 自定义绑定事件方法
    function bind_event(dom, fn, type, child,) {
        if (typeof dom == 'object' && dom != 'undefined') {
            type = type == null ? "click" : type;
            if (child != "" && child != 'object') {
                return dom.on(type, child, fn);
            } else {
                return dom.on(type, fn);
            }
        }
    };
    // 刷新页面
    bind_event($(".search_refresh"), function () {
        window.location.reload();
    });
    $(function () {
        renderCategoriesGrid();
        //切换tab页的显示
        $(document).on('click', '.view-btn', function (e) {
            // 视图切换功能
            const viewButtons = document.querySelectorAll('.view-btn');
            viewButtons.forEach(btn => {
                btn.addEventListener('click', function() {
                    const viewType = this.getAttribute('data-view');

                    viewButtons.forEach(b => b.classList.remove('active'));
                    this.classList.add('active');

                    if (viewType === 'grid') {
                        document.getElementById('categoriesGrid').classList.add('active');
                        document.getElementById('categoriesTable').classList.remove('active');
                    } else {
                        document.getElementById('categoriesGrid').classList.remove('active');
                        document.getElementById('categoriesTable').classList.add('active');
                    }
                });
            });
        })
    });
})