<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */



    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $ajaxAct = $_POST['ajax_action'];

        if ($ajaxAct === 'delete') {
            $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
            $ids = json_decode($idsRaw, true);
            if (!is_array($ids)) { $ids = []; }
            $ids = array_map('intval', $ids);
            if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择要删除的项']); exit; }
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $db->query("DELETE FROM {$db->table('video')} WHERE id IN ($placeholders)", $ids);
            echo json_encode(['code'=>200,'msg'=>'已删除 '.count($ids).' 项']); exit;
        }

        if ($ajaxAct === 'show') {
            $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
            $ids = json_decode($idsRaw, true);
            if (!is_array($ids)) { $ids = []; }
            $ids = array_map('intval', $ids);
            if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择']); exit; }
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $db->query("UPDATE {$db->table('video')} SET status=1, update_time=? WHERE id IN ($placeholders)", array_merge([time()], $ids));
            echo json_encode(['code'=>200,'msg'=>'已显示']); exit;
        }

        if ($ajaxAct === 'hide') {
            $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
            $ids = json_decode($idsRaw, true);
            if (!is_array($ids)) { $ids = []; }
            $ids = array_map('intval', $ids);
            if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择']); exit; }
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $db->query("UPDATE {$db->table('video')} SET status=0, update_time=? WHERE id IN ($placeholders)", array_merge([time()], $ids));
            echo json_encode(['code'=>200,'msg'=>'已隐藏']); exit;
        }
    }


$action = isset($_GET['action']) ? $_GET['action'] : 'list';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'save') {
        $id = intval($_POST['id']);
        $data = [
            'channel_id' => intval((isset($_POST['channel_id']) ? $_POST['channel_id'] : 0)),
            'title' => trim((isset($_POST['title']) ? $_POST['title'] : '')),
            'litpic' => trim((isset($_POST['litpic']) ? $_POST['litpic'] : '')),
            'video_path' => trim((isset($_POST['video_path']) ? $_POST['video_path'] : '')),
            'video_duration' => intval((isset($_POST['video_duration']) ? $_POST['video_duration'] : 0)),
            'video_cover' => trim((isset($_POST['video_cover']) ? $_POST['video_cover'] : '')),
            'seo_title' => trim((isset($_POST['seo_title']) ? $_POST['seo_title'] : '')),
            'seo_keywords' => trim((isset($_POST['seo_keywords']) ? $_POST['seo_keywords'] : '')),
            'seo_description' => trim((isset($_POST['seo_description']) ? $_POST['seo_description'] : '')),
            'content' => ((isset($_POST['content']) ? $_POST['content'] : '')),
            'sort_order' => intval((isset($_POST['sort_order']) ? $_POST['sort_order'] : 100)),
            'status' => isset($_POST['status']) ? 1 : 0,
            'update_time' => time()
        ];
        if ($id > 0) {
            $db->update('video', $data, 'id = ?', [$id]);
            addLog('修改', '视频管理', '修改视频 ' . $data['title']);
        } else {
            $data['create_time'] = time();
            $db->insert('video', $data);
            addLog('添加', '视频管理', '添加视频 ' . $data['title']);
        }
        echo '<script>alert("保存成功");location.href="?act=video"</script>';
        exit;
    }
    if ($action === 'delete') {
        $id = intval($_POST['id']);
        $row = $db->fetch("SELECT title FROM {$db->table('video')} WHERE id = ?", [$id]);
        $db->delete('video', 'id = ?', [$id]);
        addLog('删除', '视频管理', '删除视频 ' . ((isset($row['title']) ? $row['title'] : $id)));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
    if ($action === 'upload') {
        header('Content-Type: application/json');
        $type = isset($_POST['upload_type']) ? $_POST['upload_type'] : 'video';
        $allowed = $type === 'video' ? ['mp4', 'webm', 'ogg', 'avi', 'mov', 'mkv'] : ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            echo json_encode(['code' => 400, 'msg' => '上传失败']);
            exit;
        }
        $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed)) {
            echo json_encode(['code' => 400, 'msg' => '不支持的文件类型']);
            exit;
        }
        $dir = dirname(__DIR__) . '/uploads/' . ($type === 'video' ? 'video' : 'litpic') . '/';
        if (!is_dir($dir)) { mkdir($dir, 0755, true); }
        $filename = uniqid(mt_rand()) . '.' . $ext;
        $filepath = $dir . $filename;
        if (move_uploaded_file($_FILES['file']['tmp_name'], $filepath)) {
            $url = '/uploads/' . ($type === 'video' ? 'video' : 'litpic') . '/' . $filename;
            echo json_encode(['code' => 200, 'msg' => '上传成功', 'url' => $url]);
        } else {
            echo json_encode(['code' => 400, 'msg' => '保存失败']);
        }
        exit;
    }
}

if ($action === 'list') {
    $videoChannels = $db->fetchAll("SELECT id, channel_name FROM {$db->table('channel')} WHERE channel_type = 7 ORDER BY list_order ASC");
    $channelMap = [];
    foreach ($videoChannels as $ch) { $channelMap[$ch['id']] = $ch['channel_name']; }
    $videos = $db->fetchAll("SELECT * FROM {$db->table('video')} ORDER BY sort_order ASC");
    $totalVideo = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('video')}")['cnt'];
    $activeVideo = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('video')} WHERE status = 1")['cnt'];
    ?>
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon" style="background:#eff6ff;color:#2563eb;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $totalVideo; ?></div><div class="stat-label">视频总数</div></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background:#ecfdf5;color:#10b981;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $activeVideo; ?></div><div class="stat-label">展示中</div></div>
        </div>
    </div>
    <div class="filter-bar">
        <a href="?act=video&action=add" class="btn btn-primary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> 添加视频</a>
    </div>
    <div class="content-card">
        <?php if (empty($videos)): ?>
        <div class="empty-state">
            <div class="empty-icon"><svg style="width:40px;height:40px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M16 16v1a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2m5.66 0H14a2 2 0 0 1 2 2v3.34l1 1L23 7v10"/><line x1="1" y1="1" x2="23" y2="23"/></svg></div>
            <h3>暂无视频</h3>
            <p>添加第一个视频</p>
            <a href="?act=video&action=add" class="btn btn-primary">添加视频</a>
        </div>
        <?php else: ?>
        <table class="data-table">
            <thead>
                <tr><th style="width:50px;">ID</th><th style="width:80px;">封面</th><th>标题</th><th style="width:120px;">栏目</th><th style="width:80px;">时长</th><th style="width:100px;">状态</th><th style="width:250px;">操作</th></tr>
            </thead>
            <tbody>
                <?php foreach ($videos as $item): ?>
                <td style="text-align:center;"><input type="checkbox" class="row-check" value="<?php echo $item['id']; ?>" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></td><tr>
                    <td class="id-cell"><?php echo $item['id']; ?></td>
                    <td>
                        <?php if (!empty($item['litpic'])): ?>
                        <img src="<?php echo htmlspecialchars($item['litpic']); ?>" style="width:60px;height:36px;object-fit:cover;border-radius:4px;">
                        <?php else: ?>
                        <div style="width:60px;height:36px;background:#f1f5f9;border-radius:4px;display:flex;align-items:center;justify-content:center;">
                            <svg style="width:20px;height:20px;color:#cbd5e1;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg>
                        </div>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div style="font-weight:600;color:#334155;"><?php echo htmlspecialchars($item['title']); ?></div>
                        <?php if (!empty($item['video_path'])): ?>
                        <div style="font-size:12px;color:#64748b;margin-top:2px;"><?php echo htmlspecialchars($item['video_path']); ?></div>
                        <?php endif; ?>
                    </td>
                    <td style="color:#64748b;font-size:13px;"><?php echo isset($channelMap[$item['channel_id']]) ? htmlspecialchars($channelMap[$item['channel_id']]) : '-'; ?></td>
                    <td style="font-family:monospace;color:#64748b;"><?php echo !empty($item['video_duration']) ? intval($item['video_duration']) . '秒' : '-'; ?></td>
                    <td>
                        <?php if ($item['status']): ?>
                        <span class="badge badge-success">显示</span>
                        <?php else: ?>
                        <span class="badge badge-secondary">隐藏</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div class="btn-group">
                            <a href="?act=video&action=edit&id=<?php echo $item['id']; ?>" class="btn btn-primary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg> 编辑</a>
                            <a href="javascript:delVideo(<?php echo $item['id']; ?>);" class="btn btn-ghost" style="color:#EF4444;"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg> 删除</a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
    <script>
    function delVideo(id) { if (confirm('确定删除?')) { fetch('?act=video&action=delete', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id}).then(r=>r.json()).then(d=>{alert(d.msg);if(d.code==200)location.reload();}); } }
    lucide.createIcons();
    
    function toggleCheckAll(cb) { document.querySelectorAll('.row-check').forEach(function(c){c.checked=cb.checked;}); }
    function getSelectedIds() { var ids=[]; document.querySelectorAll('.row-check:checked').forEach(function(c){ids.push(c.value);}); return ids; }
    function batchAction(action) {
        var ids = getSelectedIds();
        if (ids.length === 0) { alert('请先勾选要操作的项'); return; }
        if (action === 'delete') {
            if (!confirm('确定删除选中的 ' + ids.length + ' 项？')) return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=video&action=batch', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                try { var d = JSON.parse(xhr.responseText); alert(d.msg||'操作完成'); if(d.code==200) location.reload(); }
                catch(e) { alert('JSON解析失败'); }
            }
        };
        xhr.send('ajax_action=' + action + '&ids=' + encodeURIComponent(JSON.stringify(ids)));
    }

</script>
    <?php
}

if ($action === 'add' || $action === 'edit') {
    $defaults = ['id'=>'','channel_id'=>0,'title'=>'','litpic'=>'','video_path'=>'','video_duration'=>'','video_cover'=>'','seo_title'=>'','seo_keywords'=>'','seo_description'=>'','content'=>'','sort_order'=>100,'status'=>1];
    if ($action === 'add' && isset($_GET['channel_id'])) {
        $defaults['channel_id'] = intval($_GET['channel_id']);
    }
    $editData = $defaults;
    if ($action === 'edit' && isset($_GET['id'])) {
        $row = $db->fetch("SELECT * FROM {$db->table('video')} WHERE id = ?", [intval($_GET['id'])]);
        if ($row) { $editData = array_merge($editData, $row); }
    }
    $isEdit = $action === 'edit';
    $videoChannels = $db->fetchAll("SELECT id, channel_name, parent_id FROM {$db->table('channel')} WHERE channel_type = 7 ORDER BY list_order ASC");

    function renderVideoChannelSelect($channels, $parentId = 0, $selected = 0, $depth = 0) {
        foreach ($channels as $ch) {
            if ($ch['parent_id'] == $parentId) {
                echo '<option value="' . $ch['id'] . '"' . ($selected == $ch['id'] ? ' selected' : '') . '>' . str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $depth) . $ch['channel_name'] . '</option>';
                renderVideoChannelSelect($channels, $ch['id'], $selected, $depth + 1);
            }
        }
    }

    $releaseTime = !empty($editData['create_time']) ? $editData['create_time'] : time();
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></div>
                <div><h1><?php echo $isEdit ? '编辑视频' : '添加视频'; ?></h1><p style="font-size:12px;color:#64748b;margin:0;">填写视频信息</p></div>
            </div>
            <div class="page-actions"><a href="?act=video" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <form method="post" action="?act=video&action=save" id="videoForm">
            <input type="hidden" name="id" value="<?php echo $editData['id']; ?>">
            <div style="display:grid;grid-template-columns:820px 340px;gap:20px;align-items:start;">
                <div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg> 基本信息</div>
                        <div class="form-section-body">
                            <div class="form-group"><label>视频标题 <span class="required">*</span></label><input type="text" name="title" class="form-control" value="<?php echo htmlspecialchars($editData['title']); ?>" placeholder="请输入视频标题" required></div>
                            <div class="form-group">
                                <label>所属栏目 <span class="required">*</span></label>
                                <select name="channel_id" class="form-control" required>
                                    <option value="">请选择栏目</option>
                                    <?php renderVideoChannelSelect($videoChannels, 0, $editData['channel_id']); ?>
                                </select>
                            </div>
                            <div class="form-row">
                                <div class="form-group"><label>时长（秒）</label><input type="number" name="video_duration" class="form-control" value="<?php echo intval($editData['video_duration']); ?>" min="0" placeholder="如：120"></div>
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg> 视频文件</div>
                        <div class="form-section-body">
                            <div class="form-group"><label>视频地址URL</label>
                                <input type="text" name="video_path" id="videoPath" class="form-control" value="<?php echo htmlspecialchars($editData['video_path']); ?>" placeholder="直接输入视频URL，支持 mp4/webm/ogg 等格式">
                                <div style="margin-top:8px;display:flex;gap:8px;align-items:center;">
                                    <button type="button" class="btn btn-secondary" onclick="document.getElementById('videoFileInput').click();"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg> 本地上传视频</button>
                                    <span id="videoUploadStatus" style="font-size:12px;color:#94a3b8;align-self:center;"></span>
                                </div>
                                <input type="file" id="videoFileInput" accept="video/*" style="display:none;" onchange="handleVideoUpload(this)">
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="9" y1="21" x2="9" y2="9"/></svg> 视频介绍</div>
                        <div class="form-section-body cms-ueditor-wrap">
                            <script src="/public/ueditor/ueditor.config.js"></script>
                            <script src="/public/ueditor/ueditor.all.min.js"></script>
                            <script type="text/plain" id="video_content_editor" name="content" style="width:780px;height:360px;"></script>
                            <script>
                            (function(){
                                var editorContent = <?php echo json_encode(isset($editData['content']) ? $editData['content'] : '', JSON_UNESCAPED_UNICODE); ?>;
                                function initEditor(){
                                    if (!window.UE) { alert('UEditor资源加载失败'); return; }
                                    try { if (UE.instants && UE.instants['video_content_editor']) UE.instants['video_content_editor'].destroy(); } catch(e) {}
                                    window.videoContentEditor = UE.getEditor('video_content_editor', {
                                        initialFrameWidth: 780,
                                        initialFrameHeight: 360,
                                        autoHeightEnabled: false,
                                        autoFloatEnabled: false,
                                        scaleEnabled: false,
                                        serverUrl: '/public/ueditor/php/controller.php'
                                    });
                                    videoContentEditor.ready(function(){ videoContentEditor.setContent(editorContent || ''); });
                                }
                                if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', initEditor); else setTimeout(initEditor, 0);
                            })();
                            </script>
                            <style>
                            .cms-ueditor-wrap{overflow:visible !important;padding:20px !important;box-sizing:border-box;height:500px !important;margin:0 !important;display:block;}
                            .cms-ueditor-wrap .edui-editor{display:block !important;width:780px !important;max-width:780px !important;box-sizing:border-box;}
                            .cms-ueditor-wrap .edui-editor-toolbarbox,.cms-ueditor-wrap .edui-editor-iframeholder{width:780px !important;max-width:780px !important;box-sizing:border-box;}
                            </style>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg> 封面图片</div>
                        <div class="form-section-body">
                            <div id="litpicPreview" class="upload-preview" style="cursor:pointer;" onclick="document.getElementById('litpicUpload').click();">
                                <?php if (!empty($editData['litpic'])): ?>
                                <img src="<?php echo htmlspecialchars($editData['litpic']); ?>" style="width:100%;height:100%;object-fit:cover;">
                                <?php else: ?>
                                <div class="placeholder"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg><span style="font-size:12px;color:#94a3b8;margin-top:4px;">点击上传本地图片</span></div>
                                <?php endif; ?>
                            </div>
                            <input type="file" id="litpicUpload" accept="image/*" style="display:none;" onchange="handleLitpicUpload(this)">
                            <input type="text" name="litpic" id="litpicInput" value="<?php echo htmlspecialchars($editData['litpic']); ?>" placeholder="或直接输入图片URL" style="width:100%;margin-top:10px;" class="form-control">
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg> 显示设置</div>
                        <div class="form-section-body">
                            <div class="form-group"><label>排序</label><input type="number" name="sort_order" class="form-control" value="<?php echo $editData['sort_order']; ?>" min="0"></div>
                            <div class="form-group">
                                <label style="display:flex;align-items:center;gap:12px;cursor:pointer;padding-top:8px;">
                                    <input type="checkbox" name="status" value="1" <?php echo $editData['status'] ? 'checked' : ''; ?> id="stToggle" style="display:none;">
                                    <div id="stSwitch" style="width:44px;height:24px;background:<?php echo $editData['status'] ? '#10b981' : '#cbd5e1'; ?>;border-radius:12px;position:relative;transition:all 0.2s;"><div style="width:18px;height:18px;background:#fff;border-radius:50%;position:absolute;top:3px;left:<?php echo $editData['status'] ? '23px' : '3px'; ?>;transition:all 0.2s;"></div></div>
                                    <span id="stLabel" style="font-weight:500;color:<?php echo $editData['status'] ? '#10b981' : '#64748b'; ?>;"><?php echo $editData['status'] ? '显示' : '隐藏'; ?></span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-actions" style="background:#fff;padding:20px;border-radius:8px;margin-top:20px;">
                <button type="submit" class="btn btn-success btn-lg"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> <?php echo $isEdit ? '保存' : '发布'; ?></button>
                <a href="?act=video" class="btn btn-secondary btn-lg">取消</a>
            </div>
        </form>
    </div>
    <script>
    document.getElementById('stToggle').addEventListener('change', function() {
        var sw = document.getElementById('stSwitch');
        var lb = document.getElementById('stLabel');
        if (this.checked) { sw.style.background = '#10b981'; sw.querySelector('div').style.left = '23px'; lb.textContent = '显示'; lb.style.color = '#10b981'; }
        else { sw.style.background = '#cbd5e1'; sw.querySelector('div').style.left = '3px'; lb.textContent = '隐藏'; lb.style.color = '#64748b'; }
    });
    function handleLitpicUpload(input) {
        if (!input.files || !input.files[0]) return;
        var formData = new FormData();
        formData.append('file', input.files[0]);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=upload', true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                var d = JSON.parse(xhr.responseText);
                if (d.code === 200) {
                    document.getElementById('litpicInput').value = d.data.url;
                    var preview = document.getElementById('litpicPreview');
                    preview.innerHTML = '<img src="' + d.data.url + '" style="width:100%;height:100%;object-fit:cover;">';
                } else { alert(d.msg); }
            } else { alert('上传失败'); }
        };
        xhr.send(formData);
    }
    function handleVideoUpload(input) {
        if (!input.files || !input.files[0]) return;
        var file = input.files[0];
        document.getElementById('videoUploadStatus').textContent = '正在上传: ' + file.name + '...';
        var formData = new FormData();
        formData.append('file', file);
        formData.append('upload_type', 'video');
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=upload', true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                var d = JSON.parse(xhr.responseText);
                if (d.code === 200) {
                    document.getElementById('videoPath').value = d.data.url;
                    document.getElementById('videoUploadStatus').textContent = '上传成功: ' + file.name;
                } else {
                    alert(d.msg);
                    document.getElementById('videoUploadStatus').textContent = '';
                }
            } else { alert('上传失败'); document.getElementById('videoUploadStatus').textContent = ''; }
        };
        xhr.onerror = function() { alert('上传失败'); document.getElementById('videoUploadStatus').textContent = ''; };
        xhr.send(formData);
    }
    lucide.createIcons();
    
    function toggleCheckAll(cb) { document.querySelectorAll('.row-check').forEach(function(c){c.checked=cb.checked;}); }
    function getSelectedIds() { var ids=[]; document.querySelectorAll('.row-check:checked').forEach(function(c){ids.push(c.value);}); return ids; }
    function batchAction(action) {
        var ids = getSelectedIds();
        if (ids.length === 0) { alert('请先勾选要操作的项'); return; }
        if (action === 'delete') {
            if (!confirm('确定删除选中的 ' + ids.length + ' 项？')) return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=video&action=batch', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                try { var d = JSON.parse(xhr.responseText); alert(d.msg||'操作完成'); if(d.code==200) location.reload(); }
                catch(e) { alert('JSON解析失败'); }
            }
        };
        xhr.send('ajax_action=' + action + '&ids=' + encodeURIComponent(JSON.stringify(ids)));
    }

</script>
    <?php
}
?>

