{% extends "service_manage/base.html" %}

{% block title %}服务授权{% endblock %}
{% block breadcrumb %}服务授权{% endblock %}

{% block extra_css %}
<style>
    .steps-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px; margin-bottom: 24px; }
    .step-card { background: #fff; border-radius: 12px; padding: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); border: 1px solid var(--gray-200); position: relative; }
    .step-number { position: absolute; top: -12px; left: 20px; background: var(--primary); color: #fff; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 14px; }
    .step-title { font-size: 16px; font-weight: 700; color: var(--gray-900); margin-bottom: 16px; padding-top: 8px; }
    .step-actions { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 12px; }
    .btn-action { display: inline-flex; align-items: center; gap: 6px; padding: 10px 16px; border-radius: 8px; font-size: 14px; font-weight: 500; cursor: pointer; border: none; transition: all 0.2s; }
    .btn-primary { background: var(--primary); color: #fff; }
    .btn-primary:hover { background: var(--primary-hover); }
    .btn-outline { background: #fff; color: var(--gray-700); border: 1px solid var(--gray-300); }
    .btn-outline:hover { background: var(--gray-50); border-color: var(--gray-400); }
    .step-desc { font-size: 13px; color: var(--gray-500); line-height: 1.6; }
    .form-group { margin-bottom: 16px; }
    .form-label { display: block; font-size: 14px; font-weight: 600; color: var(--gray-700); margin-bottom: 6px; }
    .form-label .required { color: var(--red); margin-left: 2px; }
    .form-input { width: 100%; padding: 10px 12px; border: 1px solid var(--gray-300); border-radius: 8px; font-size: 14px; color: var(--gray-900); background: #fff; transition: border-color 0.2s, box-shadow 0.2s; }
    .form-input:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-light); }
    .form-input::placeholder { color: var(--gray-400); }
    textarea.form-input { min-height: 80px; resize: vertical; }
    .btn-save { display: inline-flex; align-items: center; gap: 6px; background: var(--primary); color: #fff; border: none; padding: 10px 24px; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; }
    .btn-save:hover { background: var(--primary-hover); }
    .upload-area { border: 2px dashed var(--gray-300); border-radius: 8px; padding: 20px; text-align: center; cursor: pointer; transition: border-color 0.2s, background 0.2s; }
    .upload-area:hover { border-color: var(--primary); background: var(--primary-light); }
    .upload-icon { font-size: 24px; margin-bottom: 8px; }
    .upload-text { font-size: 14px; color: var(--gray-500); }
    .upload-hint { font-size: 12px; color: var(--gray-400); margin-top: 4px; }
    @media screen and (max-width: 768px) { .steps-container { grid-template-columns: 1fr; } }
</style>
{% endblock %}
{% block content %}
<div class="section-head"><h2 class="section-title">🔑 服务授权</h2></div>
<div class="steps-container">
    <div class="step-card">
        <div class="step-number">1</div>
        <div class="step-title">申请服务授权</div>
        <div class="step-actions">
            <button class="btn-action btn-outline" onclick="handleDownload('activation')">📥 下载激活文件</button>
            <button class="btn-action btn-primary" onclick="document.getElementById('auth-file').click()">📤 上传授权文件</button>
            <input type="file" id="auth-file" style="display:none" accept=".lic,.key,.dat" onchange="handleAuthUpload(this)">
        </div>
        <div class="upload-area" onclick="document.getElementById('auth-file').click()">
            <div class="upload-icon">📁</div>
            <div class="upload-text">点击或拖拽上传授权文件</div>
            <div class="upload-hint">支持 .lic / .key / .dat 格式</div>
        </div>
        <div class="step-desc" style="margin-top: 12px;">下载激活文件后发送给厂商获取授权，收到授权文件后上传即可完成授权申请。</div>
    </div>
    <div class="step-card">
        <div class="step-number">2</div>
        <div class="step-title">填写项目信息</div>
        <form id="project-form" onsubmit="handleSaveProject(event)">
            <div class="form-group"><label class="form-label">项目销售 <span class="required">*</span></label><input type="text" id="pj-sales" class="form-input" placeholder="请输入项目的销售" required></div>
            <div class="form-group"><label class="form-label">部署人员 <span class="required">*</span></label><input type="text" id="pj-deployer" class="form-input" placeholder="请输入项目部署或更新人员" required></div>
            <div class="form-group"><label class="form-label">下单时间 <span class="required">*</span></label><input type="datetime-local" id="pj-order-time" class="form-input" required></div>
            <div class="form-group"><label class="form-label">服务器密码 <span class="required">*</span></label><input type="password" id="pj-password" class="form-input" placeholder="请输入服务器密码" required></div>
            <div class="form-group"><label class="form-label">项目概述 <span class="required">*</span></label><textarea id="pj-overview" class="form-input" placeholder="请输入项目概述" required></textarea></div>
            <button type="submit" id="pj-save" class="btn-save">💾 保存</button>
        </form>
    </div>
    <div class="step-card">
        <div class="step-number">3</div>
        <div class="step-title">填写并提交部署视图</div>
        <div class="step-actions"><button class="btn-action btn-outline" onclick="handleDownload('deploy-view')">📥 下载部署视图</button></div>
        <div class="upload-area" onclick="document.getElementById('deploy-file').click()">
            <div class="upload-icon">📄</div>
            <div class="upload-text">点击上传已填写的部署视图</div>
            <div class="upload-hint">支持 .xlsx / .xls / .pdf 格式</div>
        </div>
        <input type="file" id="deploy-file" style="display:none" accept=".xlsx,.xls,.pdf" onchange="handleDeployUpload(this)">
        <div class="step-desc" style="margin-top: 12px;">下载部署视图模板，填写后上传提交。</div>
    </div>
    <div class="step-card">
        <div class="step-number">4</div>
        <div class="step-title">填写并提交自检文档</div>
        <div class="step-actions"><button class="btn-action btn-outline" onclick="handleDownload('self-check')">📥 下载自检文档</button></div>
        <div class="upload-area" onclick="document.getElementById('check-file').click()">
            <div class="upload-icon">📋</div>
            <div class="upload-text">点击上传已填写的自检文档</div>
            <div class="upload-hint">支持 .docx / .doc / .pdf 格式</div>
        </div>
        <input type="file" id="check-file" style="display:none" accept=".docx,.doc,.pdf" onchange="handleCheckUpload(this)">
        <div class="step-desc" style="margin-top: 12px;">下载自检文档模板，填写后上传提交。</div>
    </div>
</div>
{% endblock %}
{% block extra_js %}
<script>
// ============================================================
// 通用工具
// ============================================================
function _errMsg(d) {
    return (d && d.error && d.error.message) ? d.error.message : '请求失败';
}

function _readFile(f) {
    return new Promise(function(resolve, reject) {
        var reader = new FileReader();
        reader.onload = function() { resolve(reader.result); };
        reader.onerror = function() { reject(new Error('文件读取失败')); };
        reader.readAsDataURL(f);
    });
}

function _download(dataUrl, filename) {
    var a = document.createElement('a');
    a.href = dataUrl;
    a.download = filename || 'download';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

function _downloadBlob(data, filename) {
    var blob = new Blob([data], {type: 'application/octet-stream'});
    var url = URL.createObjectURL(blob);
    _download(url, filename);
    setTimeout(function() { URL.revokeObjectURL(url); }, 1000);
}

// ============================================================
// 步骤 1：申请服务授权
// ============================================================
function handleDownload(type) {
    var urlMap = {
        'activation': '/api/service-manage/license/download',
        'deploy-view': '/api/service-manage/deploy-view/download',
        'self-check': '/api/service-manage/self-check/download'
    };
    var url = urlMap[type];
    if (!url) return;

    fetch(url, {credentials: 'include'})
        .then(function(resp) {
            if (resp.status === 401 || resp.status === 403) {
                resp.json().then(function(d) {
                    window.location.href = '/login';
                });
                throw new Error('未登录或权限不足');
            }
            if (!resp.ok) {
                return resp.json().then(function(d) { throw new Error(_errMsg(d)); });
            }
            var disposition = resp.headers.get('Content-Disposition') || '';
            var match = /filename[*]=UTF-8''([^;]+)|filename="?([^";]+)"?/.exec(disposition);
            var name = null;
            if (match) name = decodeURIComponent((match[1] || match[2] || '').replace(/\+/g, ' '));
            return resp.blob().then(function(blob) {
                _downloadBlob(blob, name || 'download');
            });
        })
        .then(function() {
            showToast('文件下载完成', 'success');
        })
        .catch(function(e) {
            if (e.message !== '未登录或权限不足') showToast('下载失败：' + e.message, 'error');
        });
}

function handleAuthUpload(input) {
    var file = input.files && input.files[0];
    if (!file) return;
    _uploadFile('/api/service-manage/license/upload', file, '授权文件上传成功', 'handleAuthUpload', input);
}

// ============================================================
// 通用上传
// ============================================================
function _uploadFile(url, file, okMsg, fnName, input) {
    var form = new FormData();
    form.append('file', file);
    fetch(url, {method: 'POST', body: form, credentials: 'include'})
        .then(function(resp) {
            return resp.json().then(function(d) {
                if (!resp.ok) throw new Error(_errMsg(d));
                return d;
            });
        })
        .then(function(d) {
            if (d.success) {
                showToast(okMsg, 'success');
            } else {
                throw new Error(d.message || '上传失败');
            }
        })
        .catch(function(e) {
            showToast('上传失败：' + e.message, 'error');
        })
        .finally(function() {
            if (input) input.value = '';
        });
}

// ============================================================
// 步骤 2：项目信息
// ============================================================
function handleSaveProject(e) {
    e.preventDefault();
    var btn = document.getElementById('pj-save');
    btn.disabled = true;
    btn.textContent = '保存中...';

    var data = {
        salesPeople: document.getElementById('pj-sales').value.trim(),
        deployer: document.getElementById('pj-deployer').value.trim(),
        orderTime: document.getElementById('pj-order-time').value,
        serverPassword: document.getElementById('pj-password').value,
        projectOverview: document.getElementById('pj-overview').value.trim()
    };

    fetch('/api/service-manage/project', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        credentials: 'include',
        body: JSON.stringify(data)
    })
        .then(function(resp) {
            return resp.json().then(function(d) {
                if (!resp.ok) throw new Error(_errMsg(d));
                return d;
            });
        })
        .then(function(d) {
            if (d.success) {
                showToast('项目信息保存成功', 'success');
                document.getElementById('pj-password').value = '';
            } else {
                throw new Error(d.message || '保存失败');
            }
        })
        .catch(function(e) {
            showToast('保存失败：' + e.message, 'error');
        })
        .finally(function() {
            btn.disabled = false;
            btn.textContent = '💾 保存';
        });
}

function loadProject() {
    fetch('/api/service-manage/project', {credentials: 'include'})
        .then(function(resp) { return resp.json(); })
        .then(function(d) {
            if (!d.success || !d.project) return;
            var p = d.project;
            document.getElementById('pj-sales').value = p.salesPeople || '';
            document.getElementById('pj-deployer').value = p.deployer || '';
            var t = p.orderTime || '';
            // ISO 秒级时间转 datetime-local 输入格式
            if (t.length >= 16) {
                document.getElementById('pj-order-time').value = t.slice(0, 16);
            } else {
                document.getElementById('pj-order-time').value = t;
            }
            document.getElementById('pj-overview').value = p.projectOverview || '';
            if (p.has_password) {
                document.getElementById('pj-password').placeholder = '服务器密码已保存（留空则不修改）';
                document.getElementById('pj-password').removeAttribute('required');
            } else {
                document.getElementById('pj-password').placeholder = '请输入服务器密码';
                document.getElementById('pj-password').setAttribute('required', 'required');
            }
        })
        .catch(function() {});
}

// ============================================================
// 步骤 3 / 4：部署视图 / 自检文档上传
// ============================================================
function handleDeployUpload(input) {
    var file = input.files && input.files[0];
    if (!file) return;
    _uploadFile('/api/service-manage/deploy-view/upload', file, '部署视图上传成功', 'handleDeployUpload', input);
}

function handleCheckUpload(input) {
    var file = input.files && input.files[0];
    if (!file) return;
    _uploadFile('/api/service-manage/self-check/upload', file, '自检文档上传成功', 'handleCheckUpload', input);
}

// 页面加载时回填已保存的项目信息
document.addEventListener('DOMContentLoaded', loadProject);
</script>
{% endblock %}