{include file="app/manage/view/index/emlog_nav"}

<!-- 页面标题 -->
<h1 class="page-title">
    <i class="fas fa-list"></i>
    发现管理
</h1>

<!-- 操作栏 -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div class="action-buttons">
        <a href="index.php?r=manage/find/addarticle" class="btn btn-primary">
            <i class="fas fa-plus"></i> 发布线索
        </a>
        <button class="btn btn-outline-success" onclick="location.reload()">
            <i class="fas fa-sync-alt"></i> 刷新
        </button>
        <button class="btn btn-success" onclick="openCollectModal()">
            <i class="fas fa-bolt"></i> 商品采集
        </button>
        <button class="btn btn-info" onclick="openNewsModal()">
            <i class="fas fa-newspaper"></i> 资讯采集
        </button>
        <div class="btn-group ml-2 d-none" id="batchBtnGroup">
            <button class="btn btn-warning" onclick="batchAction('publish')">
                <i class="fas fa-check-circle"></i> 批量发布
            </button>
            <button class="btn btn-secondary" onclick="batchAction('unpublish')">
                <i class="fas fa-eye-slash"></i> 批量取消发布
            </button>
            <button class="btn btn-danger" onclick="batchAction('delete')">
                <i class="fas fa-trash"></i> 批量删除
            </button>
        </div>
    </div>
    
    <div class="search-form w-300">
        <div class="input-group">
            <input type="text" class="form-control" id="keyword" placeholder="搜索文章标题" value="<?php echo isset($keyword) ? $keyword : ''; ?>">
            <div class="input-group-append">
                <button class="btn btn-outline-secondary" type="button" onclick="search()">
                    <i class="fas fa-search"></i>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 数据列表 -->
<div class="card">
    <div class="card-header">
        <i class="fas fa-table"></i> 文章列表
        <span class="badge badge-info float-right mt-1"><?php echo isset($page['count']) ? $page['count'] : count($ret); ?> 条记录</span>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover table-striped">
                <thead class="thead-light">
                    <tr>
                        <th class="w-40"><input type="checkbox" id="selectAll" onclick="toggleAll()" title="全选/取消"></th>
                        <th class="w-60">ID</th>
                        <th>文章标题</th>
                        <th class="w-120">分类</th>
                        <th class="w-60">推荐</th>
                        <th class="w-100">状态</th>
                        <th class="w-80">浏览量</th>
                        <th class="w-160">发布时间</th>
                        <th class="w-150">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($ret)): ?>
                    <?php foreach ($ret as $row): ?>
                    <tr>
                        <td><input type="checkbox" class="row-checkbox" value="<?php echo $row['id']; ?>" onclick="updateBatchBtns()"></td>
                        <td><?php echo $row['id']; ?></td>
                        <td>
                            <div class="text-truncate mw-300" title="<?php echo $row['title']; ?>">
                                <?php echo mb_substr($row['title'], 0, 50, 'UTF-8'); ?>
                                <?php if(mb_strlen($row['title'], 'UTF-8') > 50): ?>...<?php endif; ?>
                            </div>
                        </td>
                        <td>
                            <span class="badge badge-primary badge-pill">
                                <?php echo isset($navs[$row['navid']]) ? $navs[$row['navid']] : (isset($categories[$row['cid']]) ? $categories[$row['cid']] : '未分类'); ?>
                            </span>
                        </td>
                        <td>
                            <span class="badge badge-<?php echo $row['status'] == 1 ? 'success' : 'secondary'; ?>">
                                <?php echo $row['status'] == 1 ? '已发布' : '未发布'; ?>
                            </span>
                        </td>
                        <td>
                            <?php if (!empty($row['featured'])): ?>
                            <span class="badge badge-warning">⭐ 推荐</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="text-muted">
                                <i class="fas fa-eye mr-1"></i>
                                <?php echo $row['view']; ?>
                            </span>
                        </td>
                        <td>
                            <small class="text-muted">
                                <?php echo isset($row['date']) ? $row['date'] : ''; ?>
                            </small>
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm" role="group">
                                <a href="index.php?r=manage/find/editArticle&id=<?php echo $row['id']; ?>" class="btn btn-outline-primary" title="编辑">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="<?php echo url($route='index/index/view/id=<id>', $params=array('id'=>(int)$row['id'])); ?>" target="_blank" class="btn btn-outline-info" title="预览">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <button class="btn btn-outline-danger" onclick="delItem(<?php echo $row['id']; ?>)" title="删除">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php else: ?>
                    <tr>
                        <td colspan="9" class="text-center py-5">
                            <div class="empty-state">
                                <i class="fas fa-file-alt fa-3x text-muted mb-3"></i>
                                <h5 class="text-muted">暂无文章数据</h5>
                                <p class="text-muted">点击上方"发布线索"按钮添加文章</p>
                            </div>
                        </td>
                    </tr>
                    <?php endif; ?> 
                </tbody>
            </table>
        </div>
        
        <!-- 分页 -->
        <nav aria-label="分页导航" class="mt-4">
            <div class="text-center">
                <?php if(isset($page['page']) && $page['page']): ?>
                <ul class="pagination d-inline-flex">
                    <?php echo $page['page']; ?>
                </ul>
                <?php endif; ?>
                <?php if(isset($page['count'])): ?>
                <div class="text-muted mt-2">
                    <small>共 <?php echo number_format($page['count']); ?> 条数据</small>
                </div>
                <?php endif; ?>
            </div>
        </nav>
    </div>
</div>

<!-- 好单库朋友圈一键采集弹窗 -->
<style>
.pagination {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    list-style: none;
    padding: 0;
    margin: 0;
    flex-wrap: wrap;
    justify-content: center;
}

.pagination li {
    display: inline-flex;
    list-style: none;
}

.pagination a, .pagination span {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 36px;
    height: 36px;
    padding: 0 12px;
    border-radius: 6px;
    font-size: 14px;
    text-decoration: none;
    color: #495057;
    border: 1px solid #dee2e6;
    background-color: #fff;
    transition: all 0.2s;
}

.pagination a:hover {
    background-color: #e9ecef;
    color: #007bff;
    border-color: #b3d7ff;
}

.pagination .active a {
    background-color: #007bff;
    color: #fff;
    border-color: #007bff;
    font-weight: 600;
}

.cat-modal {
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,0.45);
    z-index: 10000;
    display: flex;
    align-items: center;
    justify-content: center;
}
.cat-modal-box {
    background: #fff;
    width: 560px;
    max-width: 94%;
    max-height: 88vh;
    overflow-y: auto;
    border-radius: 10px;
    box-shadow: 0 12px 40px rgba(0,0,0,0.25);
}
.cat-modal-header {
    padding: 14px 18px;
    font-weight: 600;
    font-size: 16px;
    border-bottom: 1px solid #f0f0f0;
}
.cat-modal-body {
    padding: 18px;
}
.cat-modal-footer {
    padding: 12px 18px;
    border-top: 1px solid #f0f0f0;
    text-align: right;
}
.cat-modal-footer .btn { margin-left: 8px; }
</style>
<div class="cat-modal d-none" id="collectModal">
    <div class="cat-modal-box">
        <div class="cat-modal-header">
            <i class="fas fa-bolt text-warning mr-2"></i> 一键采集（朋友圈）
        </div>
        <div class="cat-modal-body">
            <p class="text-muted small mb-3">将从朋友圈素材库拉取最新发圈文案并生成文章（含商品卡片）。仅归入「发现分类」，不使用电商产品分类。</p>
            <div class="form-group">
                <label class="small text-muted">数据源</label>
                <select class="form-control" id="collectSource" onchange="onCollectSourceChange()">
                    <option value="hdk">好单库朋友圈</option>
                    <option value="dtk">大淘客朋友圈</option>
                </select>
            </div>
            <div class="form-group" id="collectNavGroup">
                <label class="small text-muted">发现分类（前台频道）</label>
                <select class="form-control" id="collectNav">
                    <option value="0">未分类</option>
                    <?php if(isset($navs)): ?>
                    <?php foreach($navs as $k => $v): ?>
                    <option value="<?php echo $k; ?>"><?php echo $v; ?></option>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </select>
            </div>

            <!-- 大淘客朋友圈专属参数（默认隐藏）：商品分类(cid) => 文章分类(navid) 一对一，用户手动指定，不自动映射 -->
            <div id="dtkFields" style="display:none;">
                <p class="text-muted small mb-2">大淘客商品分类（与网站商品分类一致）对应本地「发现分类（文章分类）」，仅勾选并指定归属的分类参与采集。</p>
                <div class="table-responsive">
                    <table class="table table-sm table-bordered mb-2">
                        <thead class="thead-light"><tr><th>热门商品分类</th><th>归属文章分类</th><th>采集</th></tr></thead>
                        <tbody>
                        <?php
                        $dtkHot = array('9'=>'男装','1'=>'女装','5'=>'鞋包配饰','8'=>'数码家电');
                        if(isset($navs)): foreach($dtkHot as $cid => $cname):
                        ?>
                            <tr>
                                <td><?php echo htmlspecialchars($cname); ?> <small class="text-muted">(cid=<?php echo intval($cid); ?>)</small></td>
                                <td>
                                    <select class="form-control form-control-sm dtk-navid" data-cid="<?php echo intval($cid); ?>">
                                        <option value="0">不采集</option>
                                        <?php foreach($navs as $nk => $nv): ?>
                                        <option value="<?php echo $nk; ?>"><?php echo $nv; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td class="text-center"><input type="checkbox" class="dtk-cid-chk" data-cid="<?php echo intval($cid); ?>" checked></td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                    <div class="card card-body bg-light py-2 px-3 mb-2">
                        <div class="form-row align-items-end">
                            <div class="col">
                                <label class="small text-muted mb-1">其他商品分类ID（自定义）</label>
                                <input type="text" class="form-control form-control-sm" id="dtkCustomCids" placeholder="如 7,13,16">
                            </div>
                            <div class="col-auto">
                                <label class="small text-muted mb-1">归属文章分类</label>
                                <select class="form-control form-control-sm dtk-custom-navid">
                                    <option value="0">不采集</option>
                                    <?php if(isset($navs)): ?><?php foreach($navs as $nk => $nv): ?>
                                    <option value="<?php echo $nk; ?>"><?php echo $nv; ?></option>
                                    <?php endforeach; ?><?php endif; ?>
                                </select>
                            </div>
                        </div>
                        <small class="text-muted mt-1">支持的商品分类ID为 1~20（女装1、男装9、母婴2、化妆品3、美食6、居家4、数码家电8、鞋包配饰5、内衣10、箱包11、配饰12、户外运动13、家装家纺14、珠宝首饰15、奢侈品16、宠物用品17、图书音像18、话费充值19、其他20），可填多个，用英文逗号分隔。</small>
                    </div>
                </div>
                <div class="form-group">
                    <label class="small text-muted">排序方式</label>
                    <select class="form-control" id="collectSort">
                        <option value="0">综合排序</option>
                        <option value="1">商品上架时间（高→低）</option>
                        <option value="2">热销（高→低）</option>
                        <option value="3">领券量（高→低）</option>
                        <option value="4">佣金比例（高→低）</option>
                        <option value="5">券后价（高→低）</option>
                        <option value="6">券后价（低→高）</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="small text-muted">每页条数（pageSize，1~100）</label>
                    <input type="number" class="form-control" id="collectPageSize" value="50" min="1" max="100" step="1">
                </div>
            </div>

            <div class="form-group mb-0">
                <label class="small text-muted">采集页数（建议3~10页）</label>
                <input type="number" class="form-control" id="collectPages" value="5" min="1" max="20" step="1">
            </div>
        </div>
        <div class="cat-modal-footer">
            <button class="btn btn-sm btn-secondary" onclick="closeCollectModal()">取消</button>
            <button class="btn btn-sm btn-primary" id="collectConfirmBtn">开始采集</button>
        </div>
    </div>
</div>

<!-- 聚合资讯一键采集弹窗 -->
<div class="cat-modal d-none" id="newsModal">
    <div class="cat-modal-box w-560">
        <div class="cat-modal-header">
            <i class="fas fa-newspaper text-info mr-2"></i> 资讯采集（聚合数据）
        </div>
        <div class="cat-modal-body" style="max-height: 70vh; overflow-y: auto;">
            <p class="text-muted small mb-2">两个接口各自独立 Key；下方为聚合分类与本地「发现分类」一对一映射，仅勾选/选择需要对接的分类。</p>

            <div class="form-group">
                <label class="small text-muted">接口235 新闻头条 Key</label>
                <input type="text" class="form-control" id="newsKey235" placeholder="填写聚合数据 235 接口 Key" value="<?php echo isset($juheKeys['key235']) ? $juheKeys['key235'] : ''; ?>">
            </div>
            <div class="form-group">
                <label class="small text-muted">接口850 AI新闻简报 Key</label>
                <input type="text" class="form-control" id="newsKey850" placeholder="填写聚合数据 850 接口 Key" value="<?php echo isset($juheKeys['key850']) ? $juheKeys['key850'] : ''; ?>">
            </div>

            <div class="form-group">
                <label class="small text-muted">采集页数（每个分类拉取页数，建议 1~3）</label>
                <input type="number" class="form-control" id="newsPages" value="2" min="1" max="10">
            </div>

            <hr>
            <h6 class="text-muted">接口235 分类映射</h6>
            <div class="table-responsive">
                <table class="table table-sm table-bordered mb-3">
                    <thead class="thead-light"><tr><th>聚合分类</th><th>本地发现分类</th><th>对接</th></tr></thead>
                    <tbody>
                    <?php if(isset($juheTypes235)): ?>
                    <?php foreach($juheTypes235 as $code => $name): ?>
                        <tr>
                            <td><?php echo $name; ?> <small class="text-muted">(<?php echo $code; ?>)</small></td>
                            <td>
                                <select class="form-control form-control-sm" id="map235_<?php echo $code; ?>">
                                    <option value="0">不采集</option>
                                    <?php if(isset($navs)): ?><?php foreach($navs as $nk => $nv): ?>
                                    <option value="<?php echo $nk; ?>"><?php echo $nv; ?></option>
                                    <?php endforeach; ?><?php endif; ?>
                                </select>
                            </td>
                            <td class="text-center"><input type="checkbox" class="news235chk" data-code="<?php echo $code; ?>" checked></td>
                        </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <hr>
            <h6 class="text-muted">接口850 分类映射</h6>
            <div class="table-responsive">
                <table class="table table-sm table-bordered">
                    <thead class="thead-light"><tr><th>聚合分类</th><th>本地发现分类</th><th>对接</th></tr></thead>
                    <tbody>
                    <?php if(isset($juheTypes850)): ?>
                    <?php foreach($juheTypes850 as $code => $name): ?>
                        <tr>
                            <td><?php echo $name; ?> <small class="text-muted">(<?php echo $code; ?>)</small></td>
                            <td>
                                <select class="form-control form-control-sm" id="map850_<?php echo $code; ?>">
                                    <option value="0">不采集</option>
                                    <?php if(isset($navs)): ?><?php foreach($navs as $nk => $nv): ?>
                                    <option value="<?php echo $nk; ?>"><?php echo $nv; ?></option>
                                    <?php endforeach; ?><?php endif; ?>
                                </select>
                            </td>
                            <td class="text-center"><input type="checkbox" class="news850chk" data-code="<?php echo $code; ?>" checked></td>
                        </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="cat-modal-footer">
            <button class="btn btn-sm btn-secondary" onclick="closeNewsModal()">取消</button>
            <button class="btn btn-sm btn-primary" id="newsConfirmBtn">开始采集</button>
        </div>
    </div>
</div>

{include file="app/manage/view/index/emlog_footer"}

<script>
// 全选/取消全选
function toggleAll() {
    var all = document.getElementById('selectAll').checked;
    var boxes = document.querySelectorAll('.row-checkbox');
    for (var i = 0; i < boxes.length; i++) {
        boxes[i].checked = all;
    }
    updateBatchBtns();
}

// 显示/隐藏批量按钮
function updateBatchBtns() {
    var group = document.getElementById('batchBtnGroup');
    var checked = document.querySelectorAll('.row-checkbox:checked').length;
    if (checked > 0) {
        // 必须先移除 d-none（display:none !important 优先级高于内联 display），否则按钮不会显示
        group.classList.remove('d-none');
        group.style.display = 'inline-flex';
    } else {
        group.classList.add('d-none');
        group.style.display = '';
    }
}

// 获取选中的 ID
function getSelectedIds() {
    var ids = [];
    var boxes = document.querySelectorAll('.row-checkbox:checked');
    for (var i = 0; i < boxes.length; i++) {
        ids.push(boxes[i].value);
    }
    return ids.join(',');
}

// 批量操作
function batchAction(action) {
    var ids = getSelectedIds();
    if (!ids) { alert('请先选择要操作的文章'); return; }
    var titles = { publish: '批量发布', unpublish: '批量取消发布', delete: '批量删除' };
    var msg = titles[action] || action;
    if (action === 'delete') {
        if (!confirm('确定要' + msg + '这 ' + ids.split(',').length + ' 篇文章吗？此操作不可恢复！')) return;
    } else {
        if (!confirm('确定要' + msg + '这 ' + ids.split(',').length + ' 篇文章吗？')) return;
    }
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/find/batch', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                try {
                    var r = JSON.parse(xhr.responseText);
                    alert(r.info);
                    location.reload();
                } catch(e) {
                    alert('操作异常: ' + xhr.responseText.substring(0, 200));
                }
            } else {
                alert('请求失败 HTTP ' + xhr.status);
            }
        }
    };
    xhr.send('action=' + encodeURIComponent(action) + '&ids=' + encodeURIComponent(ids));
}

function search() {
    var keyword = document.getElementById('keyword').value;
    var url = 'index.php?r=manage/find/index';
    if (keyword) url += '&keyword=' + encodeURIComponent(keyword);
    location.href = url;
}

function delItem(id) {
    if(confirm('确定要删除这篇文章吗？此操作不可恢复！')) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'index.php?r=manage/find/del&id=' + id, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                try {
                    var result = JSON.parse(xhr.responseText);
                    if (result.status === 'y') {
                        alert(result.info);
                        location.reload();
                    } else {
                        alert(result.info);
                    }
                } catch(e) {
                    alert('删除失败，响应数据异常');
                }
            }
        };
        xhr.send();
    }
}

// 键盘事件 - 回车搜索
document.getElementById('keyword').addEventListener('keypress', function(e) {
    if(e.which === 13) {
        search();
    }
});

// 数据源切换：大淘客朋友圈时显示专属参数
function onCollectSourceChange() {
    var src = document.getElementById('collectSource').value;
    document.getElementById('dtkFields').style.display = (src === 'dtk') ? 'block' : 'none';
    // 大淘客用「商品分类→文章分类」映射表指定归属，独立的发现分类下拉多余，隐藏；好单库仍需使用
    var navGroup = document.getElementById('collectNavGroup');
    if (navGroup) navGroup.style.display = (src === 'dtk') ? 'none' : 'block';
}

// 一键采集（朋友圈：好单库 / 大淘客）
function openCollectModal() {
    // 移除 .d-none（display:none !important）类，用内联 display 覆盖，否则弹窗无法显示
    document.getElementById('collectModal').classList.remove('d-none');
    document.getElementById('collectModal').style.display = 'flex';
    onCollectSourceChange();
    var btn = document.getElementById('collectConfirmBtn');
    btn.disabled = false;
    btn.innerText = '开始采集';
    btn.onclick = function() {
        var src = document.getElementById('collectSource').value;
        var navid = document.getElementById('collectNav').value;
        var pages = document.getElementById('collectPages').value || 5;
        btn.disabled = true;
        btn.innerText = '采集中（请耐心等待）...';
        var url;
        if (src === 'dtk') {
            // 大淘客朋友圈：收集「商品分类 cid => 文章分类 navid」映射（参考资讯采集），POST 提交
            var sort = document.getElementById('collectSort').value || 0;
            var pageSize = document.getElementById('collectPageSize').value || 50;
            var map = {};
            var chks = document.querySelectorAll('.dtk-cid-chk');
            for (var i = 0; i < chks.length; i++) {
                if (!chks[i].checked) continue;
                var cid = chks[i].getAttribute('data-cid');
                var navSel = document.querySelector('.dtk-navid[data-cid="' + cid + '"]');
                var nav = navSel ? navSel.value : '0';
                if (nav && nav != '0') map[cid] = nav;
            }
            // 自定义商品分类ID：逗号分隔，统一映射到所选文章分类
            var customInput = document.getElementById('dtkCustomCids');
            var customNav = document.querySelector('.dtk-custom-navid');
            var customNavVal = customNav ? customNav.value : '0';
            if (customInput && customInput.value.trim() !== '' && customNavVal && customNavVal != '0') {
                var parts = customInput.value.split(',');
                for (var j = 0; j < parts.length; j++) {
                    var ccid = parts[j].trim();
                    if (ccid === '') continue;
                    if (!/^\d+$/.test(ccid)) continue; // 仅接受纯数字分类ID
                    map[ccid] = customNavVal;
                }
            }
            if (Object.keys(map).length === 0) {
                alert('请至少勾选一个大淘客商品分类，并指定其归属的文章分类');
                btn.disabled = false; btn.innerText = '开始采集';
                return;
            }
            var params = 'map=' + encodeURIComponent(JSON.stringify(map))
                + '&pages=' + encodeURIComponent(pages)
                + '&sort=' + encodeURIComponent(sort)
                + '&pageSize=' + encodeURIComponent(pageSize);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'index.php?r=manage/find/collectDtk', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    try {
                        var r = JSON.parse(xhr.responseText);
                        alert(r.info);
                        if (r.status === 'y') setTimeout(function() { location.reload(); }, 1500);
                    } catch(e) { alert('采集异常：' + xhr.responseText.substring(0, 200)); }
                    closeCollectModal();
                }
            };
            xhr.send(params);
            return;
        } else {
            url = 'index.php?r=manage/find/collect&navid=' + navid + '&pages=' + pages;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                try {
                    var r = JSON.parse(xhr.responseText);
                    alert(r.info);
                    if (r.status === 'y') {
                        setTimeout(function() { location.reload(); }, 1500);
                    }
                } catch(e) {
                    alert('采集异常，请稍后重试');
                }
                closeCollectModal();
            }
        };
        xhr.send();
    };
}

function closeCollectModal() {
    var m = document.getElementById('collectModal');
    if (m) { m.style.display = 'none'; m.classList.add('d-none'); }
    var btn = document.getElementById('collectConfirmBtn');
    if (btn) { btn.disabled = false; btn.innerText = '开始采集'; }
    var input = document.getElementById('collectPages');
    if (input) input.value = '5';
}

// 点击背景 / Esc 关闭采集弹窗
document.getElementById('collectModal').addEventListener('click', function(e) {
    if (e.target === this) { this.style.display = 'none'; this.classList.add('d-none'); }
});
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        var ids = ['collectModal', 'newsModal'];
        for (var i = 0; i < ids.length; i++) {
            var m = document.getElementById(ids[i]);
            if (m && m.style.display !== 'none') { m.style.display = 'none'; m.classList.add('d-none'); }
        }
    }
});

// ===== 资讯采集（聚合数据） =====
function openNewsModal() {
    // 移除 .d-none（display:none !important）类，用内联 display 覆盖，否则弹窗无法显示
    document.getElementById('newsModal').classList.remove('d-none');
    document.getElementById('newsModal').style.display = 'flex';
    var btn = document.getElementById('newsConfirmBtn');
    btn.disabled = false;
    btn.innerText = '开始采集';
    btn.onclick = function() {
        var key235 = document.getElementById('newsKey235').value.trim();
        var key850 = document.getElementById('newsKey850').value.trim();
        var pages  = document.getElementById('newsPages').value || 2;

        if (!key235 && !key850) {
            alert('请至少填写一个聚合接口 Key');
            return;
        }

        var map235 = {}, map850 = {};
        var c235 = document.querySelectorAll('.news235chk');
        for (var i = 0; i < c235.length; i++) {
            if (!c235[i].checked) continue;
            var code = c235[i].getAttribute('data-code');
            var nav = document.getElementById('map235_' + code).value;
            if (nav && nav != '0') map235[code] = nav;
        }
        var c850 = document.querySelectorAll('.news850chk');
        for (var j = 0; j < c850.length; j++) {
            if (!c850[j].checked) continue;
            var code2 = c850[j].getAttribute('data-code');
            var nav2 = document.getElementById('map850_' + code2).value;
            if (nav2 && nav2 != '0') map850[code2] = nav2;
        }

        if (key235 && Object.keys(map235).length === 0) {
            alert('已填 235 Key，请至少选择一个 235 分类并指定本地发现分类');
            return;
        }
        if (key850 && Object.keys(map850).length === 0) {
            alert('已填 850 Key，请至少选择一个 850 分类并指定本地发现分类');
            return;
        }

        btn.disabled = true;
        btn.innerText = '采集中（请耐心等待）...';

        var params = 'key235=' + encodeURIComponent(key235)
            + '&key850=' + encodeURIComponent(key850)
            + '&pages=' + encodeURIComponent(pages)
            + '&map235=' + encodeURIComponent(JSON.stringify(map235))
            + '&map850=' + encodeURIComponent(JSON.stringify(map850));

        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'index.php?r=manage/find/newsCollect', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                try {
                    var r = JSON.parse(xhr.responseText);
                    alert(r.info);
                    if (r.status === 'y') {
                        setTimeout(function() { location.reload(); }, 1500);
                    }
                } catch(e) {
                    alert('采集异常：' + xhr.responseText.substring(0, 200));
                }
                closeNewsModal();
            }
        };
        xhr.send(params);
    };
}

function closeNewsModal() {
    var m = document.getElementById('newsModal');
    if (m) { m.style.display = 'none'; m.classList.add('d-none'); }
    var btn = document.getElementById('newsConfirmBtn');
    if (btn) { btn.disabled = false; btn.innerText = '开始采集'; }
}

document.getElementById('newsModal').addEventListener('click', function(e) {
    if (e.target === this) { this.style.display = 'none'; this.classList.add('d-none'); }
});

</script>