// 子目录绑定功能
?>

<div class="card">
    <div class="card-header">
        <h3 class="card-title mb-0"><?php echo L('subdirectory_binding', 'menu'); ?></h3>
    </div>
    <div class="card-body">
        <div class="form-inline mb-3" style="font-size:13px;">
            <span class="font-weight-bold mr-2">域名</span>
            <input type="text" class="form-control form-control-sm mr-3" id="zmlDomain" placeholder="example.com 或 *.example.com">
            <span class="font-weight-bold mr-2">子目录</span>
            <select class="form-control form-control-sm mr-3" id="zmlDir" style="min-width:180px;">
                <option value="/">加载中...</option>
            </select>
            <button type="button" class="btn btn-primary btn-sm" id="btnAddZml">
                <i class="fas fa-plus"></i> 添加
            </button>
        </div>

        <div id="zmlList" class="table-responsive">
            <div class="text-center py-4 text-muted" style="font-size:13px;">
                <i class="fas fa-spinner fa-spin mr-1"></i> 加载中...
            </div>
        </div>

        <div class="d-flex align-items-center mt-3" style="font-size:13px;">
            <input type="checkbox" id="zmlSelectAll" class="mr-2">
            <select class="form-control form-control-sm mr-2" id="zmlBatchAction" style="width:180px;">
                <option value="">请选择批量操作</option>
                <option value="delete">批量删除</option>
            </select>
            <button type="button" class="btn btn-outline-primary btn-sm" id="btnZmlBatch">批量操作</button>
        </div>
    </div>
</div>

<!-- 复用上面的子目录绑定模态框 -->
<!-- 子目录绑定模态框 -->
<div class="modal fade" id="subdirModal" tabindex="-1" role="dialog" aria-labelledby="subdirModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="subdirModalLabel"><?php echo L('subdirectory_binding', 'menu'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="subdirBindingId">
                <div class="form-group">
                    <label class="font-weight-bold">域名</label>
                    <input type="text" id="subdirDomain" class="form-control" readonly>
                </div>
                <div class="form-group">
                    <label class="font-weight-bold">当前绑定目录</label>
                    <input type="text" id="subdirCurrentPath" class="form-control" readonly>
                    <small class="form-text text-muted">为空或 "/" 表示绑定到网站根目录。</small>
                </div>
                <div class="form-group mb-1">
                    <label class="font-weight-bold">新的子目录名称</label>
                    <input type="text" id="subdirDirName" class="form-control" placeholder="例如：blog，不要带 /">
                    <small class="form-text text-muted">
                        - 只填写目录名，如 <code>blog</code>，不要写成 <code>/blog/</code>。<br>
                        - 设为空表示取消子目录绑定，回到根目录。
                    </small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo L('cancel', 'common'); ?></button>
                <button type="button" class="btn btn-primary" onclick="saveSubdirBinding(this)"><?php echo L('save', 'common'); ?></button>
            </div>
        </div>
    </div>
</div>

<style>
    #zmlList table.domain-subdir-table th,
    #zmlList table.domain-subdir-table td {
        font-size: 13px;
        padding: 6px 8px;
        vertical-align: middle;
        white-space: nowrap;
    }
    #zmlList table.domain-subdir-table td code {
        font-size: 12px;
    }
</style>

<!-- 子目录伪静态模态框 -->
<div class="modal fade" id="rewriteModal" tabindex="-1" role="dialog" aria-labelledby="rewriteModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="rewriteModalLabel"><?php echo L('rewrite', 'menu'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="rewriteBindId">
                <input type="hidden" id="rewriteDomain">
                <input type="hidden" id="rewritePath">
                <div class="form-group">
                    <label class="font-weight-bold">域名</label>
                    <input type="text" id="rewriteDomainDisplay" class="form-control" readonly>
                </div>
                <div class="form-group">
                    <label class="font-weight-bold">子目录</label>
                    <input type="text" id="rewritePathDisplay" class="form-control" readonly>
                </div>
                <div class="form-group">
                    <label class="font-weight-bold">选择伪静态规则</label>
                    <select class="form-control" id="rewriteSelect" onchange="changeRewrite(this)">
                        <option value="">请选择伪静态规则...</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="font-weight-bold">伪静态规则内容</label>
                    <textarea class="form-control" id="rewriteContent" rows="10" placeholder="请输入伪静态规则..."></textarea>
                    <small class="form-text text-muted">
                        支持Nginx伪静态规则。如：<code>location / { try_files $uri $uri/ /index.php$is_args$args; }</code>
                    </small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo L('cancel', 'common'); ?></button>
                <button type="button" class="btn btn-primary" onclick="saveSubdirRewrite(this)"><?php echo L('save', 'common'); ?></button>
            </div>
        </div>
    </div>
</div>

<script>

function loadZmlPage() {
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: 'egn=getdirbinding',
        dataType: 'json',
        success: function(data) {
            console.log('子目录绑定API返回:', data);
            
            // 直接使用返回的数据，不需要提取 data.data
            var apiData = data;
            
            // dirs 下拉列表
            var dirs = (apiData && Array.isArray(apiData.dirs)) ? apiData.dirs : [];
            
            // 如果dirs为空，从binding列表中提取目录
            var bindingList = (apiData && Array.isArray(apiData.binding)) ? apiData.binding : [];
            
            // 规范化 path 字段：确保所有路径都以 ../ 开头（除了根目录 /）
            bindingList = bindingList.map(function(item) {
                var path = item.path || '/';
                // 如果不是根目录，且不以 ../ 或 / 开头，则添加 ../
                if (path !== '/' && path.indexOf('../') !== 0 && path.indexOf('/') !== 0) {
                    item.path = '../' + path;
                }
                return item;
            });
            
            if (dirs.length === 0 && bindingList.length > 0) {
                bindingList.forEach(function(item) {
                    var path = item.path || '';
                    // 提取目录名：支持 ../qq 或 qq 格式
                    var dirName = path;
                    // 去掉 ../ 前缀
                    if (dirName.indexOf('../') === 0) {
                        dirName = dirName.substring(3);
                    }
                    // 去掉首尾斜杠
                    dirName = dirName.replace(/^\/+|\/+$/g, '');
                    if (dirName && dirs.indexOf(dirName) === -1) {
                        dirs.push(dirName);
                    }
                });
            }
            
            console.log('提取的目录列表:', dirs);
            console.log('规范化后的绑定列表:', bindingList);
            
            var $sel = $('#zmlDir');
            $sel.empty();
            dirs.forEach(function(d) {
                var val = (d === '/' ? '/' : String(d).replace(/^\/+|\/+$/g, ''));
                if (!val) val = '/';
                var text = (val === '/' ? '/' : val);
                $sel.append($('<option></option>').val(val === '/' ? '/' : val).text(text));
            });
            if (!$sel.find('option[value="/"]').length) {
                $sel.prepend($('<option></option>').val('/').text('/'));
            }

            // list 表格 - 子目录绑定列表
            renderZmlList(bindingList);
        },
        error: function(xhr) {
            console.error('子目录绑定请求失败:', xhr);
            $('#zmlList').html('<div class="text-center py-4 text-muted" style="font-size:13px;">加载失败</div>');
        }
    });
}

function renderZmlList(domains) {
    if (!Array.isArray(domains) || domains.length === 0) {
        $('#zmlList').html('<div class="text-center py-5 text-muted" style="font-size:13px;"><i class="fas fa-inbox fa-3x mb-3 d-block"></i>暂无数据</div>');
        return;
    }
    var $table = $('<table class="table table-sm table-bordered mb-0 domain-subdir-table"></table>');
    var $thead = $('<thead class="thead-light"><tr>' +
                   '<th style="width:40px;"><input type="checkbox" id="zmlCheckAll"></th>' +
                   '<th>域名</th>' +
                   '<th style="width:80px;">端口</th>' +
                   '<th style="width:100px;">子目录</th>' +
                   '<th style="width:80px;">伪静态</th>' +
                   '<th style="width:160px;" class="text-right">操作</th>' +
                   '</tr></thead>');
    var $tbody = $('<tbody></tbody>');
    domains.forEach(function(item) {
        var name  = item.name || item.domain || '';
        var port  = item.port || 80;
        var url = (port == 80 || port == 443) ? (port == 443 ? 'https://' : 'http://') + name : 'http://' + name + ':' + port;
        var path  = item.path || '/';
        var bindId = item.bind_id || item.id || '';
        var isBinding = !!bindId || item.is_binding === true;
        var showDir = (path && path !== '/' && path !== '../') ? path.replace(/^\.\.\//, '').replace(/^\/+|\/+$/g, '') : '/';
        var hasRewrite = item.has_rewrite === true || item.rewrite_content;
        var $tr = $('<tr></tr>');
        $tr.append('<td><input type="checkbox" class="zml-cb" data-name="' + name + '" data-port="' + port + '" data-bind-id="' + (bindId || '') + '" data-path="' + path + '"></td>');
        $tr.append('<td><a href="' + url + '" target="_blank" class="font-weight-bold text-decoration-none" title="点击访问">' + name + '</a></td>');
        $tr.append('<td>' + port + '</td>');
        $tr.append('<td><code class="mb-0">' + showDir + '</code></td>');
        // 伪静态列
        var rewriteStatus = hasRewrite ? '<span class="badge badge-success">已设置</span>' : '<span class="badge badge-secondary">未设置</span>';
        $tr.append('<td>' + rewriteStatus + '</td>');
        var $ops = $('<td class="text-right"></td>');
        var $btnSub = $('<button type="button" class="btn btn-outline-secondary btn-xs mr-2 btn-bind-subdir"><i class="fas fa-edit"></i> 修改</button>');
        $btnSub.attr('data-name', name).attr('data-path', path);
        if (isBinding && bindId) $btnSub.attr('data-bind-id', bindId);
        // 伪静态按钮
        var $btnRewrite = $('<button type="button" class="btn btn-outline-info btn-xs mr-2 btn-rewrite-subdir" title="设置伪静态"><i class="fas fa-magic"></i> 伪静态</button>');
        $btnRewrite.attr('data-name', name).attr('data-path', path);
        if (bindId) $btnRewrite.attr('data-bind-id', bindId);
        var $btnDel = $('<button type="button" class="btn btn-danger btn-xs btn-delete-domain"><i class="fas fa-trash"></i> 删除</button>');
        $btnDel.attr('data-name', name).attr('data-port', port);
        if (isBinding && bindId) $btnDel.attr('data-bind-id', bindId);
        $ops.append($btnSub).append($btnRewrite).append($btnDel);
        $tr.append($ops);
        $tbody.append($tr);
    });
    $table.append($thead).append($tbody);
    $('#zmlList').empty().append($table);

    $('#zmlCheckAll').off('change').on('change', function() {
        $('#zmlList .zml-cb').prop('checked', this.checked);
    });
}

function addZmlBinding() {
    var domain = $('#zmlDomain').val().trim();
    var dir = $('#zmlDir').val();
    if (!domain) {
        layer.msg('请输入域名', {icon: 2});
        return;
    }
    // 域名格式验证：支持如 example.com, blog.example.com, *.example.com（泛解析）
    var domainRegex = /^(\*\.)?([a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/i;
    if (!domainRegex.test(domain)) {
        layer.msg('域名格式不正确，请输入正确的域名（如 example.com, blog.example.com, *.example.com）');
        return;
    }
    // 根目录：走添加域名
    if (!dir || dir === '/') {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: { egn: 'setym', ym: domain },
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                if (res && res.status) {
                    layer.msg(res.msg || '添加成功');
                    $('#zmlDomain').val('');
                    loadZmlPage();
                } else {
                    layer.alert((res && res.msg) ? res.msg : '添加失败');
                }
            },
            error: function() {
                layer.close(ii);
                layer.msg('添加失败，请重试');
            }
        });
        return;
    }

    // 子目录：走子目录绑定
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: { action: 'adddirbinding', domain: domain, dir: dir },
        dataType: 'json',
        success: function(res) {
            layer.close(ii);
            if (res && (res.status === true || res.code === 'success')) {
                layer.msg(res.msg || '绑定成功');
                $('#zmlDomain').val('');
                loadZmlPage();
            } else {
                layer.alert((res && (res.msg || res.code)) ? (res.msg || res.code) : '绑定失败');
            }
        },
        error: function() {
            layer.close(ii);
            layer.msg('绑定失败，请重试');
        }
    });
}

function batchDeleteZml() {
    var action = $('#zmlBatchAction').val();
    if (action !== 'delete') return;
    var items = [];
    $('#zmlList .zml-cb:checked').each(function() {
        items.push({
            name: $(this).data('name'),
            port: $(this).data('port'),
            bindId: $(this).data('bind-id'),
            path: $(this).data('path')
        });
    });
    if (!items.length) {
        layer.msg('请先选择要操作的域名', {icon: 2});
        return;
    }
    layer.confirm('确定删除选中的 ' + items.length + ' 项？', {btn: ['确定', '取消']}, function() {
        var promises = items.map(function(it) {
            if (it.bindId) {
                return $.ajax({ type: 'POST', url: './api/api_router.php', data: { action: 'deldirbinding', id: it.bindId }, dataType: 'json' });
            }
            return $.ajax({ type: 'POST', url: './api/api_router.php', data: { action: 'delym', domain: it.name, port: it.port }, dataType: 'json' });
        });
        $.when.apply($, promises).always(function() {
            layer.closeAll();
            loadZmlPage();
        });
    });
}

$(document).ready(function() {
    loadZmlPage();
    $('#btnAddZml').on('click', addZmlBinding);
    $('#zmlDomain').on('keydown', function(e){ if (e.key === 'Enter') { e.preventDefault(); addZmlBinding(); }});
    $('#btnZmlBatch').on('click', batchDeleteZml);

    // 修改按钮：打开子目录绑定编辑模态框
    $(document).on('click', '#zmlList .btn-bind-subdir', function(e) {
        e.preventDefault();
        console.log('修改按钮点击事件触发');
        var name = $(this).data('name') || '';
        var path = $(this).data('path') || '/';
        var bindId = $(this).data('bind-id') || '';
        
        console.log('修改按钮数据:', {name: name, path: path, bindId: bindId});
        
        $('#subdirDomain').val(name);
        $('#subdirCurrentPath').val(path);
        $('#subdirDirName').val(path && path !== '/' && path !== '../' ? path.replace(/^\.\.\//, '').replace(/^\/+|\/+$/g, '') : '');
        $('#subdirBindingId').val(bindId);
        
        $('#subdirModal').modal('show');
    });

    // 删除按钮：根域名/子目录绑定都能删（根据 bind_id 判断）
    $(document).on('click', '#zmlList .btn-delete-domain', function(e) {
        e.preventDefault();
        console.log('删除按钮点击事件触发');
        var domain = $(this).attr('data-name');
        var port = $(this).attr('data-port');
        var bindId = $(this).attr('data-bind-id');
        console.log('删除按钮数据:', {domain: domain, port: port, bindId: bindId});
        if (bindId) {
            delDirBinding(bindId, loadZmlPage);
        } else {
            delym(domain, port, loadZmlPage);
        }
    });
});

// 删除子目录绑定（zml页面专用）
function delDirBinding(id, callback) {
    layer.confirm('确定要删除该子目录绑定吗？', {btn: ['确定', '取消']}, function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: './api/api_router.php',
            data: { action: 'deldirbinding', id: id },
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                if (res.status === true || res.code === 'success') {
                    layer.msg(res.msg || '删除成功');
                    if (callback) {
                        callback();
                    } else {
                        loadZmlPage();
                    }
                } else {
                    layer.alert(res.msg || res.code || '删除失败');
                }
            },
            error: function() {
                layer.close(ii);
                layer.msg('删除失败，请重试');
            }
        });
    });
}

// 删除域名（zml页面专用）
function delym(domain, port, callback) {
    layer.confirm('确定要删除域名 "' + domain + '" 吗？', {
        btn: ['确定', '取消']
    }, function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: './api/api_router.php',
            data: {
                action: 'delym',
                domain: domain,
                port: port
            },
            dataType: 'json',
            success: function(data) {
                console.log('删除域名API返回:', data);
                layer.close(ii);
                if(data.status === true || data.code === 'success') {
                    layer.msg(data.msg || '删除成功');
                    if (callback) {
                        callback();
                    } else {
                        loadZmlPage();
                    }
                } else {
                    layer.alert(data.msg || data.code || '删除失败');
                }
            },
            error: function() {
                console.error('删除域名请求失败');
                layer.close(ii);
                layer.msg('删除失败，请重试');
            }
        });
    });
}

// 保存子目录绑定（zml页面专用）
function saveSubdirBinding(btn) {
    var $btn = $(btn);
    var domain = $('#subdirDomain').val();
    var dirName = $('#subdirDirName').val().trim();
    var bindId = $('#subdirBindingId').val();

    // 空表示取消绑定，恢复根目录
    if (!dirName) {
        if (!bindId) {
            $('#subdirModal').modal('hide');
            return;
        }
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: './api/api_router.php',
            data: { action: 'deldirbinding', id: bindId },
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                if (res.status === true || res.code === 'success') {
                    layer.msg(res.msg || '已取消子目录绑定');
                    $('#subdirModal').modal('hide');
                    loadZmlPage();
                } else {
                    layer.alert(res.msg || res.code || '取消子目录绑定失败');
                }
            },
            error: function() {
                layer.close(ii);
                layer.msg('取消子目录绑定失败，请重试');
            }
        });
        return;
    }

    // 规范目录名：只允许相对目录名，不带首尾 /
    dirName = dirName.replace(/^\/+|\/+$/g, '');

    var doAdd = function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: './api/api_router.php',
            data: { action: 'adddirbinding', domain: domain, dir: dirName },
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                if (res.status === true || res.code === 'success') {
                    layer.msg(res.msg || '绑定成功');
                    $('#subdirModal').modal('hide');
                    loadZmlPage();
                } else {
                    layer.alert(res.msg || res.code || '绑定失败');
                }
            },
            error: function() {
                layer.close(ii);
                layer.msg('绑定失败，请重试');
            }
        });
    };

    // 如果已有绑定，先删除再添加
    if (bindId) {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: './api/api_router.php',
            data: { action: 'deldirbinding', id: bindId },
            dataType: 'json',
            complete: function() {
                layer.close(ii);
                doAdd();
            }
        });
    } else {
        doAdd();
    }
}

// 获取子目录伪静态规则列表
var subdirRewriteRulesCache = null;

function getSubdirRewriteRules() {
    var $sel = $('#rewriteSelect');
    
    // 如果有缓存，直接使用
    if (subdirRewriteRulesCache && Array.isArray(subdirRewriteRulesCache)) {
        populateSubdirRewriteSelect(subdirRewriteRulesCache);
        return;
    }
    
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: 'action=getrewriterules',
        dataType: 'json',
        timeout: 8000,
        success: function(data) {
            console.log('获取伪静态规则列表返回：', data);
            if (data && data.code == 'success' && data.rules && Array.isArray(data.rules)) {
                subdirRewriteRulesCache = data.rules;
                populateSubdirRewriteSelect(data.rules);
            } else {
                $sel.html('<option value="">获取规则失败</option>');
            }
        },
        error: function() {
            console.log('获取伪静态规则列表失败');
            $sel.html('<option value="">获取规则失败</option>');
        }
    });
}

function populateSubdirRewriteSelect(rules) {
    var select = $('#rewriteSelect');
    select.empty();
    select.append('<option value="">请选择伪静态规则...</option>');
    
    // 兼容各种字段名
    rules.forEach(function(rule) {
        var name = rule.name || rule.title || rule.id || '';
        var content = rule.content || rule.data || rule.rule || '';
        if (name) {
            select.append($('<option>').val(name).text(name).data('content', content));
        }
    });
}

// 切换伪静态规则选择
function changeRewrite(sel) {
    var name = $(sel).val();
    if (!name) {
        return;
    }
    
    // 先检查缓存中是否有内容
    var $selected = $(sel).find('option:selected');
    var cachedContent = $selected.data('content');
    if (cachedContent) {
        $('#rewriteContent').val(cachedContent);
        return;
    }
    
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: { action: 'getrewritecontent', name: name },
        dataType: 'json',
        success: function(data) {
            console.log('获取伪静态规则内容返回：', data);
            // 兼容各种字段名
            var content = data.content || data.data || data.rule || '';
            if (content) {
                $('#rewriteContent').val(content);
                $selected.data('content', content); // 存入缓存
            }
        }
    });
}

// 打开子目录伪静态设置
$(document).on('click', '.btn-rewrite-subdir', function(e) {
    e.preventDefault();
    var name = $(this).data('name') || '';
    var path = $(this).data('path') || '/';
    var bindId = $(this).data('bind-id') || '';
    
    console.log('打开伪静态设置:', {name: name, path: path, bindId: bindId});
    
    $('#rewriteBindId').val(bindId);
    $('#rewriteDomain').val(name);
    $('#rewritePath').val(path);
    $('#rewriteDomainDisplay').val(name);
    $('#rewritePathDisplay').val(path && path !== '/' ? path.replace(/^\.\.\//, '') : '/');
    $('#rewriteContent').val('');
    $('#rewriteSelect').val('');
    
    // 获取伪静态规则列表
    getSubdirRewriteRules();
    
    // 获取当前子目录的伪静态规则
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: { action: 'getsubdirrewrite', domain: name, path: path },
        dataType: 'json',
        success: function(data) {
            console.log('获取子目录伪静态返回:', data);
            if (data && data.code == 'success' && data.content) {
                $('#rewriteContent').val(data.content);
            }
        }
    });
    
    $('#rewriteModal').modal('show');
});

// 保存子目录伪静态规则
function saveSubdirRewrite(btn) {
    var bindId = $('#rewriteBindId').val();
    var domain = $('#rewriteDomain').val();
    var path = $('#rewritePath').val();
    var content = $('#rewriteContent').val();
    
    if (!bindId) {
        layer.msg('请先绑定子目录再设置伪静态', {icon: 2});
        return;
    }
    
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: JSON.stringify({ action: 'setsubdirrewrite', id: bindId, domain: domain, path: path, content: content }),
        dataType: 'json',
        contentType: 'application/json',
        success: function(res) {
            layer.close(ii);
            if (res && res.status) {
                layer.msg(res.msg || '保存成功', {icon: 1});
                $('#rewriteModal').modal('hide');
                loadZmlPage();
            } else {
                layer.alert((res && res.msg) ? res.msg : '保存失败');
            }
        },
        error: function(xhr, status, error) {
            layer.close(ii);
            layer.msg('保存失败：' + error, {icon: 2});
        }
    });
}
</script>