{include file="app/manage/view/index/emlog_nav"}

<h1 class="page-title">
    <i class="fas fa-robot"></i>
    AI 开放平台
</h1>

<div class="row">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-header">
                <span class="text-muted"><i class="fas fa-info-circle"></i> 统一管理兼容 OpenAI 协议的大模型（文本对话 / 图像生成 / Embedding / Rerank）</span>
            </div>
            <div class="card-body">
                <!-- 全局设置 -->
                <form id="aiGlobalForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">默认对话模型 <span class="text-danger">*</span></label>
                                <select id="ai_chat" name="ai_chat" class="form-control">
                                    <option value="">-- 请选择 --</option>
                                    <?php foreach ($aiModels as $k => $m): if (($m['type'] ?? 'chat') !== 'chat') continue; ?>
                                    <option value="<?php echo $k; ?>" <?php echo $aiChat === $k ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($m['name'] ?? $m['model'], ENT_QUOTES, 'UTF-8'); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">默认图像模型</label>
                                <select id="ai_image" name="ai_image" class="form-control">
                                    <option value="">-- 请选择 --</option>
                                    <?php foreach ($aiModels as $k => $m): if (($m['type'] ?? 'chat') !== 'image') continue; ?>
                                    <option value="<?php echo $k; ?>" <?php echo $aiImage === $k ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($m['name'] ?? $m['model'], ENT_QUOTES, 'UTF-8'); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">系统提示词</label>
                        <textarea id="ai_system_prompt" name="ai_system_prompt" class="form-control" rows="3" placeholder="如：你是一个有用的助手"><?php echo htmlspecialchars($aiSystemPrompt, ENT_QUOTES, 'UTF-8'); ?></textarea>
                        <small class="text-muted">AI 辅助写作（提取关键词、生成描述、选品）时使用的系统角色设定。</small>
                    </div>
                    <div class="text-end">
                        <button type="button" class="btn btn-primary btn-sm" onclick="saveGlobal()">
                            <i class="fas fa-save"></i> 保存全局设置
                        </button>
                    </div>
                </form>

                <hr>

                <!-- 模型管理 -->
                <div class="d-flex flex-wrap align-items-center gap-2 mb-3">
                    <button type="button" class="btn btn-success btn-sm" onclick="openModelModal(0)">
                        <i class="fas fa-plus"></i> 添加模型
                    </button>
                </div>

                <div class="table-responsive">
                    <table class="table table-bordered table-hover align-middle mb-0">
                        <thead class="thead-light">
                            <tr>
                                <th style="width:60px">ID</th>
                                <th>名称</th>
                                <th>类型</th>
                                <th>模型ID</th>
                                <th>平台</th>
                                <th>对接地址</th>
                                <th>状态</th>
                                <th style="width:160px">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(!empty($aiModels)): $i = 0; foreach($aiModels as $k => $m): $i++; ?>
                            <tr>
                                <td><?php echo $i; ?></td>
                                <td><?php echo htmlspecialchars($m['name'] ?? $m['model'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td>
                                    <?php
                                        $t = $m['type'] ?? 'chat';
                                        $tMap = array('chat'=>'文本对话','image'=>'图像生成','embed'=>'Embedding','rerank'=>'Rerank');
                                        $tClass = array('chat'=>'badge-info','image'=>'badge-warning','embed'=>'badge-secondary','rerank'=>'badge-dark');
                                    ?>
                                    <span class="badge <?php echo $tClass[$t] ?? 'badge-info'; ?>"><?php echo $tMap[$t] ?? $t; ?></span>
                                </td>
                                <td><code style="font-size:12px"><?php echo htmlspecialchars($m['model'] ?? '', ENT_QUOTES, 'UTF-8'); ?></code></td>
                                <td>
                                    <?php
                                        $pf = $m['platform'] ?? '';
                                        echo htmlspecialchars(isset($aiPlatformName[$pf]) ? $aiPlatformName[$pf] : ($pf ?: '—'), ENT_QUOTES, 'UTF-8');
                                    ?>
                                </td>
                                <td><code style="font-size:11px"><?php echo htmlspecialchars($m['api_url'] ?? '', ENT_QUOTES, 'UTF-8'); ?></code></td>
                                <td>
                                    <span class="ai-status-badge" data-key="<?php echo htmlspecialchars($k, ENT_QUOTES, 'UTF-8'); ?>" data-type="<?php echo htmlspecialchars($m['type'] ?? 'chat', ENT_QUOTES, 'UTF-8'); ?>">
                                    <?php
                                        $isChat = (($m['type'] ?? 'chat') === 'chat') && $aiChat === $k;
                                        $isImg  = (($m['type'] ?? 'chat') === 'image') && $aiImage === $k;
                                        if ($isChat): ?><span class="badge badge-success">对话启用</span>
                                        <?php elseif ($isImg): ?><span class="badge badge-success">图像启用</span>
                                        <?php else: ?><span class="badge badge-light">未启用</span>
                                        <?php endif; ?>
                                    </span>
                                </td>
                                <td>
                                    <?php
                                        $rowType = $m['type'] ?? 'chat';
                                        $isActive = ($rowType === 'chat' && $aiChat === $k) || ($rowType === 'image' && $aiImage === $k);
                                    ?>
                                    <?php if ($rowType === 'chat' || $rowType === 'image'): ?>
                                    <a href="javascript:;" class="btn btn-sm <?php echo $isActive ? 'btn-warning' : 'btn-outline-success'; ?> ai-active-btn" data-key="<?php echo htmlspecialchars($k, ENT_QUOTES, 'UTF-8'); ?>" data-type="<?php echo htmlspecialchars($rowType, ENT_QUOTES, 'UTF-8'); ?>" onclick="activeModel(this)"><?php echo $isActive ? '暂停对话' : '启用对话'; ?></a>
                                    <?php else: ?>
                                    <span class="text-muted" style="font-size:12px">能力模型</span>
                                    <?php endif; ?>
                                    <a href="javascript:;" class="btn btn-sm btn-outline-primary" onclick="openModelModal('<?php echo $k; ?>')">修改</a>
                                    <a href="javascript:;" class="btn btn-sm btn-outline-danger" onclick="delModel('<?php echo $k; ?>')">删除</a>
                                </td>
                            </tr>
                            <?php endforeach; else: ?>
                            <tr><td colspan="8" class="text-center text-muted">暂无模型，点击「添加模型」开始配置</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

{include file="app/manage/view/index/emlog_footer"}

<input type="hidden" name="__hash__" id="hash_field" value="<?php echo isset($hash) ? $hash : ''; ?>">

<!-- 模型 新增/编辑 弹窗（原生，无 jQuery 依赖） -->
<div id="modelModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,.45); z-index:1080;" onclick="if(event.target===this)closeModelModal()">
  <div style="position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); width:560px; max-width:94%; background:#fff; border-radius:10px; box-shadow:0 10px 40px rgba(0,0,0,.25); max-height:92vh; overflow:auto;">
    <div style="padding:16px 20px; border-bottom:1px solid #eee; display:flex; justify-content:space-between; align-items:center;">
      <h5 id="modelModalTitle" style="margin:0; font-size:16px;">添加模型</h5>
      <button type="button" class="btn-close" onclick="closeModelModal()"></button>
    </div>
    <div style="padding:20px;">
      <input type="hidden" id="model_id" value="">

      <div class="mb-3">
        <label class="form-label">模型类型 <span class="text-danger">*</span></label>
        <select id="model_type" class="form-control" onchange="onModelTypeChange()">
          <option value="chat">文本对话（Chat）</option>
          <option value="image">图像生成（Image）</option>
          <option value="embed">Embedding（向量化）</option>
          <option value="rerank">Rerank（重排）</option>
        </select>
        <small class="form-text text-muted" id="model_type_tip"></small>
      </div>

      <div class="mb-3">
        <label class="form-label">AI 平台 <span class="text-danger">*</span></label>
        <select id="model_platform" class="form-control" onchange="onModelPlatformChange()">
          <option value="deepseek">DeepSeek</option>
          <option value="zhipu">智谱 AI</option>
          <option value="siliconflow">硅基流动</option>
          <option value="doubao">豆包（火山方舟）</option>
          <option value="openai">OpenAI</option>
        </select>
        <small class="form-text text-muted" id="model_platform_tip"></small>
      </div>

      <div class="mb-3">
        <label class="form-label">对接地址（API URL） <span class="text-danger">*</span></label>
        <input type="text" id="model_api_url" class="form-control" placeholder="选择平台后自动带出，可手动修改">
        <small class="form-text text-muted" id="model_api_url_tip"></small>
      </div>

      <div class="mb-3">
        <label class="form-label">API Key <span class="text-danger">*</span></label>
        <input type="text" id="model_api_key" class="form-control" placeholder="平台分配的 API Key" value="">
      </div>

      <div class="mb-3">
        <label class="form-label">模型 ID <span class="text-danger">*</span></label>
        <select id="model_model_sel" class="form-control" onchange="onModelSelectChange()" style="margin-bottom:6px;"></select>
        <input type="text" id="model_model" class="form-control" placeholder="如 deepseek-chat">
        <small class="text-muted">下拉为平台预设模型，选择后填入下方输入框；也可直接手填自定义模型 ID。</small>
      </div>

      <div class="mb-3">
        <label class="form-label">备注名称</label>
        <input type="text" id="model_name" class="form-control" placeholder="便于识别的名称，如「DeepSeek 对话」">
      </div>
    </div>
    <div style="padding:14px 20px; border-top:1px solid #eee; text-align:right;">
      <button type="button" class="btn btn-light me-2" onclick="closeModelModal()">取消</button>
      <button type="button" class="btn btn-success" onclick="submitModel()">提交</button>
    </div>
  </div>
</div>

<script>
/* ==================== 平台预设数据（由 AiController::setting() 注入） ==================== */
window.AI_PLATFORMS_DATA = <?php echo isset($aiPlatformsJson) ? $aiPlatformsJson : '{}'; ?>;
var AI_PLATFORMS = window.AI_PLATFORMS_DATA || {};

/* 类型中文说明 */
var MODEL_TYPE_TIPS = {
    chat:  '文本对话：用于 AI 辅助写作、文章摘要、关键词提取、选品推荐等。',
    image: '图像生成：根据提示词生成图片（如豆包 Seedream、硅基 Kolors / FLUX）。',
    embed: 'Embedding：将文本向量化，用于语义检索、RAG 知识库入库。',
    rerank:'Rerank：对检索结果重排序，提升 RAG 召回精度。'
};

/* 按类型取平台的地址 / 模型列表 */
function platformField(p, type, field) {
    var d = AI_PLATFORMS[p];
    if (!d) return '';
    // 按类型取地址：chat 用 url/models，其余用 xxx_url/xxx_models
    if (field === 'url') {
        var umap = { chat:'url', image:'image_url', embed:'embed_url', rerank:'rerank_url' };
        return d[umap[type]] || '';
    }
    if (field === 'models') {
        var mmap = { chat:'models', image:'image_models', embed:'embed_models', rerank:'rerank_models' };
        return d[mmap[type]] || [];
    }
    return '';
}

/* 类型变更：更新说明 + 联动平台地址/模型 */
function onModelTypeChange() {
    var type = document.getElementById('model_type').value;
    var tip = document.getElementById('model_type_tip');
    tip.textContent = MODEL_TYPE_TIPS[type] || '';
    // 类型变动后，按当前平台重新带出地址与模型
    onModelPlatformChange();
}

/* 平台变更：带出地址 + 填充模型下拉 */
function onModelPlatformChange() {
    var type = document.getElementById('model_type').value;
    var platform = document.getElementById('model_platform').value;
    var pTip = document.getElementById('model_platform_tip');
    var urlTip = document.getElementById('model_api_url_tip');

    var def = (AI_PLATFORMS[platform] && AI_PLATFORMS[platform].name) ? AI_PLATFORMS[platform].name : platform;
    pTip.textContent = '已选平台：' + def;

    var url = platformField(platform, type, 'url');
    var urlInput = document.getElementById('model_api_url');
    if (!urlInput.value || urlInput.dataset.auto === '1') {
        urlInput.value = url;
        urlInput.dataset.auto = '1';
    }
    if (url) {
        urlTip.innerHTML = '<span class="text-success">已带出 ' + def + ' 的' + typeName(type) + '预设地址</span>';
    } else {
        urlTip.innerHTML = '<span class="text-warning">该平台暂未提供「' + typeName(type) + '」预设地址，请手动填写</span>';
    }

    // 模型下拉（预设为 {id, price} 对象数组）
    var models = platformField(platform, type, 'models');
    var sel = document.getElementById('model_model_sel');
    sel.innerHTML = '';
    var ph = document.createElement('option');
    ph.value = ''; ph.text = (models && models.length) ? '— 选择预设模型 —' : '— 该类型无预设，请手填 —';
    sel.appendChild(ph);
    (models || []).forEach(function(m){
        var id    = (typeof m === 'object' && m && m.id) ? m.id : m;
        var price = (typeof m === 'object' && m && m.price) ? m.price : '';
        var o = document.createElement('option');
        o.value = id;
        var isFree = /免费/.test(price || '');
        if (price) {
            o.text = isFree ? (id + '  【免费】') : (id + '  (' + price + ')');
        } else {
            o.text = id;
        }
        if (isFree) o.style.color = '#e74c3c';
        sel.appendChild(o);
    });
    // 若当前 model 输入框与某预设一致，则回显选中
    var cur = document.getElementById('model_model').value;
    if (cur) {
        var matched = false;
        for (var i=0;i<sel.options.length;i++){ if (sel.options[i].value===cur){ sel.value=cur; matched=true; break; } }
        if (!matched) sel.value = '';
    }
}

function onModelSelectChange() {
    var v = document.getElementById('model_model_sel').value;
    if (v) document.getElementById('model_model').value = v;
}

function typeName(t) {
    return ({chat:'对话',image:'图像',embed:'向量',rerank:'重排'})[t] || t;
}

/* ==================== 弹窗控制 ==================== */
function openModelModal(id) {
    id = id || '';
    document.getElementById('model_id').value = id;
    document.getElementById('modelModalTitle').textContent = id ? '修改模型' : '添加模型';
    // 清空
    document.getElementById('model_api_url').value = '';
    document.getElementById('model_api_url').dataset.auto = '0';
    document.getElementById('model_api_key').value = '';
    document.getElementById('model_model').value = '';
    document.getElementById('model_name').value = '';
    document.getElementById('model_type').value = 'chat';
    document.getElementById('model_platform').value = 'deepseek';

    if (id) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'index.php?r=manage/ai/modelInfo&id=' + encodeURIComponent(id), true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                try {
                    var r = JSON.parse(xhr.responseText);
                    if (r.status === 'y' && r.data) {
                        var d = r.data;
                        document.getElementById('model_name').value = d.name || '';
                        if (d.type) document.getElementById('model_type').value = d.type;
                        if (d.platform) document.getElementById('model_platform').value = d.platform;
                        document.getElementById('model_api_url').value = d.api_url || '';
                        document.getElementById('model_api_url').dataset.auto = '0';
                        document.getElementById('model_api_key').value = d.api_key || '';
                        document.getElementById('model_model').value = d.model || '';
                        onModelTypeChange();      // 刷新说明 + 联动（保留已填地址）
                        document.getElementById('model_api_url').value = d.api_url || '';
                        document.getElementById('model_api_url').dataset.auto = '0';
                        onModelPlatformChange();  // 填充模型下拉并回显选中
                    }
                } catch(e) {}
            }
        };
        xhr.send();
    } else {
        onModelTypeChange();
    }
    document.getElementById('modelModal').style.display = 'block';
}
function closeModelModal() {
    document.getElementById('modelModal').style.display = 'none';
}

function submitModel() {
    var id       = document.getElementById('model_id').value;
    var type     = document.getElementById('model_type').value;
    var platform = document.getElementById('model_platform').value;
    var apiUrl   = document.getElementById('model_api_url').value.trim();
    var apiKey   = document.getElementById('model_api_key').value.trim();
    var model    = document.getElementById('model_model').value.trim();
    var name     = document.getElementById('model_name').value.trim();

    if (!type)        { showToast('请选择模型类型', 'danger'); return; }
    if (!platform)    { showToast('请选择 AI 平台', 'danger'); return; }
    if (!apiUrl)      { showToast('请填写对接地址', 'danger'); return; }
    if (!apiKey)      { showToast('请填写 API Key', 'danger'); return; }
    if (!model)       { showToast('请填写模型 ID', 'danger'); return; }

    var params = 'id=' + encodeURIComponent(id)
        + '&ai_model_type=' + encodeURIComponent(type)
        + '&ai_platform=' + encodeURIComponent(platform)
        + '&ai_api_url=' + encodeURIComponent(apiUrl)
        + '&ai_api_key=' + encodeURIComponent(apiKey)
        + '&ai_model=' + encodeURIComponent(model)
        + '&ai_name=' + encodeURIComponent(name);
    if (document.getElementById('hash_field')) params += '&hash=' + encodeURIComponent(document.getElementById('hash_field').value);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/ai/saveModel', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            try {
                var r = JSON.parse(xhr.responseText);
                if (r.status === 'y') {
                    showToast(r.info, 'success');
                    closeModelModal();
                    setTimeout(function(){ location.reload(); }, 800);
                } else {
                    showToast(r.info || '保存失败', 'danger');
                }
            } catch(e) {
                showToast('提交失败，请检查网络', 'danger');
            }
        }
    };
    xhr.send(params);
}

function delModel(id) {
    if (!confirm('确定删除该模型吗？')) return;
    var params = 'id=' + encodeURIComponent(id);
    if (document.getElementById('hash_field')) params += '&hash=' + encodeURIComponent(document.getElementById('hash_field').value);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/ai/delModel', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            try {
                var r = JSON.parse(xhr.responseText);
                showToast(r.info, r.status === 'y' ? 'success' : 'danger');
                if (r.status === 'y') setTimeout(function(){ location.reload(); }, 800);
            } catch(e) {
                showToast('删除失败', 'danger');
            }
        }
    };
    xhr.send(params);
}

/* ==================== 启用 / 暂停 模型（即时更新，无需刷新） ==================== */
function activeModel(btn) {
    var key  = btn.getAttribute('data-key');
    var type = btn.getAttribute('data-type');
    if (!key) return;
    var params = 'key=' + encodeURIComponent(key) + '&type=' + encodeURIComponent(type);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/ai/active', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            try {
                var r = JSON.parse(xhr.responseText);
                if (r.status !== 'y') {
                    showToast(r.info || '操作失败', 'danger');
                    return;
                }
                showToast(r.info, r.status === 'y' ? 'success' : 'danger');
                var enabled = (r.enabled === 1 || r.enabled === true);
                // 即时更新所有行的状态（清除其它同类型行的"启用"态）
                document.querySelectorAll('.ai-status-badge').forEach(function(span){
                    if (span.getAttribute('data-type') !== type) return;
                    var k = span.getAttribute('data-key');
                    if (enabled && k === key) {
                        span.innerHTML = type === 'image'
                            ? '<span class="badge badge-success">图像启用</span>'
                            : '<span class="badge badge-success">对话启用</span>';
                    } else {
                        span.innerHTML = '<span class="badge badge-light">未启用</span>';
                    }
                });
                // 即时更新按钮文字与样式
                document.querySelectorAll('.ai-active-btn').forEach(function(b){
                    if (b.getAttribute('data-type') !== type) return;
                    var k = b.getAttribute('data-key');
                    if (enabled && k === key) {
                        b.className = 'btn btn-sm btn-warning ai-active-btn';
                        b.textContent = type === 'image' ? '暂停图像' : '暂停对话';
                    } else {
                        b.className = 'btn btn-sm btn-outline-success ai-active-btn';
                        b.textContent = type === 'image' ? '启用图像' : '启用对话';
                    }
                });
                // 同步顶部全局下拉
                var sel = document.getElementById(type === 'image' ? 'ai_image' : 'ai_chat');
                if (sel) sel.value = enabled ? key : '';
            } catch(e) {
                showToast('操作失败，请检查网络', 'danger');
            }
        }
    };
    xhr.send(params);
}

/* ==================== 全局设置 ==================== */
function saveGlobal() {
    var params = 'ai_chat=' + encodeURIComponent(document.getElementById('ai_chat').value)
        + '&ai_image=' + encodeURIComponent(document.getElementById('ai_image').value)
        + '&ai_system_prompt=' + encodeURIComponent(document.getElementById('ai_system_prompt').value);
    if (document.getElementById('hash_field')) params += '&hash=' + encodeURIComponent(document.getElementById('hash_field').value);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/ai/save', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            try {
                var r = JSON.parse(xhr.responseText);
                showToast(r.info || (r.status === 'y' ? '保存成功' : '保存失败'), r.status === 'y' ? 'success' : 'danger');
            } catch(e) {
                showToast('提交失败，请检查网络', 'danger');
            }
        }
    };
    xhr.send(params);
}
</script>
