<?php
$pageTitle = '数据导入';
$pageCss = '/css/zsos-import.css';
require_once '../includes/header.php';

// 支持的数据类型（不含身份信息）
$types = [
    'course'   => ['name' => '课表',     'label' => '课表'],
    'score'    => ['name' => '成绩',     'label' => '成绩'],
    'progress' => ['name' => '学业进度',  'label' => '学业进度'],
    'classroom'=> ['name' => '空教室',   'label' => '空教室'],
    'exam'     => ['name' => '考试安排',  'label' => '考试安排'],
];

$currentType = trim($_GET['type'] ?? 'course');
if (!isset($types[$currentType])) $currentType = 'course';

$typeInfo = $types[$currentType];
?>

<div class="zsos-import-page">
    <!-- 顶部 -->
    <div class="import-header">
        <div class="import-back" onclick="history.back()">
            <i class="fas fa-chevron-left"></i>
        </div>
        <div class="import-title-area">
            <div class="import-main-title">知岁OS数据智能导入</div>
            <div class="import-subtitle">安全 · 可靠 · 便捷</div>
        </div>
        <div class="import-illustration"></div>
    </div>

    <!-- 导入卡片 -->
    <div class="import-card">
        <!-- 步骤1：进入知岁 -->
        <div class="import-step">
            <div class="step-header">
                <span class="step-num">1</span>
                <span class="step-text">点击下方按钮，扫码进入知岁OS获取数据密钥</span>
            </div>
            <button class="btn-primary-full" onclick="showQrcode()">
                进入知岁
            </button>
        </div>

        <!-- 步骤2：输入密钥 -->
        <div class="import-step">
            <div class="step-header">
                <span class="step-num">2</span>
                <span class="step-text">
                    输入从知岁获取的【<strong><?php echo htmlspecialchars($typeInfo['label']); ?></strong>】安全秘钥导入
                </span>
            </div>
            <textarea class="token-textarea"
                      id="tokenInput"
                      placeholder="请粘贴输入密钥更新数据"></textarea>
            <div class="btn-import-wrapper">
                <button class="btn-import" id="btnImport" onclick="doImport()">导入</button>
            </div>
        </div>
    </div>

    <!-- 说明 -->
    <div class="import-notes">
        <div class="notes-title">说明</div>
        <div class="note-item"><span class="note-num">1、</span>知岁os应用是第三方提供服务需要单独注册认证</div>
        <div class="note-item"><span class="note-num">2、</span>知岁os应用的密匙有效期只有15分钟</div>
        <div class="note-item"><span class="note-num">3、</span>知岁os应用的密匙只能使用一次</div>
        <div class="note-item"><span class="note-num">4、</span>数据仅本地临时缓存，不永久存储，超过7天需重新同步更新</div>
        <div class="note-item"><span class="note-num">5、</span>建议每周同步一次知岁OS保持数据最新</div>
    </div>
</div>

<!-- 小程序码弹窗 -->
<div id="qrcode-modal" onclick="closeQrcode(event)" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);z-index:9999;display:none;align-items:center;justify-content:center;">
    <div style="background:white;border-radius:16px;padding:24px;text-align:center;max-width:300px;width:85%;position:relative;">
        <div style="font-size:16px;font-weight:600;color:#1f2937;margin-bottom:4px;">知岁OS小程序</div>
        <div style="font-size:13px;color:#6b7280;margin-bottom:16px;">微信扫码进入知岁OS，获取数据密钥</div>
        <div style="width:220px;height:220px;margin:0 auto;border-radius:8px;overflow:hidden;background:#f3f4f6;">
            <img src="<?php echo SITE_URL; ?>/image/zsos.jpg" style="width:100%;height:100%;object-fit:contain;" alt="知岁OS小程序码">
        </div>
        <div style="font-size:12px;color:#9ca3af;margin-top:12px;">长按识别小程序码，或在微信搜索「知岁OS」</div>
        <div onclick="closeQrcode(event)" style="position:absolute;top:8px;right:12px;width:28px;height:28px;border-radius:50%;background:#f3f4f6;display:flex;align-items:center;justify-content:center;cursor:pointer;">
            <i class="fas fa-times" style="font-size:14px;color:#6b7280;"></i>
        </div>
    </div>
</div>

<script>
function showQrcode() {
    var modal = document.getElementById('qrcode-modal');
    modal.style.display = 'flex';
}

function closeQrcode(e) {
    if (e.target === document.getElementById('qrcode-modal') || e.target.closest('[onclick="closeQrcode(event)"]')) {
        document.getElementById('qrcode-modal').style.display = 'none';
    }
}

var importType = '<?php echo $currentType; ?>';
var typeNameMap = {
    'course': '课表',
    'score': '成绩',
    'progress': '学业进度',
    'classroom': '空教室',
    'exam': '考试安排'
};

function doImport() {
    var token = document.getElementById('tokenInput').value.trim();
    if (!token) {
        alert('请先粘贴输入从知岁OS获取的安全密钥');
        return;
    }

    var btn = document.getElementById('btnImport');
    btn.classList.add('loading');
    btn.textContent = '导入中...';

    fetch('<?php echo SITE_URL; ?>/api/zsos.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=sync&token=' + encodeURIComponent(token) + '&type=' + importType
    })
    .then(function(res) {
        return res.text().then(function(text) {
            // 容错：剥离可能混入的非JSON内容（PHP warning等），找到第一个{开始解析
            var jsonStart = text.indexOf('{');
            if (jsonStart === -1) {
                throw new Error('服务器响应异常（非JSON格式）');
            }
            var jsonStr = text.substring(jsonStart);
            try { return JSON.parse(jsonStr); }
            catch(e) { throw new Error('JSON解析失败: ' + e.message); }
        });
    })
    .then(function(data) {
        if (data.code === 1) {
            alert((typeNameMap[importType] || '数据') + '同步成功');
            // 根据数据类型跳转到对应页面，确保刷新获取最新数据
            var pageMap = {
                'course': '<?php echo SITE_URL; ?>/pages/schedule.php',
                'score': '<?php echo SITE_URL; ?>/pages/grades.php',
                'progress': '<?php echo SITE_URL; ?>/pages/academic.php',
                'classroom': '<?php echo SITE_URL; ?>/pages/academic.php',
                'exam': '<?php echo SITE_URL; ?>/pages/academic.php',
            };
            var targetPage = pageMap[importType] || '<?php echo SITE_URL; ?>/index.php';
            location.href = targetPage;
        } else {
            alert(data.msg || '导入失败，请检查密钥是否正确');
            btn.classList.remove('loading');
            btn.textContent = '导入';
        }
    })
    .catch(function(err) {
        alert(err.message || '网络错误，请稍后重试');
        btn.classList.remove('loading');
        btn.textContent = '导入';
    });
}
</script>

<?php require_once '../includes/footer.php'; ?>
