<?php
if (!isset($ADMINKEY)) exit('404');
include('../Php/Admin/cookie.php');

$root = realpath(__DIR__ . '/../../../..');
$collectorLib = $root . '/PPQSQL/collect_lib.php';
if (is_file($collectorLib)) require_once $collectorLib;
$configFile = $root . '/PPQSQL/Admin/Basic/AdminBasic.php';
$typeFile = $root . '/PPQSQL/type.php';
$config = json_decode((string)@file_get_contents($configFile), true);
if (!is_array($config)) $config = array();

$notice = '';
$noticeClass = 'notice';

/* ===== PPQCMS 免费版：内置采集点锁定（勿删，删掉会回退到官方采集点） ===== */
if (!defined('PPQ_LOCK_KEY'))        define('PPQ_LOCK_KEY', 'ppqcms-free-2026');
if (!defined('PPQ_DEFAULT_API_ENC')) define('PPQ_DEFAULT_API_ENC', 'GAQFEx5JAkkQAAxUXV5VGAMcEBMEEUtIEQoIAlNAWxgAGAFMHQFCEBsBAAJEX1Y=');
if (!defined('PPQ_ALLOW_HOSTS_ENC')) define('PPQ_ALLOW_HOSTS_ENC', 'EhUYGgIdSkgBCQRdW1JUGBMfHA==');
if (!defined('PPQ_DEFAULT_API_B64')) define('PPQ_DEFAULT_API_B64', 'aHR0cHM6Ly9iZWl5b25nLnNsYXBpYmYuY29tL2FwaS5waHAvcHJvdmlkZS92b2Q=');

if (!function_exists('ppq_xor_de')) {
    function ppq_xor_de($enc, $key = PPQ_LOCK_KEY) {
        $raw = @base64_decode($enc);
        if ($raw === false || $raw === '') return '';
        $out = ''; $kl = strlen($key);
        for ($i = 0; $i < strlen($raw); $i++) $out .= chr(ord($raw[$i]) ^ ord($key[$i % $kl]));
        return $out;
    }
}
if (!function_exists('ppq_locked_api')) {
    function ppq_locked_api() {
        $u = ppq_xor_de(PPQ_DEFAULT_API_ENC);
        if (stripos($u, 'http') !== 0) $u = @base64_decode(PPQ_DEFAULT_API_B64);
        return $u ? rtrim($u, '/') : '';
    }
}
if (!function_exists('ppq_api_allowed')) {
    function ppq_api_allowed($url) {
        $hosts = ppq_xor_de(PPQ_ALLOW_HOSTS_ENC);
        if ($hosts === '') return false;
        $h = @parse_url($url, PHP_URL_HOST);
        if (!$h) return false;
        $h = strtolower($h);
        foreach (explode(',', $hosts) as $a) {
            $a = strtolower(trim($a));
            if ($a === '') continue;
            if ($h === $a || substr($h, -strlen('.' . $a)) === '.' . $a) return true;
        }
        return false;
    }
}
/* ===== 锁定段结束 ===== */

if (isset($_POST['save_collection'])) {
    $url = ppq_locked_api(); // 免费版：内置官方采集点，忽略任何手工提交
    $check = function_exists('ppq_preflight_collection_source')
        ? ppq_preflight_collection_source($url)
        : array('ok' => false, 'msg' => '采集预检模块未加载。');
    if (!empty($check['ok'])) {
        $config['CollectionDomain'] = base64_encode($check['api']);
        file_put_contents($configFile, json_encode($config, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
        $notice = '资源站预检通过，地址已保存。请继续绑定分类。';
        if (!empty($check['cover_warning'])) $notice .= ' 样本封面为空，采集时仍会继续读取详情封面字段。';
    } else {
        $noticeClass .= ' notice-error';
        $notice = '地址未保存：' . (isset($check['msg']) ? $check['msg'] : '资源站预检失败。');
    }
}

// 每类目标总条数：每日自动更新按此补齐
$collectTarget = isset($config['CollectPerCategory']) ? (int)$config['CollectPerCategory'] : 500;
if ($collectTarget < 10) $collectTarget = 500;
if ($collectTarget > 5000) $collectTarget = 5000;

if (isset($_POST['save_collect_target'])) {
    $t = (int)(isset($_POST['CollectPerCategory']) ? $_POST['CollectPerCategory'] : 500);
    $t = max(10, min(5000, $t));
    $config['CollectPerCategory'] = $t;
    file_put_contents($configFile, json_encode($config, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    $collectTarget = $t;
    $notice = '已保存：每类目标 ' . $t . ' 条。每日自动更新会按这个目标分批补齐。';
}

$collectionUrl = isset($config['CollectionDomain']) ? base64_decode($config['CollectionDomain']) : '';
$typeRows = json_decode((string)@file_get_contents($typeFile), true);
$activeNames = array();
foreach ((array)$typeRows as $row) {
    if (!empty($row['name']) && (!isset($row['type']) || $row['type'] === 'video')) $activeNames[] = $row['name'];
}
$isBound = function_exists('is_bound') ? is_bound() : false;
$selectedModules = isset($config['HomeModuleNames']) && is_array($config['HomeModuleNames']) ? $config['HomeModuleNames'] : array();
$homeLimit = function_exists('ppq_home_card_limit') ? ppq_home_card_limit(isset($config['HomeModuleLimit']) ? $config['HomeModuleLimit'] : null) : 16;

if (isset($_POST['save_home_modules'])) {
    if (!$isBound) {
        $noticeClass .= ' notice-error';
        $notice = '请先完成分类绑定，再设置首页展示分类。';
    } else {
        $allowed = array_flip($activeNames);
        $chosen = array();
        foreach ((array)(isset($_POST['HomeModuleNames']) ? $_POST['HomeModuleNames'] : array()) as $name) {
            $name = trim((string)$name);
            if ($name !== '' && isset($allowed[$name]) && !in_array($name, $chosen, true)) $chosen[] = $name;
            if (count($chosen) >= 6) break;
        }
        $config['HomeModuleNames'] = $chosen;
        $config['HomeModuleLimit'] = function_exists('ppq_home_card_limit')
            ? ppq_home_card_limit(isset($_POST['HomeModuleLimit']) ? $_POST['HomeModuleLimit'] : 16)
            : 16;
        file_put_contents($configFile, json_encode($config, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
        $selectedModules = $chosen;
        $homeLimit = $config['HomeModuleLimit'];
        $notice = '首页展示设置已保存。少于六个时，只会使用当前有视频数据的分类补足。';
    }
}
?>
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>采集资源站 - PPQCMS</title>
<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
<style>
*{box-sizing:border-box}body{margin:0;background:#eef3f1;color:#223047;font-family:"Microsoft YaHei","Segoe UI",sans-serif}.main-content{margin-left:270px;padding:24px 30px 36px}.breadcrumb{color:#718096;font-size:14px;margin-bottom:13px}.breadcrumb a{color:#3d927e;text-decoration:none}.page-title{margin:0;color:#223047;font-size:29px}.page-subtitle{margin:8px 0 24px;color:#718096}.collector-card{background:#fffdf9;border:1px solid #dce5e1;border-radius:12px;box-shadow:0 8px 22px rgba(34,48,71,.07);margin-bottom:20px;overflow:hidden}.card-head{padding:18px 22px;background:#edf4f1;border-bottom:1px solid #dce5e1;font-weight:700;font-size:18px}.card-body{padding:22px}.source-form{display:grid;grid-template-columns:1fr auto;gap:14px;align-items:end}.field label{display:block;font-weight:700;margin-bottom:8px}.field input{width:100%;height:46px;border:1px solid #cfdad6;border-radius:7px;padding:0 13px;font-size:16px}.field input:focus{outline:0;border-color:#3d927e;box-shadow:0 0 0 3px rgba(61,146,126,.14)}.hint{margin-top:8px;color:#718096;font-size:14px;word-break:break-all}.btn{height:46px;border:1px solid transparent;border-radius:7px;padding:0 18px;font-size:15px;font-weight:700;cursor:pointer}.btn:disabled{opacity:.55;cursor:not-allowed}.btn-main{background:#3d927e;color:#fff}.btn-outline{background:#fffdf9;color:#3d927e;border-color:#3d927e}.ops{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-top:18px;padding-top:18px;border-top:1px solid #dce5e1}.per{display:flex;align-items:center;gap:8px;color:#3d4c62}.per input{width:96px;height:42px;border:1px solid #cfdad6;border-radius:7px;padding:0 10px}.state{font-size:14px;color:#718096}.notice{margin-bottom:16px;padding:12px 14px;border:1px solid #b9dccc;background:#e8f3ef;border-radius:7px;color:#2f7566}.notice-error{border-color:#f0b9b4;background:#fff0ef;color:#b83d36}.home-module-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin:14px 0}.home-module-option{display:flex;align-items:center;gap:8px;border:1px solid #dce5e1;border-radius:8px;padding:10px 12px;background:#fff;cursor:pointer}.home-module-option input{accent-color:#3d927e}.home-module-option.is-disabled{opacity:.5;cursor:not-allowed;background:#f7f9f8}.module-toolbar{display:flex;align-items:center;gap:14px;flex-wrap:wrap}.module-toolbar select{height:42px;border:1px solid #cfdad6;border-radius:7px;padding:0 10px;background:#fff}.module-note{font-size:13px;color:#718096}.module-limit-tip{min-height:20px;margin-top:8px;color:#b83d36;font-size:13px}.result-meta{display:flex;gap:18px;flex-wrap:wrap;padding:14px 16px;background:#f7fbf9;border:1px solid #dce5e1;border-radius:8px;margin-bottom:16px}.category-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}.category{border:1px solid #dce5e1;border-radius:8px;padding:13px 14px;background:#fff}.category-name{font-weight:700;color:#223047;margin-bottom:8px}.category-data{display:flex;justify-content:space-between;color:#718096;font-size:13px}.ok{color:#2f7566}.low{color:#d94a45}.empty{text-align:center;color:#718096;padding:28px}.modal{position:fixed;inset:0;display:none;place-items:center;background:rgba(23,33,51,.45);z-index:9999}.modal.show{display:grid}.modal-box{background:#fffdf9;border-radius:12px;padding:25px;max-width:510px;width:calc(100% - 32px);box-shadow:0 16px 40px rgba(0,0,0,.24)}.modal-box h3{margin:0 0 15px}.progress-track{height:10px;background:#e5ece9;border-radius:999px;overflow:hidden;margin-top:16px}.progress-bar{height:100%;width:0;background:linear-gradient(90deg,#3d927e,#79c7b2);transition:width .35s ease}.progress-text{margin:9px 0 0;color:#718096;font-size:14px}.modal-close-row{text-align:right;margin:18px 0 0}.modal:not(.terminal) #modal-close{display:none!important}@media(max-width:992px){.main-content{margin-left:0;padding:24px 16px 28px}}@media(max-width:720px){.source-form{grid-template-columns:1fr}.category-grid,.home-module-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.card-body{padding:16px}}
</style>
<style id="ppq-unified">
/* PPQCMS 统一后台样式 — 仅视觉统一，不改布局 */
html,body{font-family:'Segoe UI','Microsoft YaHei',sans-serif}
body{background:#eef2f1!important;color:#223047!important}
.sidebar,.admin-sidebar,.menu-box,.left-menu{background:linear-gradient(180deg,#223047 0%,#172133 100%)!important;color:#fff!important}
.sidebar .logo-text,.sidebar .logo i{color:#fff!important}
.sidebar .menu-item,.sidebar .submenu-item{color:#DCE8E4!important}
.sidebar .menu-item:hover,.sidebar .submenu-item:hover{background:rgba(255,255,255,.08)!important;color:#fff!important}
.sidebar .menu-item.active,.sidebar .submenu-item.active,.sidebar .menu-item.selected{background:#3e9c88!important;color:#fff!important}
.header,.top-bar,.admin-header{background:#223047!important;color:#fff!important;box-shadow:0 2px 12px rgba(23,33,51,.18)!important}
.header a,.header .header-icon,.header .user-name{color:#F7FAF9!important}
.header .user-avatar{background:#3D4C62!important;color:#fff!important}
.settings-card,.card,.panel,.box,.content-card,.form-card,.table-card,.section-card,.admin-card,.data-card,.list-card,.info-card,.stat-card,.usage-guide{background:#fff!important;border:1px solid #dbe7e4!important;border-radius:14px!important;box-shadow:0 10px 28px rgba(27,50,74,.07)!important;overflow:hidden}
.settings-card-header,.card-header,.panel-header,.section-header,.content-card-header{background:#edf6f3!important;border-bottom:1px solid #dcebe6!important;color:#22344f!important;font-weight:800!important;font-size:20px!important;padding:18px 22px!important}
h1{font-size:31px!important;color:#22344f!important;margin:22px 0 8px!important}
h2,h3,.settings-title{color:#22344f!important}
.page-subtitle,.text-muted,.breadcrumb{color:#75879e!important}
.breadcrumb a{color:#3e9c88!important}
input[type=text],input[type=password],input[type=number],input[type=url],input[type=email],select,textarea{background:#fff!important;border:1px solid #cbdad6!important;color:#223047!important;border-radius:8px!important;padding:10px 12px!important;font-size:15px!important}
input:focus,select:focus,textarea:focus{border-color:#3e9c88!important;box-shadow:0 0 0 3px rgba(62,156,136,.14)!important;outline:none!important}
.btn-primary,.btn-success,.am-btn-primary,.am-btn-success,button.btn-primary{background:#3e9c88!important;border-color:#3e9c88!important;color:#fff!important;border-radius:8px!important;font-weight:800!important;padding:12px 18px!important;font-size:15px!important;cursor:pointer!important}
.btn-primary:hover,.btn-success:hover{background:#34876f!important;border-color:#34876f!important}
.btn-warning,.am-btn-warning{background:#C9953D!important;border-color:#C9953D!important;color:#fff!important}
.translation-switch input:checked+b{background:#3e9c88!important}
table{background:#fff!important;border-radius:12px!important;overflow:hidden}
th{background:#edf6f3!important;color:#22344f!important}
.alert-success,.am-alert-success{background:#E8F3EF!important;border-color:#B9DCCC!important;color:#21866f!important}
.alert-warning,.am-alert-warning{background:#FFF8E8!important;border-color:#EEDAA7!important;color:#7e6421!important}
/* 采集页与其他后台页面对齐（只改视觉：配色/圆角/阴影/字号，不动布局） */
.collector-card{background:#fff!important;border:1px solid #dbe7e4!important;border-radius:14px!important;box-shadow:0 10px 28px rgba(27,50,74,.07)!important;overflow:hidden}
.card-head{background:#edf6f3!important;border-bottom:1px solid #dcebe6!important;color:#22344f!important;font-weight:800!important;font-size:20px!important}
.page-title{font-size:31px!important;color:#22344f!important}
</style>

<style id="ppq-header-layout">
/* 后台顶栏布局：统一后台样式的过程中这段被覆盖丢掉了，导致顶栏元素在 DOM 里
   却没有定位与排布，页面上看不到"首页 / 退出 / 管理员"。这里只补布局，
   配色仍由 #ppq-admin-theme / #ppq-unified 负责，不改动其他任何元素。 */
.header{height:72px;display:flex;align-items:center;justify-content:space-between;padding:0 30px;position:fixed;top:0;left:260px;right:0;z-index:99;transition:left .3s}
.header-left{display:flex;align-items:center;gap:20px}
.header-right{display:flex;align-items:center;gap:20px}
.header-icon{display:inline-flex;align-items:center;gap:6px;position:relative;cursor:pointer;font-size:15px;text-decoration:none}
.header-icon:hover{text-decoration:none}
.user-profile{display:flex;align-items:center;gap:10px}
.user-avatar{width:40px;height:40px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:600}
.user-name{font-weight:500}
.mobile-toggle{display:none;background:none;border:0;font-size:21px;cursor:pointer}
.main-content{margin-left:260px;padding:96px 30px 36px}
@media(max-width:992px){
  .header{left:0}
  .main-content{margin-left:0;padding:96px 16px 28px}
}
</style>
</head>
<body>
<?php include('../Php/Admin/list.php'); include('../Php/Admin/header.php'); ?>
<main class="main-content">
  <div class="breadcrumb"><a href="?Php=Home/index">首页</a> / 基本设置 / 采集资源站</div>
  <h1 class="page-title"><i class="fa fa-cloud-download"></i> 采集资源站</h1>
  <p class="page-subtitle">配置 VOD JSON 接口，绑定视频分类后按分类采集内容。</p>
  <?php if ($notice): ?><div class="<?php echo $noticeClass; ?>"><i class="fa fa-check-circle"></i> <?php echo htmlspecialchars($notice, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
  <section class="collector-card"><div class="card-head"><i class="fa fa-link"></i> 资源站配置</div><div class="card-body">
    <form method="post" class="source-form"><div class="field"><label for="CollectionDomain">采集点域名</label><input id="CollectionDomain" name="CollectionDomain" disabled readonly style="background:#f5f5f5;color:#888;cursor:not-allowed;" value="<?php echo htmlspecialchars(ppq_locked_api(), ENT_QUOTES, 'UTF-8'); ?>">" placeholder="https://example.com/api.php/provide/vod"><div class="hint">免费版已内置官方采集点，不支持自定义。<a href="https://ppqzy.com" target="_blank" style="color:#e4393c;">升级付费版</a> 可自由切换任意资源站。</div></div><button class="btn btn-main" name="save_collection" value="1" disabled style="background:#bbb;cursor:not-allowed;"><i class="fa fa-lock"></i> 免费版已锁定</button></form>
    <div class="ops"><button type="button" id="bind" class="btn btn-outline"><i class="fa fa-sitemap"></i> 绑定分类</button><label class="per">每类采集 <input type="number" id="per" min="1" max="5000" value="<?php echo (int)$collectTarget; ?>"> 条</label><button type="button" id="collect" class="btn btn-main" disabled><i class="fa fa-download"></i> 采集资源</button><span id="state" class="state">正在读取采集状态…</span></div>
    <div class="hint" style="margin-top:10px">这里填的是「每个分类补到多少条」。站里已有的视频一条都不会动，只补差额；如果填的数字没超过现有条数，会直接提示你改大。换资源点不用管这里——点<strong>绑定分类</strong>时系统一旦发现资源点换了，会自动把旧视频清空再绑定新分类。</div>
  </div></section>
  <section class="collector-card"><div class="card-head"><i class="fa fa-th-large"></i> 首页展示设置</div><div class="card-body">
    <form method="post"><div class="module-toolbar"><strong>首页分类模块（最多 6 个）</strong><label>每个模块展示 <select name="HomeModuleLimit"><?php foreach (range(10,20) as $n): ?><option value="<?php echo $n; ?>" <?php echo $homeLimit === $n ? 'selected' : ''; ?>><?php echo $n; ?> 条</option><?php endforeach; ?></select></label><button class="btn btn-main" type="submit" name="save_home_modules" value="1" <?php echo !$isBound ? 'disabled' : ''; ?>><i class="fa fa-save"></i> 保存首页设置</button></div><div class="module-note"><?php echo $isBound ? '按勾选顺序展示；不足六个时仅补充当前有视频数据的分类。' : '请先绑定分类，绑定成功后才能选择首页展示分类。'; ?></div><div class="home-module-grid"><?php foreach ($activeNames as $moduleName): ?><label class="home-module-option"><input type="checkbox" name="HomeModuleNames[]" value="<?php echo htmlspecialchars($moduleName, ENT_QUOTES, 'UTF-8'); ?>" <?php echo in_array($moduleName, $selectedModules, true) ? 'checked' : ''; ?> <?php echo !$isBound ? 'disabled' : ''; ?>><span><?php echo htmlspecialchars($moduleName, ENT_QUOTES, 'UTF-8'); ?></span></label><?php endforeach; ?></div></form>
  </div></section>
  <section class="collector-card"><div class="card-head"><i class="fa fa-history"></i> 上次采集结果</div><div class="card-body"><div id="meta" class="result-meta"></div><div id="categories" class="category-grid"></div></div></section>
</main>
<div id="modal" class="modal"><div class="modal-box"><h3 id="modal-title">操作提示</h3><p id="modal-text"></p><div class="progress-track"><div id="progress-bar" class="progress-bar"></div></div><p id="progress-text" class="progress-text"></p><p class="modal-close-row"><button type="button" id="modal-close" class="btn btn-main">知道了</button></p></div></div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script>
(function(){
  var api='../../../PPQSQL/collect.php', activeNames=<?php echo json_encode($activeNames, JSON_UNESCAPED_UNICODE); ?>;
  var bound=false, collecting=false, polling=null;
  var moduleForm=$('.home-module-grid').closest('form').attr('id','home-module-form');
  if(moduleForm.length && !$('#module-limit-tip').length){ $('<div id="module-limit-tip" class="module-limit-tip" role="status"></div>').insertBefore(moduleForm.find('.home-module-grid')); }
  function updateHomeModuleLimit(){
    if(!moduleForm.length)return;
    var boxes=moduleForm.find('input[name="HomeModuleNames[]"]'), count=boxes.filter(':checked').length, atLimit=count>=6;
    boxes.not(':checked').prop('disabled',atLimit).closest('.home-module-option').toggleClass('is-disabled',atLimit);
    boxes.filter(':checked').prop('disabled',false).closest('.home-module-option').removeClass('is-disabled');
    $('#module-limit-tip').text(atLimit?'已选择 6 个首页模块；如需更换，请先取消其中一个。':'');
  }
  moduleForm.on('change','input[name="HomeModuleNames[]"]',function(){
    var boxes=moduleForm.find('input[name="HomeModuleNames[]"]');
    if(this.checked && boxes.filter(':checked').length>6)this.checked=false;
    updateHomeModuleLimit();
  });
  updateHomeModuleLimit();
  function e(v){ return $('<div>').text(v == null ? '' : v).html(); }
  function openModal(text, terminal){ $('#modal-title').text('操作提示'); $('#modal-text').text(text); $('#modal').toggleClass('terminal', !!terminal).addClass('show'); }
  function closeModal(){ if(!collecting) $('#modal').removeClass('show'); }
  function stopPoll(){ if(polling){ clearInterval(polling); polling=null; } }
  $('#modal-close').on('click', closeModal);
  function key(d,name){ return d[name]; }
  function stateOf(d){ return String(key(d,'状态') || ''); }
  function isDone(s){ return s === '完成'; }
  function isFailed(s){ return s === '失败'; }
  function calc(d){ var rows=(key(d,'分类明细')||[]).filter(function(x){ return activeNames.indexOf(x.name)!==-1; }); var actual=0, expected=0; rows.forEach(function(x){actual+=parseInt(x['实际'],10)||0; expected+=parseInt(x['期望'],10)||0;}); return {rows:rows,actual:actual,expected:expected}; }
  function render(d){
    bound=!!d.is_bound; $('#collect').prop('disabled',!bound||collecting); if(!collecting) $('#state').text(bound?'分类已绑定，可以采集资源':'请先绑定分类');
    var meta=[]; if(key(d,'状态'))meta.push('<strong>状态：'+e(key(d,'状态'))+'</strong>'); if(key(d,'总条数')!==undefined)meta.push('总条数：'+e(key(d,'总条数'))); if(key(d,'开始时间'))meta.push('开始：'+e(key(d,'开始时间'))); if(key(d,'结束时间'))meta.push('结束：'+e(key(d,'结束时间'))); $('#meta').html(meta.length?meta.join('　'):'暂无采集记录，请先绑定分类。');
    var rows=calc(d).rows; $('#categories').html(rows.length?rows.map(function(x){var note=x['备注']||'';var cls=(note==='OK'||note==='已到资源末尾'||note==='无新增内容')?'ok':'low';return '<article class="category"><div class="category-name">'+e(x.name)+'</div><div class="category-data"><span>期望 '+e(x['期望'])+'</span><span>实际 '+e(x['实际'])+'</span><span class="'+cls+'">'+e(note)+'</span></div></article>';}).join(''):'<div class="empty">当前没有可展示的视频分类结果。</div>');
  }
  function readStatus(){ return $.getJSON(api+'?t='+Date.now()); }
  function poll(){
    readStatus().done(function(d){
      render(d); if(!collecting)return; var s=stateOf(d), p=calc(d), total=key(d,'总条数')!==undefined?parseInt(key(d,'总条数'),10)||p.actual:p.actual;
      if(isDone(s)){ collecting=false; stopPoll(); $('#progress-bar').css('width','100%'); $('#progress-text').text('采集完成：共 '+total+' 条'); $('#collect').prop('disabled',false).html('<i class="fa fa-download"></i> 采集资源'); $('#state').text('分类已绑定，采集完成'); openModal('采集完成：共 '+total+' 条。',true); return; }
      if(isFailed(s)){ collecting=false; stopPoll(); $('#progress-bar').css('width','0'); $('#progress-text').text('采集失败'); $('#collect').prop('disabled',false).html('<i class="fa fa-download"></i> 采集资源'); openModal('采集失败：'+(key(d,'原因')||'请检查资源站地址或服务器日志。'),true); return; }
      var pct=p.expected?Math.min(99,Math.round(total/p.expected*100)):3; $('#progress-bar').css('width',pct+'%'); $('#progress-text').text('正在采集：'+total+' / '+(p.expected||'?')+' 条（已完成 '+p.rows.length+' 个分类）'); openModal('正在采集，请保持页面打开。',false);
    }).fail(function(){ if(collecting){ $('#progress-text').text('正在读取采集状态…'); openModal('正在读取采集状态，请保持页面打开。',false); } });
  }
  $('#bind').on('click',function(){ var b=$(this); b.prop('disabled',true).html('<i class="fa fa-spinner fa-spin"></i> 正在绑定…'); $.getJSON(api+'?action=bind').done(function(d){ if(d&&d.ok){ bound=true; $('#state').text('分类已绑定，可以采集资源'); openModal('分类绑定成功，页面将刷新以载入新的可选分类。',true); setTimeout(function(){location.reload();},900); } else openModal('绑定失败：'+((d&&d.msg)||'未知错误'),true); }).fail(function(){openModal('绑定请求失败，请检查资源站地址。',true);}).always(function(){b.prop('disabled',false).html('<i class="fa fa-sitemap"></i> 绑定分类');}); });
  $('#collect').on('click',function(){
    if(!bound){ $('#state').text('请先绑定分类'); return; } if(collecting)return;
    var per=Math.max(1,Math.min(5000,parseInt($('#per').val(),10)||1000)); collecting=true; $('#collect').prop('disabled',true).html('<i class="fa fa-spinner fa-spin"></i> 采集中…'); $('#progress-bar').css('width','2%'); $('#progress-text').text('采集已启动，正在读取状态…'); openModal('采集已启动，正在读取状态，请保持页面打开。',false);
    $.getJSON(api+'?action=collect&per='+per).done(function(d){ if(d&&d.ok===false){collecting=false;$('#collect').prop('disabled',false).html('<i class="fa fa-download"></i> 采集资源');openModal((d.msg||'采集请求失败，请检查服务器日志。'),true);return;} setTimeout(poll,500); polling=setInterval(poll,1200); }).fail(function(){ collecting=false; $('#collect').prop('disabled',false).html('<i class="fa fa-download"></i> 采集资源'); openModal('采集请求失败，请检查服务器日志。',true); });
  });
  readStatus().done(render).fail(function(){$('#state').text('无法读取采集状态');});
})();
</script>
<?php include('../Php/Admin/footer.php'); ?>
</body></html>
