<%@ Page Language="C#" AutoEventWireup="true" CodeFile="layoutDesign.aspx.cs" Inherits="Manage_layoutDesign" %><!DOCTYPE html>
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>布局设计</title>
    <style>
        * {
            box-sizing: border-box;
        }
        bo4dy {
            font-family: sans-serif;
            background: #f0f2f5;
            margin: 20px;
        }
        #app {
            /*max-width: 1200px;*/
            margin: 0 auto;
        }
        .toolbar-global {
            margin-bottom: 10px;
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        .toolbar-global button {
            padding: 6px 12px;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .toolbar-global button:hover {
            background: #2980b9;
        }
        .toolbar-global #resetBtn {
            background: #27ae60;
        }
        .toolbar-global #resetBtn:hover {
            background: #2ecc71;
        }

        /* 网格编辑器 */
        .grid-editor {
            border: 1px solid #2c3e50;
            border-radius: 6px;
            margin: 10px 0;
            padding: 8px;
            background: white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            position: relative;
        }

        /* 网格工具栏 */
        .grid-toolbar1 {
            display: flex;
            gap: 8px;
            margin-bottom: 8px;
            background: #ecf0f1;
            padding: 6px;
            border-radius: 4px;
            align-items: center;
        }
         .grid-toolbar {
             position: absolute;
            top: -23px;
            right: 4px;
            display: none;
             gap: 4px;
            z-index: 100;
        }
          .grid-editor:hover > .grid-toolbar {display:flex;}
        .grid-toolbar .add-row-btn {
            background: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 4px 12px;
            cursor: pointer;
        }
        .grid-toolbar .delete-grid-btn {
            background: #e74c3c;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 4px 12px;
            cursor: pointer;
            margin-left: auto;
        }

        /* 行容器 */
        .grid-rows {
            display: flex;
            flex-direction: column;
            gap: 0px;
        }

        /* 行 - 使用 grid 布局 */
        .grid-row {
            display: grid;
            gap: 6px;
            /*min-height: 120px;*/
            margin-bottom: 6px;
        }

        /* 单元格 */
        .grid-cell {
            position: relative;
            border: 1px dashed #7f8c8d;
            border-radius: 4px;
            padding: 6px;
            background: #fefefe;
            display: flex;
            flex-direction: column;
            transition: box-shadow 0.1s;
        }
        .grid-cell.selected {
            border: 1px solid #e67e22;
            box-shadow: 0 0 0 2px rgba(230, 126, 34, 0.2);
        }

        /* 按钮容器 (右上角四个按钮) - 只在单元格选中时显示 */
        .cell-buttons {
            position: absolute;
            top: 4px;
            right: 4px;
            display: none;
            gap: 4px;
            z-index: 10;
        }
        .grid-cell.selected > .cell-buttons {
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-end;
            /*max-width: 120px;*/
        }
        .cell-buttons button {
            padding: 2px 6px;
            font-size: 12px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            color: white;
        }
        .cell-buttons .delete-cell {
            background: #e74c3c;
        }
        .cell-buttons .delete-cell:hover {
            background: #c0392b;
        }
        .cell-buttons .add-col-cell {
            background: #f39c12;
        }
        .cell-buttons .add-col-cell:hover {
            background: #e67e22;
        }
        .cell-buttons .nest-cell {
            background: #2ecc71;
        }
        .cell-buttons .nest-cell:hover {
            background: #27ae60;
        }
        .cell-buttons .delete-row-cell {
            background: #e74c3c;
            opacity: 0.8;
        }
        .cell-buttons .delete-row-cell:hover {
            background: #c0392b;
            opacity: 1;
        }

        /* 单元格中部 - 绑定数据按钮区域 (无嵌套时显示) */
        .cell-center1 {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 10px 0;
        }
        .cell-center {

            display: flex;
            justify-content: left;
            align-items: center;
            height:20px;
        }
        .bind-data-btn {
            padding: 4px 12px;
            background: #9b59b6;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
        }
        .bind-data-btn:hover {
            background: #8e44ad;
        }

        /* 单元格内容区（用于嵌套网格） */
        .cell-content {
            flex: 1;
            min-height: 30px;
            /*border-top: 1px dashed #ccc; */
            margin-top: 5px;
            padding-top: 5px;
        }

        /* 嵌套网格的边框颜色变化 */
        .cell-content > .grid-editor {
            border-color: #e67e22;
            border:0;
            margin: 0;
            padding: 0;
            box-shadow:none;
        }

        /* 导出区域 */
        .export-panel {
            margin-top: 20px;
            padding: 10px;
            background: #fff;
            
            /*border-radius: 6px;border: 1px solid #ccc;*/
        }
        textarea {
            width: 100%;
            font-family: monospace;
            margin-top: 8px;
        }
    </style>
    <script src="../Scripts/init.js?ver=<%=Common.Version %>"></script>
    <script src="javascript/columns.js?ver=<%=Common.Version %>"></script>
<script>
    var select_btn=null;  
    function bindcontrols_callback(text,value)
    {
        select_btn.parentNode.setAttribute('data-text', value);
        var spans = select_btn.parentNode.getElementsByTagName("span");
        if (spans.length == 0) {
            select_btn.insertAdjacentHTML('beforebegin', '<span style="margin-right:8px;">' + text + '</span>');
        }
        else {
            spans[0].innerText = text;
        }
    };
    /**
     * 格式化HTML字符串（ES5实现）
     * @param {string} html - 原始HTML字符串
     * @param {number} indentSize - 缩进空格数，默认为2
     * @return {string} 格式化后的HTML
     */
    function formatHTML(html, indentSize) {
        indentSize = indentSize || 2;
        var indentChar = ' '; // 使用空格缩进
        var result = [];
        var level = 0;                     // 当前缩进级别
        var stack = [];                    // 标签栈，用于检查结束标签匹配
        var inRaw = false;                 // 是否在script/style等原始内容区域
        var rawTagName = '';               // 当前原始标签名，用于退出

        // 自闭合标签列表（HTML5 void elements + 常见自闭合）
        var selfClosingTags = {
            area: true, base: true, br: true, col: true, embed: true,
            hr: true, img: true, input: true, link: true, meta: true,
            param: true, source: true, track: true, wbr: true
        };

        // 需要内部原样保留的标签（不格式化内部内容）
        var rawTags = {
            script: true, style: true
        };

        // 辅助：生成当前缩进字符串
        function getIndent() {
            var indent = '';
            for (var i = 0; i < level * indentSize; i++) {
                indent += indentChar;
            }
            return indent;
        }

        // 辅助：提取标签名（不包含属性）
        function getTagName(tag) {
            // 去掉 < 和 >，以及可能的结束斜杠
            tag = tag.replace(/^<\/?|>$/g, '');
            // 取第一个空格前的部分作为标签名
            var parts = tag.split(/\s+/);
            return parts[0].toLowerCase();
        }

        // 辅助：判断标签类型
        function getTagType(tag) {
            if (tag.indexOf('<!--') === 0) return 'comment';
            if (tag.indexOf('<!') === 0) return 'doctype';  // <!DOCTYPE 等
            if (tag.indexOf('</') === 0) return 'close';
            if (tag.indexOf('<') === 0) {
                // 检查是否为自闭合（以/>结尾 或 属于自闭合标签列表）
                var tagName = getTagName(tag);
                if (selfClosingTags[tagName]) return 'selfclosing';
                if (tag.slice(-2) === '/>') return 'selfclosing';
                return 'open';
            }
            return 'text';
        }

        // 使用正则分割HTML为标签和文本交替的数组
        // 注意：此正则假设标签内不包含未转义的 >，简化处理
        var parts = html.split(/(<[^>]+>)/);

        for (var i = 0; i < parts.length; i++) {
            var part = parts[i];
            if (part === '') continue;

            // 如果是标签部分（匹配了正则）
            if (part.charAt(0) === '<' && part.charAt(part.length - 1) === '>') {
                var type = getTagType(part);

                // 注释或DOCTYPE：直接输出，不改变缩进
                if (type === 'comment' || type === 'doctype') {
                    result.push(getIndent() + part + '\n');
                    continue;
                }

                // 结束标签
                if (type === 'close') {
                    var tagName = getTagName(part);
                    // 检查栈顶是否匹配（简化，不强制检查）
                    if (stack.length > 0 && stack[stack.length - 1] === tagName) {
                        stack.pop();
                        level--;
                    }
                    // 如果当前正在raw区域并且结束标签正是raw标签，退出raw模式
                    if (inRaw && tagName === rawTagName) {
                        inRaw = false;
                        rawTagName = '';
                    }
                    result.push(getIndent() + part + '\n');
                    continue;
                }

                // 开始标签或自闭合标签
                if (type === 'open' || type === 'selfclosing') {
                    var tagName = getTagName(part);
                    // 如果是自闭合，直接输出，不入栈
                    if (type === 'selfclosing') {
                        result.push(getIndent() + part + '\n');
                    } else {
                        // 开始标签
                        result.push(getIndent() + part + '\n');
                        stack.push(tagName);
                        level++;
                        // 检查是否为raw标签（如script/style）
                        if (rawTags[tagName]) {
                            inRaw = true;
                            rawTagName = tagName;
                        }
                    }
                    continue;
                }
            } else {
                // 文本部分
                if (inRaw) {
                    // raw模式下，原样输出文本（不添加缩进，但保留原始内容）
                    result.push(part);
                } else {
                    // 普通文本：按换行分割，每行缩进，空行只输出换行
                    var lines = part.split('\n');
                    for (var j = 0; j < lines.length; j++) {
                        var line = lines[j];
                        // 如果当前行非空，则添加缩进；空行则直接输出换行
                        if (line.trim() !== '') {
                            result.push(getIndent() + line);
                        } else {
                            // 空行：只加换行（但需避免连续空行导致多余缩进，这里简单处理）
                            if (j > 0 || part.charAt(0) === '\n') {
                                // 如果前面已经有内容，保留空行
                                result.push('\n');
                            }
                        }
                        if (j < lines.length - 1) {
                            result.push('\n');
                        }
                    }
                    // 如果文本不以换行结尾，则添加一个换行以便后续标签另起一行
                    if (part.slice(-1) !== '\n' && lines.length > 0 && lines[lines.length - 1] !== '') {
                        result.push('\n');
                    }
                }
            }
        }

        // 去除末尾多余的换行，并合并结果
        var output = result.join('');
        // 去除最后的连续换行，保留一个
        output = output.replace(/\n+$/, '\n');
        return output;
    }
</script>
</head>
<body>
<div class="toolbar-global">
        <button id="resetBtn">重置</button>
        <button id="mergeBtn">合并(Ctrl+多选)</button>
        <button id="unmergeBtn">取消合并</button>
    <span style="color:#FF8100;font-size:14px;">
    提示：选中行，小键盘的↑↓←→键改变行、列的位置。</span>
    </div>
    <div id="app">
        <!-- 根网格将通过 JS 动态创建 -->
        <%=(obj=="HtmlBody" ? viewObj.HtmlBodyDesign : viewObj.mHtmlBodyDesign) %>
    </div>

    <div class="export-panel">
        <button id="exportBtn" style="background: #3498db;border-radius: 4px;border: none;color: white;padding: 6px 12px;">确认更新</button>
        <textarea id="exportOutput" rows="10" readonly placeholder="生成的 HTML 会显示在这里..." style="display:none;"></textarea>
    </div>

 <script>
     (function () {
         "use strict";

         // 当前选中的单元格数组（支持多选）
         var selectedCells = [];

         // ---------- 辅助函数 ----------
         // 获取单元格的跨列数（默认1）
         function getCellSpan(cell) {
             var span = cell.getAttribute('data-col-span');
             if (span) return parseInt(span, 10);
             // 尝试从计算样式中读取
             var computed = window.getComputedStyle(cell).gridColumn;
             if (computed && computed.indexOf('span') !== -1) {
                 var match = computed.match(/span\s+(\d+)/);
                 if (match) return parseInt(match[1], 10);
             }
             return 1;
         }

         // 计算行内所有单元格的总跨列数（即轨道数）
         function calculateTotalSpan(row) {
             var cells = row.children;
             var total = 0;
             for (var i = 0; i < cells.length; i++) {
                 total += getCellSpan(cells[i]);
             }
             return total;
         }

         // 更新行的 grid-template-columns 为总轨道数
         function updateRowGridTemplate(row) {
             var totalSpan = calculateTotalSpan(row);
             //row.style.gridTemplateColumns = 'repeat(' + totalSpan + ', 1fr)';
             var _cols="";
             for(var i=0;i<totalSpan;i++)
             {
                 if(i>0){ _cols+=" ";}
                 _cols+="1fr";
             }
             row.style.gridTemplateColumns =_cols;
         }

         // 更新单元格的绑定按钮显示状态（根据内容区是否有子节点）
         function updateCellBindButton(cell) {
             var centerDiv = cell.querySelector('.cell-center');
             var contentDiv = cell.querySelector('.cell-content');
             if (centerDiv && contentDiv) {
                 if (contentDiv.children.length === 0) {
                     //centerDiv.style.display = ''; // 显示
                 } else {
                     //centerDiv.style.display = 'none'; // 隐藏
                 }
             }
         }

         // 清除所有单元格的选中状态
         function clearSelected() {
             for (var i = 0; i < selectedCells.length; i++) {
                 if (selectedCells[i]) {
                     selectedCells[i].classList.remove('selected');
                 }
             }
             selectedCells = [];
         }

         // 判断两个单元格是否在同一行且连续（索引连续）
         function areCellsConsecutive(cells) {
             if (cells.length < 2) return false;
             var row = cells[0].parentNode;
             // 检查是否都在同一行
             for (var i = 1; i < cells.length; i++) {
                 if (cells[i].parentNode !== row) return false;
             }
             // 获取所有子节点（单元格）
             var children = row.children;
             var indices = [];
             for (var j = 0; j < cells.length; j++) {
                 var idx = -1;
                 for (var k = 0; k < children.length; k++) {
                     if (children[k] === cells[j]) {
                         idx = k;
                         break;
                     }
                 }
                 if (idx === -1) return false;
                 indices.push(idx);
             }
             indices.sort(function (a, b) { return a - b; });
             // 检查是否连续
             for (var m = 1; m < indices.length; m++) {
                 if (indices[m] !== indices[m - 1] + 1) return false;
             }
             return true;
         }

         // 删除单元格
         function deleteCell(cell) {
             var row = cell.parentNode;            // .grid-row
             var rowsContainer = row.parentNode;   // .grid-rows
             var grid = rowsContainer.parentNode;  // .grid-editor


             if (rowsContainer.children.length == 1 && row.children.length == 1) {
                 deleteRow(row);
                 return;
             }


             // 从行中移除该单元格
             row.removeChild(cell);

             // 获取行中剩余的单元格
             var remainingCells = row.children.length;
             if (remainingCells === 0) {
                 // 行已空，删除整行
                 rowsContainer.removeChild(row);
             } else {
                 // 更新行的列数（基于总跨度）
                 updateRowGridTemplate(row);
             }
         }

         // 删除当前行
         function deleteRow(row) {
             var rowsContainer = row.parentNode;   // .grid-rows
             if (rowsContainer.children.length == 1) {
                 row = row.parentNode.parentNode;
                 rowsContainer = row.parentNode;
                 rowsContainer.removeChild(row);
                 return;
             }
             if (rowsContainer) {
                 rowsContainer.removeChild(row);
             }
         }

         // 在当前单元格右侧添加一列
         function addColumnAfterCell(cell) {
             var row = cell.parentNode;            // .grid-row
             var cells = row.children;
             var index = -1;
             // 找到当前单元格在行中的索引
             for (var i = 0; i < cells.length; i++) {
                 if (cells[i] === cell) {
                     index = i;
                     break;
                 }
             }
             if (index === -1) return;

             // 创建新单元格
             var newCell = createCell();
             // 插入到当前单元格之后
             if (index + 1 < cells.length) {
                 row.insertBefore(newCell, cells[index + 1]);
             } else {
                 row.appendChild(newCell);
             }

             // 更新行的列数（基于总跨度）
             updateRowGridTemplate(row);
         }

         // 合并选中的连续单元格
         function mergeSelectedCells() {
             if (selectedCells.length < 2) {
                 alert('请按住 Ctrl 键选择至少两个连续单元格');
                 return;
             }
             if (!areCellsConsecutive(selectedCells)) {
                 alert('选中的单元格必须位于同一行且连续');
                 return;
             }

             var firstCell = selectedCells[0];
             var row = firstCell.parentNode;

             // 计算所有选中单元格的总跨度
             var totalSpan = 0;
             for (var i = 0; i < selectedCells.length; i++) {
                 totalSpan += getCellSpan(selectedCells[i]);
             }

             // 检查被合并的单元格（除第一个外）是否有嵌套网格
             for (var i = 1; i < selectedCells.length; i++) {
                 var contentDiv = selectedCells[i].querySelector('.cell-content');
                 if (contentDiv && contentDiv.children.length > 0) {
                     if (!confirm('选中的单元格含有嵌套网格，合并将丢弃这些网格。确定继续？')) {
                         return;
                     }
                     break;
                 }
             }

             // 删除除第一个外的所有选中单元格（从后往前删避免索引变化）
             var cellsToRemove = [];
             for (var j = 1; j < selectedCells.length; j++) {
                 cellsToRemove.push(selectedCells[j]);
             }
             for (var k = cellsToRemove.length - 1; k >= 0; k--) {
                 row.removeChild(cellsToRemove[k]);
             }

             // 设置第一个单元格的 grid-column 跨度
             firstCell.style.gridColumn = 'span ' + totalSpan;
             firstCell.setAttribute('data-col-span', totalSpan);

             // 更新行的 grid-template-columns 基于所有单元格的总跨度
             updateRowGridTemplate(row);

             // 清除选中状态，并选中合并后的单元格
             clearSelected();
             firstCell.classList.add('selected');
             selectedCells = [firstCell];
         }

         // 取消合并选中的单元格
         function unmergeSelectedCell() {
             if (selectedCells.length !== 1) {
                 alert('请选中一个合并的单元格');
                 return;
             }
             var cell = selectedCells[0];
             var span = getCellSpan(cell);
             if (span <= 1) {
                 alert('当前单元格不是合并单元格或无法取消合并');
                 return;
             }

             var row = cell.parentNode;
             var index = -1;
             var cells = row.children;
             for (var i = 0; i < cells.length; i++) {
                 if (cells[i] === cell) {
                     index = i;
                     break;
                 }
             }
             if (index === -1) return;

             // 保存原单元格的内容（嵌套网格）
             var contentDiv = cell.querySelector('.cell-content');
             var contentHTML = '';
             if (contentDiv) {
                 contentHTML = contentDiv.innerHTML; // 保留内部HTML
             }

             // 删除原单元格
             row.removeChild(cell);

             // 创建 span 个新单元格
             var newCells = [];
             for (var n = 0; n < span; n++) {
                 var newCell = createCell();
                 if (n === 0 && contentHTML) {
                     // 第一个单元格恢复原来的内容（包括嵌套）
                     var newContent = newCell.querySelector('.cell-content');
                     if (newContent) {
                         newContent.innerHTML = contentHTML;
                     }
                     // 更新绑定按钮状态
                     updateCellBindButton(newCell);
                 }
                 newCells.push(newCell);
             }

             // 将新单元格插入到原位置
             for (var p = 0; p < newCells.length; p++) {
                 if (index + p < row.children.length) {
                     row.insertBefore(newCells[p], row.children[index + p]);
                 } else {
                     row.appendChild(newCells[p]);
                 }
             }

             // 更新行的 grid-template-columns 基于所有单元格的总跨度
             updateRowGridTemplate(row);

             // 清除选中状态，选中第一个新单元格
             clearSelected();
             newCells[0].classList.add('selected');
             selectedCells = [newCells[0]];
         }

         // 创建一个新的单元格 (包含四个按钮、绑定数据按钮、内容区)
         function createCell() {
             var cell = document.createElement('div');
             cell.className = 'grid-cell';

             cell.style.display = 'flex';//
             cell.style.flexDirection = 'column';//

             // 右上角按钮容器（四个按钮）
             var btnContainer = document.createElement('div');
             btnContainer.className = 'cell-buttons';

             var deleteBtn = document.createElement('button');
             deleteBtn.className = 'delete-cell';
             deleteBtn.textContent = '删列';

             var addColBtn = document.createElement('button');
             addColBtn.className = 'add-col-cell';
             addColBtn.textContent = '加列';

             var nestBtn = document.createElement('button');
             nestBtn.className = 'nest-cell';
             nestBtn.textContent = '嵌套';

             var deleteRowBtn = document.createElement('button');
             deleteRowBtn.className = 'delete-row-cell';
             deleteRowBtn.textContent = '删行';

             btnContainer.appendChild(deleteBtn);
             btnContainer.appendChild(addColBtn);
             btnContainer.appendChild(nestBtn);
             btnContainer.appendChild(deleteRowBtn);

             // 中部绑定数据按钮
             var centerDiv = document.createElement('div');
             centerDiv.className = 'cell-center';
             centerDiv.setAttribute('data-text', '');
             var bindBtn = document.createElement('button');
             bindBtn.className = 'bind-data-btn';
             bindBtn.textContent = '绑定数据';
             centerDiv.appendChild(bindBtn);

             // 内容区（用于嵌套）
             var content = document.createElement('div');
             content.className = 'cell-content';

             cell.appendChild(btnContainer);
             cell.appendChild(centerDiv);
             cell.appendChild(content);

             return cell;
         }

         // 向指定网格添加一行 (列数 cols)
         function addRowToGrid(grid, cols) {
             if (cols < 1) cols = 1;

             // 创建行元素
             var row = document.createElement('div');
             row.className = 'grid-row';
             row.style.display = 'grid';
             row.style.gap="10px";
             row.style.marginBottom="10px";
             //row.style.gridTemplateColumns = 'repeat(' + cols + ', 1fr)';
             var _cols="";
             for(var i=0;i<cols;i++)
             {
                 if(i>0){ _cols+=" ";}
                 _cols+="1fr";
             }
             row.style.gridTemplateColumns =_cols;
            

             // 创建单元格
             for (var i = 0; i < cols; i++) {
                 var cell = createCell();
                 row.appendChild(cell);
             }

             // 将行添加到网格的行容器中
             var rowsContainer = grid.querySelector('.grid-rows');
             rowsContainer.appendChild(row);
         }

         // 检查并更新父单元格的绑定数据按钮显示状态
         function updateParentCellBindButton(cellContent) {
             var parentCell = cellContent.closest('.grid-cell');
             if (!parentCell) return;
             updateCellBindButton(parentCell);
         }
         function addGridEvent(grid)
         {
             grid.addEventListener('click', function (e) {
                 var target = e.target;

                 // 添加行按钮
                 if (target.classList.contains('add-row-btn')) {
                     var cols = 2;//prompt('请输入新行的列数:', '2');
                     if (cols === null) return;
                     cols = parseInt(cols, 10);
                     if (isNaN(cols) || cols < 1) {
                         alert('列数必须为大于0的数字');
                         return;
                     }
                     var currentGrid = target.closest('.grid-editor');
                     addRowToGrid(currentGrid, cols);
                     e.stopPropagation();
                 }
                     // 删除网格按钮
                 else if (target.classList.contains('delete-grid-btn')) {
                     if (confirm('确定删除该网格及其所有子网格？')) {
                         var gridToDelete = target.closest('.grid-editor');
                         if (gridToDelete) {
                             var parentCell = gridToDelete.closest('.grid-cell');
                             gridToDelete.parentNode.removeChild(gridToDelete);
                             // 如果删除的是子网格，更新父单元格的绑定按钮
                             if (parentCell) {
                                 var contentDiv = parentCell.querySelector('.cell-content');
                                 updateParentCellBindButton(contentDiv);
                             }
                         }
                     }
                     e.stopPropagation();
                 }
                     // 删除单元格按钮（删列）
                 else if (target.classList.contains('delete-cell')) {
                     var cell = target.closest('.grid-cell');
                     if (cell) {
                         deleteCell(cell);
                         // 清除选中状态（因为单元格可能被删了）
                         clearSelected();
                     }
                     e.stopPropagation();
                 }
                     // 添加列按钮
                 else if (target.classList.contains('add-col-cell')) {
                     var cell = target.closest('.grid-cell');
                     if (cell) {
                         addColumnAfterCell(cell);
                     }
                     e.stopPropagation();
                 }
                     // 嵌套按钮
                 else if (target.classList.contains('nest-cell')) {
                     var cell = target.closest('.grid-cell');
                     if (cell) {
                         var content = cell.querySelector('.cell-content');
                         if (content) {
                             if (content.children.length > 0) {
                                 alert('该单元格已有嵌套网格，请先删除现有网格');
                                 return;
                             }
                             // 在内容区创建子网格
                             createGrid(content);
                             // 隐藏绑定数据按钮
                             var centerDiv = cell.querySelector('.cell-center');
                             if (centerDiv) {
                                 //centerDiv.style.display = 'none';
                             }
                         }
                     }
                     e.stopPropagation();
                 }
                     // 删除行按钮
                 else if (target.classList.contains('delete-row-cell')) {
                     var cell = target.closest('.grid-cell');
                     if (cell) {
                         var row = cell.parentNode; // .grid-row
                         deleteRow(row);
                         // 清除选中状态
                         clearSelected();
                     }
                     e.stopPropagation();
                 }
                     // 绑定数据按钮
                 else if (target.classList.contains('bind-data-btn')) {
                     select_btn = target;
                     bindControls();
                     //alert('绑定数据功能 (可扩展)');
                     //target.insertAdjacentHTML('beforebegin', '<div>前一个兄弟</div>');
                     //target.insertAdjacentHTML('afterbegin', '<div>第一个子元素</div>');
                     //target.insertAdjacentHTML('beforeend', '<div>最后一个子元素</div>');
                     //target.insertAdjacentHTML('afterend', '<div>后一个兄弟</div>');

                     //target.parentNode.setAttribute('data-text', '{report:a0af6a0d-cdc8-4f7a-b036-08fab0ef59ff}');
                     //target.insertAdjacentHTML('beforebegin', '<span style="margin-right:8px;">图表:a0af6a0d-cdc8-4f7a-b036-08fab0ef59ff</span>');

                     e.stopPropagation();
                 }
             });
         };
         // ---------- 创建新网格 ----------
         function createGrid(parent) {
             // 创建网格根元素
             var grid = document.createElement('div');
             grid.className = 'grid-editor';

             // 网格工具栏
             var toolbar = document.createElement('div');
             toolbar.className = 'grid-toolbar';

             var addRowBtn = document.createElement('button');
             addRowBtn.className = 'add-row-btn';
             addRowBtn.textContent = '添加行';

             var deleteGridBtn = document.createElement('button');
             deleteGridBtn.className = 'delete-grid-btn';
             deleteGridBtn.textContent = '删除网格';

             toolbar.appendChild(addRowBtn);
             //toolbar.appendChild(deleteGridBtn);

             // 行容器
             var rowsContainer = document.createElement('div');
             rowsContainer.className = 'grid-rows';

             grid.appendChild(toolbar);
             grid.appendChild(rowsContainer);

             // 添加到父容器
             parent.appendChild(grid);

             // 默认添加一行（2列）
             addRowToGrid(grid, 2);

             // ---------- 事件监听：使用事件委托处理当前网格的所有点击 ----------
             addGridEvent(grid);
             return grid;
         }

         // ---------- 生成干净的布局 HTML (移除所有按钮和工具栏) ----------
         function getCleanLayoutHTML(rootGrid) {
             var clone = rootGrid.cloneNode(true);
             var toolbars = clone.querySelectorAll('.grid-toolbar');
             for (var p = 0; p < toolbars.length; p++) {
                 var toolbar = toolbars[p];
                 toolbar.parentNode.removeChild(toolbar);
             }
             var btns = clone.querySelectorAll('.cell-buttons');
             for (var p = 0; p < btns.length; p++) {
                 var btn = btns[p];
                 btn.parentNode.removeChild(btn);
             }
             btns = clone.querySelectorAll('.bind-data-btn');
             for (var p = 0; p < btns.length; p++) {
                 var btn = btns[p];
                 btn.parentNode.removeChild(btn);
             }


             var centers = clone.querySelectorAll('.cell-center');
             for (var p = 0; p < centers.length; p++) {
                 var center = centers[p];
                 //center.outerHTML = center.innerText;
                 center.outerHTML = center.getAttribute("data-text");
             }

             var gridcells = clone.querySelectorAll('.grid-cell');
             for (var p = 0; p < gridcells.length; p++) {
                 var gridcell = gridcells[p];
                 gridcell.className = "grid-cell";
             }



             var contents = clone.querySelectorAll('.cell-content');
             for (var p = 0; p < contents.length; p++) {
                 var content = contents[p];
                 if (content.children.length == 0) {
                     content.parentNode.removeChild(content);
                 }
             }

             var gridrows = clone.querySelectorAll('.grid-rows');

             //for (var p = 0; p < gridrows.length; p++) 
             for (var p = gridrows.length - 1; p >= 0; p--) {
                 var gridrow = gridrows[p];
                 gridrow.outerHTML = gridrow.innerHTML;
             }


             var grideditors = clone.querySelectorAll('.grid-editor');
             //for (var p = 0; p < grideditors.length; p++)
             for (var p = grideditors.length - 1; p >= 0; p--) {
                 var grideditor = grideditors[p];
                 grideditor.outerHTML = grideditor.innerHTML;
             }

             var contents = clone.querySelectorAll('.cell-content');
             //for (var p = 0; p < contents.length; p++)
             for (var p = contents.length - 1; p >= 0; p--) {
                 var content = contents[p];
                 content.outerHTML = content.innerHTML;
             }

             return clone.innerHTML;
         };

         // ---------- 重置编辑器（创建新的根网格）----------
         function resetEditor() {
             var app = document.getElementById('app');
             app.innerHTML = '';
             createGrid(app);
             // 清除选中
             clearSelected();
         }
         document.body.addEventListener('keydown', function (e) {
             var cell = $("div.selected");
             if(cell.length!=1)
             {
                 return;
             }
             var row=cell.parent();
             if(e.keyCode==38)//↑
             {
                 if(row.prev().length==1)
                 {
                     row.insertBefore(row.prev());
                 }
             }
             if(e.keyCode==40)//↓
             {
                 if(row.next().length==1)
                 {
                     row.insertAfter(row.next());
                 }
             }

             if(e.keyCode==37)//←
             {
                 if(cell.prev().length==1)
                 {
                     cell.insertBefore(cell.prev());
                 }
             }
             if(e.keyCode==39)//→
             {
                 if(cell.next().length==1)
                 {
                     cell.insertAfter(cell.next());
                 }
             }
             //parent.document.title= e.keyCode;
         });
         // ---------- 全局点击处理（管理选中状态，支持Ctrl多选）----------
         document.addEventListener('mousedown', function (e) {
             // 忽略按钮点击，避免干扰
             if (e.target.tagName === 'BUTTON') return;

             var cell = e.target.closest('.grid-cell');
             if (!cell) {
                 // 点击空白区域清除选中
                 clearSelected();
                 return;
             }

             // 阻止事件冒泡，防止网格内事件干扰
             e.stopPropagation();

             if (e.ctrlKey || e.metaKey) {
                 // Ctrl+单击：切换选中状态
                 if (cell.classList.contains('selected')) {
                     // 如果已选中，则取消选中
                     cell.classList.remove('selected');
                     var idx = selectedCells.indexOf(cell);
                     if (idx !== -1) selectedCells.splice(idx, 1);
                 } else {
                     // 否则添加选中
                     cell.classList.add('selected');
                     selectedCells.push(cell);
                 }
             } else {
                 // 普通单击：清除其他，只选中当前
                 clearSelected();
                 cell.classList.add('selected');
                 selectedCells = [cell];
             }
         });
         function initGrid()
         {
             // 创建网格根元素
             var grid = document.getElementsByClassName('grid-editor')[0];            
             // ---------- 事件监听：使用事件委托处理当前网格的所有点击 ----------
             addGridEvent(grid);
         };
         function update()
         {
             var root = document.querySelector('#app .grid-editor');
             if (root) {
                 var clone = root.cloneNode(true);
                 var gridcells = clone.querySelectorAll('.selected');
                 for (var p = 0; p < gridcells.length; p++) {
                     var gridcell = gridcells[p];
                     gridcell.className = "grid-cell";
                 }

                 var url = "?modelid=<%=modelid%>&obj=<%=obj%>&act=save";
                 $.ajax({
                     type: 'POST',
                     async: false,
                     url: url,
                     data: { "html": clone.outerHTML },
                     //contentType: 'application/json; charset=utf-8',
                     dataType: 'html',
                     success: function (data) {
                         //parent.layer.close(parent.arrLayerIndex.pop());
                     }
                 });



                 var html = getCleanLayoutHTML(root);
                 html = formatHTML(html, 2);
                 parent.<%=obj%>.value = html;
                 parent.<%=obj%>.onblur();
                 //parent.pre_HtmlBody.innerHTML = html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
                 var editor = parent.ace.edit('pre_<%=obj%>');
                 editor.setValue(html);

                 parent.layer.close(parent.arrLayerIndex.pop());
                 //alert(parent.HtmlBody.value);
                 //alert(html);
                 //exportOutput.value = cleanHTML;
             }
         };
         // ---------- 初始化 ----------
         window.onload = function () {
             initGrid();
             //resetEditor();
             // 绑定重置按钮
             document.getElementById('resetBtn').addEventListener('click', function () {
                 if (confirm('重置将清空当前所有网格，确定吗？')) {
                     resetEditor();
                 }
             });

             // 绑定合并按钮
             document.getElementById('mergeBtn').addEventListener('click', function () {
                 mergeSelectedCells();
             });

             // 绑定取消合并按钮
             document.getElementById('unmergeBtn').addEventListener('click', function () {
                 unmergeSelectedCell();
             });

             // 绑定导出按钮
             var exportBtn = document.getElementById('exportBtn');
             exportBtn.addEventListener('click', function () {
                 update();
             });
             //var exportOutput = document.getElementById('exportOutput');
             /*
             exportBtn.addEventListener('click', function () {
                 var root = document.querySelector('#app .grid-editor');
                 if (root) {
                     var cleanHTML = getCleanLayoutHTML(root);
                     exportOutput.value = cleanHTML;
                 } else {
                     exportOutput.value = '未找到网格，请重置。';
                 }
             });
             */
         };
     })();
    </script>
</body>
</html>
