{% extends "base.html" %}
{% block title %}发行SUNO作品{% endblock %}
{% block content %}
<div class="page-header">
    <h1>发行管理</h1>
</div>

<div class="tab-nav">
    <a href="{{ url_for('publish.index') }}"><i class="ph ph-paper-plane-tilt"></i>发行汽水作品</a>
    <a href="{{ url_for('publish.ai_create') }}" class="active"><i class="ph ph-waveform"></i>发行SUNO作品</a>
</div>

{% macro clip_table(clip_list, group) %}
<table class="data-table" style="margin-top:12px;">
    <thead>
        <tr>
            <th style="width:32px;">
                <input type="checkbox" class="select-all" data-group="{{ group }}" />
            </th>
            <th style="width:60px;">封面</th>
            <th>标题</th>
            <th>Persona</th>
            <th>时长</th>
            <th>Clip ID</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
    {% for c in clip_list %}
        <tr>
            <td><input type="checkbox" name="clip_id[]" value="{{ c.clip_id }}" class="clip-cb" data-group="{{ group }}" /></td>
            <td>
                {% if c.image_url %}
                <img src="{{ c.image_url }}" alt=""
                     style="width:48px; height:48px; object-fit:cover; border-radius:4px;" />
                {% else %}-{% endif %}
            </td>
            <td>{{ c.title or c.suno_title or '-' }}</td>
            <td>{{ c.persona_name or '-' }}</td>
            <td>{{ '%.1f' % c.duration if c.duration else '-' }}s</td>
            <td><code style="font-size:11px;">{{ c.clip_id[:12] }}…</code></td>
            <td>
                <div id="sync-container-{{ c.clip_id }}">
                    {% if c.soda_sync_status == 'pending' %}
                    <span class="badge badge-warn">同步中...</span>
                    {% elif c.soda_sync_status == 'success' %}
                    <button type="button" class="btn btn-sm btn-success" onclick="syncQishui('{{ c.clip_id }}')">已同步 | 重新同步</button>
                    {% elif c.soda_sync_status == 'failed' %}
                    <button type="button" class="btn btn-sm btn-danger" onclick="syncQishui('{{ c.clip_id }}')" title="{{ c.soda_sync_error or '未知错误' }}">失败重试</button>
                    <div style="font-size: 10px; color: var(--text-muted); margin-top: 4px; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ c.soda_sync_error or '' }}</div>
                    {% else %}
                    <button type="button" class="btn btn-sm" onclick="syncQishui('{{ c.clip_id }}')">同步汽水</button>
                    {% endif %}
                </div>
            </td>
        </tr>
    {% endfor %}
    </tbody>
</table>
{% endmacro %}

<div class="card-form">
    <h3>批量推送 SUNO 作品发行</h3>
    {% if clips %}
    <form method="POST" action="{{ url_for('publish.ai_create_start') }}">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <div class="form-row">
            <div class="form-group">
                <label>抖音音乐人账号</label>
                <select name="account_id" required>
                    <option value="">请选择账号</option>
                    {% for acc in accounts %}
                    <option value="{{ acc.id }}">
                        {{ acc.name }}{% if not acc.is_logged_in %} (未登录){% endif %}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="form-group">
                <label>签约模式</label>
                <select name="auth_type">
                    <option value="exclusive">独家授权（3年）</option>
                    <option value="exclusive_agent">独家代理授权</option>
                </select>
            </div>
            <div class="form-group">
                <label>授权范围（仅代理）</label>
                <select name="auth_region">
                    <option value="1">全球</option>
                    <option value="2">中国（含港澳台）</option>
                    <option value="3">仅中国大陆</option>
                </select>
            </div>
        </div>

        <div class="tab-nav" style="margin-top:8px;">
            <button type="button" class="subtab-btn active" data-tab="pending">
                待发行 (<span id="count-pending">{{ pending_clips|length }}</span>)
            </button>
            <button type="button" class="subtab-btn" data-tab="synced">
                已同步汽水 (<span id="count-synced">{{ synced_clips|length }}</span>)
            </button>
        </div>

        <div id="tab-pending" class="subtab-panel">
            {% if pending_clips %}
                {{ clip_table(pending_clips, 'pending') }}
            {% else %}
                <p style="color:#999; margin-top:12px;">没有待同步/待发行的作品。</p>
            {% endif %}
        </div>

        <div id="tab-synced" class="subtab-panel" style="display:none;">
            {% if synced_clips %}
                {{ clip_table(synced_clips, 'synced') }}
            {% else %}
                <p style="color:#999; margin-top:12px;">暂无已成功同步汽水的作品。</p>
            {% endif %}
        </div>

        <div class="form-group" style="margin-top:12px;">
            <button type="submit" class="btn btn-primary">批量推送发行</button>
            <span style="color:#999; margin-left:1rem;">
                封面自动 1440×1440；歌词必填；商用收益分成自动勾选
            </span>
        </div>
    </form>
    {% else %}
    <p style="color:#999;">暂无待发行的 SUNO 作品 clip。请先在 Suno 批次详情页勾选作品发行。</p>
    {% endif %}
</div>

<script>
// 子 tab 切换：待发行 / 已同步汽水
document.querySelectorAll('.subtab-btn').forEach(function (btn) {
    btn.addEventListener('click', function () {
        document.querySelectorAll('.subtab-btn').forEach(function (b) {
            b.classList.remove('active');
        });
        btn.classList.add('active');
        document.querySelectorAll('.subtab-panel').forEach(function (p) { p.style.display = 'none'; });
        var panel = document.getElementById('tab-' + btn.dataset.tab);
        if (panel) panel.style.display = '';
    });
});

// 每个表格各自的全选（只影响本组）
document.querySelectorAll('.select-all').forEach(function (all) {
    all.addEventListener('change', function () {
        var group = all.dataset.group;
        document.querySelectorAll('.clip-cb[data-group="' + group + '"]').forEach(function (cb) {
            cb.checked = all.checked;
        });
    });
});

function syncQishui(clipId) {
    const select = document.querySelector('select[name="account_id"]');
    const accountId = select ? select.value : '';
    if (!accountId) {
        alert('请先选择抖音音乐人账号');
        return;
    }

    const container = document.getElementById('sync-container-' + clipId);
    container.innerHTML = '<span class="badge badge-warn">同步中...</span>';

    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

    const formData = new FormData();
    formData.append('account_id', accountId);
    formData.append('csrf_token', csrfToken);

    fetch('/publish/ai-create/sync-qishui/' + clipId, {
        method: 'POST',
        headers: {
            'X-CSRF-Token': csrfToken
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.ok) {
            pollSyncStatus(clipId);
        } else {
            alert('提交失败: ' + (data.error || '未知错误'));
            restoreSyncButton(clipId, 'idle', data.error || '提交失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('提交出错，请查看控制台');
        restoreSyncButton(clipId, 'idle', '网络错误');
    });
}

function pollSyncStatus(clipId) {
    const interval = setInterval(() => {
        fetch('/publish/ai-create/sync-status/' + clipId)
        .then(response => response.json())
        .then(data => {
            if (data.ok) {
                if (data.status === 'success') {
                    clearInterval(interval);
                    updateSyncUI(clipId, 'success');
                } else if (data.status === 'failed') {
                    clearInterval(interval);
                    updateSyncUI(clipId, 'failed', data.error);
                }
            } else {
                clearInterval(interval);
                updateSyncUI(clipId, 'failed', '查询状态失败');
            }
        })
        .catch(error => {
            console.error('Poll Error:', error);
        });
    }, 5000);
}

function updateSyncUI(clipId, status, errorMsg) {
    const container = document.getElementById('sync-container-' + clipId);
    if (status === 'success') {
        container.innerHTML = '<button type="button" class="btn btn-sm btn-success" onclick="syncQishui(\'' + clipId + '\')">已同步 | 重新同步</button>';
        // 同步成功后把整行移动到「已同步汽水」tab
        moveRowToSynced(clipId);
    } else if (status === 'failed') {
        container.innerHTML = '<button type="button" class="btn btn-sm btn-danger" onclick="syncQishui(\'' + clipId + '\')" title="' + (errorMsg || '未知错误') + '">失败重试</button>' +
                              '<div style="font-size: 10px; color: var(--text-muted); margin-top: 4px; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">' + (errorMsg || '') + '</div>';
    } else {
        container.innerHTML = '<button type="button" class="btn btn-sm" onclick="syncQishui(\'' + clipId + '\')">同步汽水</button>';
    }
}

// 把同步成功的行从「待发行」表移到「已同步汽水」表，并更新计数
function moveRowToSynced(clipId) {
    const container = document.getElementById('sync-container-' + clipId);
    if (!container) return;
    const row = container.closest('tr');
    if (!row) return;
    const syncedPanel = document.getElementById('tab-synced');
    if (!syncedPanel) return;

    let tbody = syncedPanel.querySelector('table tbody');
    if (!tbody) {
        // 「已同步」tab 之前为空，没有表格——刷新页面以渲染表格更稳妥
        return;
    }
    const cb = row.querySelector('.clip-cb');
    if (cb) { cb.checked = false; cb.dataset.group = 'synced'; }
    tbody.appendChild(row);

    const cp = document.getElementById('count-pending');
    const cs = document.getElementById('count-synced');
    if (cp) cp.textContent = Math.max(0, parseInt(cp.textContent || '0', 10) - 1);
    if (cs) cs.textContent = parseInt(cs.textContent || '0', 10) + 1;
}

function restoreSyncButton(clipId, status, errorMsg) {
    updateSyncUI(clipId, status, errorMsg);
}

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('[id^="sync-container-"]').forEach(container => {
        const clipId = container.id.replace('sync-container-', '');
        const badge = container.querySelector('.badge');
        if (badge && badge.innerText.includes('同步中')) {
            pollSyncStatus(clipId);
        }
    });
});
</script>
{% endblock %}
