<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('常见错误监测列表')" />
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="formId">
                <input type="hidden" name="sitetag" value="site"/>
                <div class="select-list">
                    <ul>
                        <li>
                            <label>站点名称：</label>
                            <select class="type" name="sitename" style="width: 200px;">
                                <option value="">全部站点</option>
                                <option th:each="site : ${sites}" th:value="${site.sitename}" th:text="${site.sitename}"></option>
                            </select>
                        </li>
                        <li>
                            <label>所在页：</label>
                            <input type="text" name="page"/>
                        </li>
                        <li>
                            <label>错误词：</label>
                            <input type="text" name="wrongWord"/>
                        </li>
                        <li>
                            <label>正确词：</label>
                            <input type="text" name="correctWord"/>
                        </li>



                        <li>
                            <label>错误类型：</label>
                            <div class="error-type-dropdown dropdown-container">
                                <button type="button" class="dropdown-toggle form-control" id="errorTypeDropdown">
                                    <span id="selectedErrorType"  style="font-size: 13px">所有</span>
                                    <span class="caret"></span>
                                </button>
                                <input type="hidden" name="errorType" id="errorTypeValue" value="">
                                <ul class="dropdown-menu error-type-menu" id="errorTypeMenu" style="display:none; width: 360px;">
                                    <div class="error-type-column" id="errorTypeMain"></div>
                                    <div class="error-type-column" id="errorTypeSub"></div>
                                </ul>
                            </div>
                        </li>

                        <style>
                            /* 仅限错误类型联动选择器样式，避免影响其他 */
                            .error-type-dropdown {
                                position: relative;
                                display: inline-block;
                                width: 230px;
                            }
                            .error-type-dropdown .dropdown-toggle {
                                text-align: left;
                                /*padding: 6px 12px;*/
                                width: 100%;
                                height: 30px;
                                border: 1px solid #ccc;
                                border-radius: 4px;
                                background: #fff;
                                cursor: pointer;
                                position: relative;
                            }

                            .error-type-dropdown .dropdown-toggle .caret {
                                position: absolute;
                                right: 10px;
                                top: 50%;
                                transform: translateY(-50%);
                            }
                            .error-type-dropdown .error-type-menu {
                                position: absolute;
                                top: 100%;
                                left: 0;
                                background: #fff;
                                border: 1px solid #ccc;
                                border-radius: 4px;
                                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                                width: 400px;
                                display: flex;
                                z-index: 1000;
                                max-height: 300px;
                                overflow: hidden;
                            }
                            .error-type-dropdown .error-type-column {
                                width: 50%;
                                overflow-y: auto;
                                border-right: 1px solid #eee;
                            }
                            .error-type-dropdown .error-type-column:last-child {
                                border-right: none;
                            }
                            .error-type-dropdown .cascader-item {
                                padding: 8px 12px;
                                cursor: pointer;
                            }
                            .error-type-dropdown .cascader-item:hover {
                                background-color: #f5f5f5;
                            }
                        </style>

                        <script th:inline="javascript">
                            /*<![CDATA[*/
                            var errorTypeDict = /*[[${@dict.getType('trs_error_type')}]]*/ [];
                            /*]]>*/
                        </script>

                        <script th:inline="javascript">
                            /*<![CDATA[*/
                            document.addEventListener('DOMContentLoaded', function () {
                                var cascaderData = {};
                                errorTypeDict.forEach(function(item) {
                                    if (!item.dictLabel || !item.dictValue) return;
                                    var parts = item.dictLabel.split("-");
                                    if(parts.length < 2) return;
                                    var main = parts[0];
                                    var subLabel = parts.slice(1).join("-");
                                    if (!cascaderData[main]) cascaderData[main] = [];
                                    cascaderData[main].push({ label: item.dictLabel, value: item.dictValue });
                                });

                                var $dropdown = document.getElementById('errorTypeDropdown');
                                var $menu = document.getElementById('errorTypeMenu');
                                var $main = document.getElementById('errorTypeMain');
                                var $sub = document.getElementById('errorTypeSub');
                                var $selected = document.getElementById('selectedErrorType');
                                var $hidden = document.getElementById('errorTypeValue');

                                // 填充主菜单
                                Object.keys(cascaderData).forEach(function(mainKey) {
                                    var div = document.createElement('div');
                                    div.className = 'cascader-item';
                                    div.textContent = mainKey;
                                    div.dataset.main = mainKey;
                                    $main.appendChild(div);

                                    div.addEventListener('mouseover', function () {
                                        $sub.innerHTML = '';
                                        cascaderData[this.dataset.main].forEach(function(subItem) {
                                            var subDiv = document.createElement('div');
                                            subDiv.className = 'cascader-item';
                                            subDiv.textContent = subItem.label;
                                            subDiv.dataset.value = subItem.value;
                                            $sub.appendChild(subDiv);

                                            subDiv.addEventListener('click', function(e) {
                                                e.stopPropagation();
                                                $selected.textContent = this.textContent;
                                                $hidden.value = this.dataset.value;
                                                $menu.style.display = 'none';
                                            });
                                        });
                                    });
                                });

                                $dropdown.addEventListener('click', function(e) {
                                    e.stopPropagation();
                                    $menu.style.display = ($menu.style.display === 'flex') ? 'none' : 'flex';
                                });

                                document.addEventListener('click', function() {
                                    $menu.style.display = 'none';
                                });

                                // URL回填
                                var urlParams = new URLSearchParams(window.location.search);
                                var errorTypeVal = urlParams.get('errorType');
                                if (errorTypeVal) {
                                    var found = false;
                                    errorTypeDict.forEach(function(item){
                                        if(item.dictValue === errorTypeVal){
                                            $selected.textContent = item.dictLabel;
                                            $hidden.value = item.dictValue;
                                            found = true;
                                        }
                                    });
                                    if (!found) {
                                        $selected.textContent = '所有';
                                        $hidden.value = '';
                                    }
                                } else {
                                    $selected.textContent = '所有';
                                    $hidden.value = '';
                                }

                                // 重置按钮处理
                                document.querySelector('.btn-reset').addEventListener('click', function() {
                                    $selected.textContent = '所有';
                                    $hidden.value = '';
                                });
                            });
                            /*]]>*/
                        </script>






                        <li>
                            <label>错误级别：</label>
                            <select name="errorGrade" th:with="type=${@dict.getType('trs_error_grade')}">
                                <option value="">所有</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                            </select>
                        </li>
                        <li class="select-time">
                            <label>时间：</label>
                            <input type="text" class="time-input" id="startTime" placeholder="开始时间" name="params[beginTime]"/>
                            <span>-</span>
                            <input type="text" class="time-input" id="endTime" placeholder="结束时间" name="params[endTime]"/>
                        </li>
                        <li>
                            <label>状态：</label>
                            <select name="status" th:with="type=${@dict.getType('trs_oper_type')}">
                                <option value="">所有</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                            </select>
                        </li>
                        <li>
                            <a class="btn btn-primary btn-rounded btn-sm btn-search" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                            <a class="btn btn-warning btn-rounded btn-sm btn-reset" onclick="$.form.reset()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
                        </li>
                    </ul>
                </div>
            </form>
        </div>

        <div class="col-sm-12 search-collapse">
            <div class="dashboard-stat">
                <!-- 第一组 - 蓝色背景 -->
                <div class="stat-group group-blue">
                    <div class="stat-item">
                        <div class="stat-number" id="errorWordCount">0</div>
                        <div class="stat-title">常见错误</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="processedCount">0</div>
                        <div class="stat-title">已处理数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="noNeedProcessCount">0</div>
                        <div class="stat-title">不必处理数</div>
                    </div>
                </div>

                <!-- 第二组 - 绿色背景 -->
                <div class="stat-group group-green">
                    <div class="stat-item">
                        <div class="stat-number" id="errorWordCount2">0</div>
                        <div class="stat-title">严重表述错误</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="processedCount2">0</div>
                        <div class="stat-title">已处理数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="noNeedProcessCount2">0</div>
                        <div class="stat-title">不必处理数</div>
                    </div>
                </div>

                <!-- 第三组 - 橙色背景 -->
                <div class="stat-group group-orange">
                    <div class="stat-item">
                        <div class="stat-number" id="errorWordCount3">0</div>
                        <div class="stat-title">一般性错误</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="processedCount3">0</div>
                        <div class="stat-title">已处理数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="noNeedProcessCount3">0</div>
                        <div class="stat-title">不必处理数</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="btn-group-sm" id="toolbar" role="group">
            <!--<a class="btn btn-success" onclick="$.operate.add()" shiro:hasPermission="project:sensitiveresult:add">
                <i class="fa fa-plus"></i> 添加
            </a>
            <a class="btn btn-primary single disabled" onclick="$.operate.edit()" shiro:hasPermission="project:sensitiveresult:edit">
                <i class="fa fa-edit"></i> 修改
            </a>-->
            <a class="btn btn-success" onclick="biaoji()" shiro:hasPermission="project:sensitiveresult:edit">
                <i class="fa fa-edit"></i> 批量标记
            </a>
            <a class="btn btn-danger" onclick="review()" shiro:hasPermission="project:sensitiveresult:edit">
                <i class="fa fa-refresh"></i> 复核
            </a>
            <a class="btn btn-danger multiple disabled" onclick="$.operate.removeAll()" shiro:hasPermission="project:sensitiveresult:remove">
                <i class="fa fa-remove"></i> 删除
            </a>
            <a class="btn btn-warning" onclick="$.table.exportExcel()" shiro:hasPermission="project:sensitiveresult:export">
                <i class="fa fa-download"></i> 导出
            </a>
        </div>
        <div class="col-sm-12 select-table table-striped">
            <table id="bootstrap-table"></table>
        </div>
    </div>
</div>
<th:block th:include="include :: footer" />
<style>
    /* 仪表盘统计容器 */
    .dashboard-stat {
        display: flex;
        justify-content: space-between;
        align-items: stretch; /* 使子元素高度一致 */
        background: #f8f9fa;
        border-radius: 8px;
        overflow: hidden; /* 确保圆角效果 */
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    /* 每组统计样式 */
    .stat-group {
        display: flex;
        flex: 1;
        justify-content: space-around;
        padding: 15px 0;
    }

    /* 不同组的背景颜色 */
    .group-blue {
        /*background: #e7f5ff; !* 浅蓝色 *!*/
        background: #deebfd; /* 浅蓝色 */
    }
    .group-green {
        /*background: #ebfbee; !* 浅绿色 *!*/
        background: #f2f2f2; /* 浅绿色 */
    }
    .group-orange {
        /*background: #fff4e6; !* 浅橙色 *!*/
        background: #e8eaff; /* 浅橙色 */
    }

    /* 统计项之间的分隔线 */
    .stat-group:not(:last-child) {
        border-right: 1px solid rgba(0,0,0,0.05);
    }

    /* 单个统计项 */
    .stat-item {
        text-align: center;
        padding: 0 15px;
        min-width: 80px;
    }

    .stat-number {
        font-size: 22px;
        font-weight: bold;
        line-height: 1.2;
    }

    /* 不同组的数字颜色 */
    .group-blue .stat-number {
        color: #228be6; /* 蓝色 */
    }
    .group-green .stat-number {
        color: #FF6B6B;

    }
    .group-orange .stat-number {
        color: #fd7e14; /* 橙色 */
    }

    .stat-title {
        font-size: 13px;
        color: #495057;
        margin-top: 6px;
    }
</style>
<!--     <style>
         /* 调整后的紧凑统计区域样式 */
         .dashboard-stat {
             display: flex;
             justify-content: space-around;
             /*margin-bottom: 15px;
             background: #fff;*/
             padding: 10px 15px;  /* 减少上下padding */
             border-radius: 4px;
             /*ox-shadow: 0 1px 3px rgba(0,0,0,0.1);*/
             height: 70px;  /* 固定高度 */
             align-items: center;  /* 垂直居中 */
         }
         .stat-item {
             text-align: center;
             padding: 0 15px;  /* 减少左右padding */
         }
         .stat-number {
             font-size: 20px;  /* 缩小字体 */
             font-weight: bold;
             color: #1ab394;
             line-height: 1.2;  /* 调整行高 */
         }
         .stat-title {
             font-size: 13px;  /* 缩小字体 */
             color: #676a6c;
             margin-top: 3px;  /* 减少间距 */
         }
     </style>-->

<script th:inline="javascript">
    var editFlag = [[${@permission.hasPermi('project:sensitiveresult:edit')}]];
    var removeFlag = [[${@permission.hasPermi('project:sensitiveresult:remove')}]];
    var errorTypeDatas = [[${@dict.getType('trs_error_type')}]];
    var errorGradeDatas = [[${@dict.getType('trs_error_grade')}]];
    var statusDatas = [[${@dict.getType('trs_oper_type')}]];
    var prefix = ctx + "project/sensitiveresult";
    var prefixscan = ctx + "project/siteconfig";


    $(function() {
        var options = {
            url: prefix + "/list",
            createUrl: prefix + "/add",
            updateUrl: prefix + "/edit/{id}",
            removeUrl: prefix + "/remove",
            exportUrl: prefix + "/export",
            modalName: "常见错误监测",
            columns: [{
                checkbox: true
            },
                {
                    field: 'id',
                    title: '主键',
                    visible: false
                },
                {
                    field: 'sitename',
                    title: '站点名称'
                },
                {
                    field: 'page',
                    title: '所在页',
                    formatter: function(value, row, index) {
                        // 假设 row 对象中有 title 字段存储页面标题
                        var title = row.title || '无标题';  // 如果没有标题，显示"无标题"
                        var url = value;  // value 是页面URL

                        // 在新标签页中打开链接，显示标题但链接到URL
                        return '<a href="' + url + '" target="_blank" title="' + url + '">' + title + '</a>';
                    }
                },
                {
                    field: 'wrongWord',
                    title: '错误词',
                    width: '100px',
                },
                {
                    field: 'correctWord',
                    title: '正确词',
                    width: '100px',
                },
                {
                    field: 'errorType',
                    title: '错误类型',
                    formatter: function(value, row, index) {
                        return $.table.selectDictLabel(errorTypeDatas, value);
                    }
                },
                {
                    field: 'errorGrade',
                    title: '错误级别',
                    width: '100px',
                    formatter: function(value, row, index) {
                        return $.table.selectDictLabel(errorGradeDatas, value);
                    }
                },
                {
                    field: 'context',
                    title: '上下文',
                    escape: true  // 关键设置，禁用HTML转义
                },
                {
                    field: 'time',
                    width: '100px',
                    title: '发布时间'
                },
                {
                    field: 'scantime',
                    width: '100px',
                    title: '审核时间'
                },
                {
                    field: 'status',
                    title: '状态',
                    width: '70px',
                    formatter: function(value, row, index) {
                        return $.table.selectDictLabel(statusDatas, value);
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    width: '180px',
                    formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-warning btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="mark(\'' + row.id + '\')"><i class="fa fa-anchor"></i>定位</a> ');
                        actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="biaoji(\'' + row.id + '\')"><i class="fa fa-edit"></i>标记</a> ');
                        actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>');
                        return actions.join('');
                    }
                }]
        };
        $.table.init(options);
    });

    // 在表格加载和搜索时刷新统计
    $(function() {
        // 从URL中解析参数并填充到表单
        var urlParams = new URLSearchParams(window.location.search);

        var hasParams = false;
        if (urlParams.has('wrongWord')) {
            $('input[name="wrongWord"]').val(urlParams.get('wrongWord'));
            hasParams = true;
        }
        if (urlParams.has('sitename')) {
            $('select[name="sitename"]').val(urlParams.get('sitename'));
            hasParams = true;
        }
        if (urlParams.has('params[beginTime]')) {
            $('#startTime').val(urlParams.get('params[beginTime]'));
            hasParams = true;
        }
        if (urlParams.has('params[endTime]')) {
            $('#endTime').val(urlParams.get('params[endTime]'));
            hasParams = true;
        }

        // 如果URL有参数，自动触发搜索（无需等待手动点击）
        if (hasParams) {
            $.table.search();
            //loadStatistics(); // 同时刷新统计
        }

        // 初始化时加载
        loadStatistics();
        // 搜索按钮点击时重新加载
        $('.btn-search').click(function() {
            // 先执行原有搜索逻辑
            $.table.search();
            // 然后刷新统计
            setTimeout(loadStatistics, 300); // 延迟确保搜索完成
        });

        // 重置按钮点击时重新加载
        $('.btn-reset').click(function() {
            // 先执行原有重置逻辑
            $.form.reset();
            // 然后刷新统计
            setTimeout(loadStatistics, 300); // 延迟确保重置完成
        });
    });

    // 加载统计数据
    function loadStatistics() {
        // 1. 扩展jQuery方法（如果尚未定义）
        if (typeof $.fn.serializeObject !== 'function') {
            $.fn.serializeObject = function() {
                var obj = {};
                var arr = this.serializeArray();
                $.each(arr, function() {
                    if (obj[this.name] !== undefined) {
                        if (!obj[this.name].push) {
                            obj[this.name] = [obj[this.name]];
                        }
                        obj[this.name].push(this.value || '');
                    } else {
                        obj[this.name] = this.value || '';
                    }
                });
                return obj;
            };
        }

        // 2. 获取表单数据并处理特殊字段
        var formData = $('#formId').serializeObject();
        $.ajax({
            url: prefix + "/statistics",
            type: "GET",
            data: formData,  // 将表单数据作为查询参数
            success: function(res) {
                $('#errorWordCount').text(res.data.errorWordCount || 0);
                $('#processedCount').text(res.data.processedCount || 0);
                $('#noNeedProcessCount').text(res.data.noNeedProcessCount || 0);

                $('#errorWordCount2').text(res.data.errorWordCount2 || 0);
                $('#processedCount2').text(res.data.processedCount2 || 0);
                $('#noNeedProcessCount2').text(res.data.noNeedProcessCount2 || 0);

                $('#errorWordCount3').text(res.data.errorWordCount3 || 0);
                $('#processedCount3').text(res.data.processedCount3 || 0);
                $('#noNeedProcessCount3').text(res.data.noNeedProcessCount3 || 0);
            }
        });
    }

    function review() {
        $.modal.confirm("是否执行复核操作？", function() {
            var data = { "id": 1, "type":"2" };
            $.operate.saveModal(prefixscan + "/doscan", data, null);
        })
        $('#bootstrap-table').bootstrapTable('refresh');

    }

    function mark(id) {
        window.open('sensitiveresult/mark/'+id, '_blank');
    }

    function biaoji(id) {
        // 判断是单个标记还是批量标记
        var rows;
        if (id) {
            // 单个标记，构造一个只包含当前行的数组
            rows = [{id: id}];
        } else {
            // 批量标记，获取选中的行
            rows = $('#bootstrap-table').bootstrapTable('getSelections');
            if (rows.length == 0) {
                $.modal.alertWarning("请至少选择一条记录");
                return;
            }
        }

        // 准备单选按钮HTML
        var radioOptions = statusDatas.map(item => `
                <label style="margin-left: ${item.dictValue === '1' ? '0' : '20px'};">
                    <input type="radio" name="errorType" value="${item.dictValue}" ${item.dictValue === '1' ? 'checked' : ''}>
                    ${item.dictLabel}
                </label>
            `).join('');

        var radioHtml = `
            <div class="form-horizontal" style="padding: 20px;">
                <div class="form-group">
                    <div class="col-sm-10">
                        <div class="radio-box">${radioOptions}</div>
                    </div>
                </div>
            </div>
            `;

        layer.open({
            type: 1,
            title: '请选择状态',
            content: radioHtml,
            area: ['600px', '200px'],
            btn: ['确定', '取消'],
            yes: function(index, layero) {
                var selectedValue = $('input[name="errorType"]:checked').val();
                if (selectedValue) {
                    // 获取选中行的ID数组
                    var ids = rows.map(row => row.id);

                    $.ajax({
                        url: prefix + "/biaoji",
                        type: "POST",
                        data: {
                            ids: ids.join(","),
                            status: selectedValue
                        },
                        success: function(res) {
                            layer.msg("标记成功");
                            $('#bootstrap-table').bootstrapTable('refresh');
                        },
                        error: function() {
                            layer.msg("操作失败");
                        }
                    });
                }
                layer.close(index);
            },
            btn2: function(index) {
                layer.close(index);
            }
        });

    }

    $(function() {
        // 监听表单的 Enter 键按下事件
        $('#formId').on('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault(); // 阻止默认提交行为
                $.table.search();   // 触发搜索
                loadStatistics();   // 刷新统计（可选）
            }
        });
    });
</script>
</body>
</html>