<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" class="search-form">
      <el-form-item label="服务名称" prop="serviceName">
        <el-input v-model="queryParams.serviceName" placeholder="请输入服务名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="厂商" prop="provider">
        <el-select v-model="queryParams.provider" placeholder="请选择厂商" clearable>
          <el-option v-for="item in providerOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-select v-model="queryParams.enabled" placeholder="请选择状态" clearable>
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['ai:service:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['ai:service:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['ai:service:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="serviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="服务名称" prop="serviceName" min-width="140">
        <template #default="scope">
          <div class="service-name">
            <el-tag v-if="scope.row.isDefault === '1'" type="success" size="small" class="default-tag">默认</el-tag>
            <span>{{ scope.row.serviceName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="服务代码" prop="serviceCode" width="150" />
      <el-table-column label="厂商" prop="providerName" width="100">
        <template #default="scope">
          <el-tag :type="getProviderTagType(scope.row.provider)">{{ scope.row.providerName || scope.row.provider }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="模型" prop="modelCode" width="150" />
      <el-table-column label="支持能力" width="180" align="center">
        <template #default="scope">
          <div class="capability-icons">
            <el-tooltip content="流式输出" placement="top">
              <el-icon v-if="scope.row.supportsStream === '1'" color="#67c23a"><VideoCameraFilled /></el-icon>
            </el-tooltip>
            <el-tooltip content="视觉理解" placement="top">
              <el-icon v-if="scope.row.supportsVision === '1'" color="#409eff"><PictureFilled /></el-icon>
            </el-tooltip>
            <el-tooltip content="工具调用" placement="top">
              <el-icon v-if="scope.row.supportsTools === '1'" color="#e6a23c"><SetUp /></el-icon>
            </el-tooltip>
            <el-tooltip content="深度思考" placement="top">
              <el-icon v-if="scope.row.supportsThinking === '1'" color="#9b59b6"><Cpu /></el-icon>
            </el-tooltip>
            <el-tooltip content="联网搜索" placement="top">
              <el-icon v-if="scope.row.supportsSearch === '1'" color="#3498db"><Search /></el-icon>
            </el-tooltip>
            <el-tooltip content="文件解析" placement="top">
              <el-icon v-if="scope.row.supportsFiles === '1'" color="#1abc9c"><Document /></el-icon>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.enabled" active-value="1" inactive-value="0" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ai:service:edit']" />
          </el-tooltip>
          <el-tooltip content="设为默认" placement="top" v-if="scope.row.isDefault !== '1'">
            <el-button link type="warning" icon="Star" @click="handleSetDefault(scope.row)" v-hasPermi="['ai:service:edit']" />
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ai:service:remove']" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" v-model="open" width="750px" append-to-body destroy-on-close class="service-dialog">
      <el-form ref="serviceRef" :model="form" :rules="rules" label-width="110px">
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务名称" prop="serviceName">
              <el-input v-model="form.serviceName" placeholder="显示名称，如：GPT-4o" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务代码" prop="serviceCode">
              <el-input v-model="form.serviceCode" placeholder="唯一标识，如：openai-gpt4o" :disabled="form.serviceId != null" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="厂商" prop="provider">
              <el-select v-model="form.provider" placeholder="请选择厂商" @change="handleProviderChange" style="width: 100%">
                <el-option v-for="item in providerOptions" :key="item.value" :label="item.label" :value="item.value">
                  <span>{{ item.label }}</span>
                  <span class="provider-url">{{ item.url }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模型代码" prop="modelCode">
              <el-input v-model="form.modelCode" placeholder="厂商模型标识，如：gpt-4o、glm-4" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">
          <span>API配置</span>
          <el-tooltip placement="top">
            <template #content>
              <div style="max-width: 280px;">
                <p style="margin-bottom: 8px;"><b>如何获取 API Key？</b></p>
                <p>• OpenAI: platform.openai.com</p>
                <p>• 智谱AI: open.bigmodel.cn</p>
                <p>• 阿里云: dashscope.console.aliyun.com</p>
                <p>• 月之暗面: platform.moonshot.cn</p>
                <p>• DeepSeek: platform.deepseek.com</p>
              </div>
            </template>
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
        </el-divider>

        <el-form-item label="API地址" prop="apiUrl">
          <el-input v-model="form.apiUrl" placeholder="选择厂商后自动填充，也可手动修改" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="API密钥" prop="apiKey">
              <div class="key-input-wrapper">
                <el-input v-model="form.apiKey" placeholder="从厂商平台获取的 API Key" />
                <el-button 
                  v-if="form.serviceId && isKeyMasked" 
                  class="view-key-btn"
                  link 
                  @click="handleViewKey"
                  v-hasPermi="['ai:service:viewkey']"
                >
                  <el-icon><View /></el-icon>
                  <span>查看原文</span>
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="API Secret" prop="apiSecret">
              <el-input v-model="form.apiSecret" placeholder="部分厂商需要（如百度）" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">
          <span>模型参数</span>
          <el-tooltip placement="top">
            <template #content>
              <div style="max-width: 280px;">
                <p><b>温度</b>: 控制随机性，0=确定，0.7=推荐，1.5+=创意</p>
                <p style="margin-top: 6px;"><b>Top P</b>: 核采样，0.95推荐</p>
                <p style="margin-top: 6px;"><b>最大Token</b>: 回复长度上限，1Token≈0.75中文字</p>
              </div>
            </template>
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
        </el-divider>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="温度" prop="temperature">
              <el-input-number v-model="form.temperature" :min="0" :max="2" :step="0.1" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="Top P" prop="topP">
              <el-input-number v-model="form.topP" :min="0" :max="1" :step="0.05" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最大Token" prop="maxTokens">
              <el-input-number v-model="form.maxTokens" :min="1" :max="128000" :step="1024" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="系统提示词" prop="systemPrompt">
          <el-input v-model="form.systemPrompt" type="textarea" :rows="3" placeholder="设定AI角色，如：你是一个专业、友好的AI助手" />
        </el-form-item>

        <el-divider content-position="left">
          <span>支持的能力</span>
          <el-tooltip placement="top">
            <template #content>
              <div style="max-width: 320px;">
                <p style="margin-bottom: 8px;">勾选此服务支持的能力，对话时会显示对应按钮</p>
                <p><b>流式输出</b>: 逐字显示回复，体验更好</p>
                <p><b>视觉理解</b>: 可上传图片分析（GPT-4o/GLM-4V）</p>
                <p><b>工具调用</b>: Function Calling能力</p>
                <p><b>深度思考</b>: AI先推理再回答（智谱/DeepSeek）</p>
                <p><b>联网搜索</b>: 获取最新信息（智谱/Kimi）</p>
                <p><b>文件解析</b>: 上传文件分析（Kimi/通义）</p>
              </div>
            </template>
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
        </el-divider>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="流式输出">
              <el-switch v-model="form.supportsStream" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="视觉理解">
              <el-switch v-model="form.supportsVision" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工具调用">
              <el-switch v-model="form.supportsTools" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="深度思考">
              <el-switch v-model="form.supportsThinking" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联网搜索">
              <el-switch v-model="form.supportsSearch" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文件解析">
              <el-switch v-model="form.supportsFiles" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">状态设置</el-divider>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="启用状态">
              <el-switch v-model="form.enabled" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number v-model="form.sortOrder" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="备注信息" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AiService">
import { listService, getService, addService, updateService, delService, setDefaultService, viewApiKey } from '@/api/system/ai/service'
import { VideoCameraFilled, PictureFilled, SetUp, QuestionFilled, Cpu, Search, Document, View } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()

const loading = ref(true)
const showSearch = ref(true)
const serviceList = ref([])
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const open = ref(false)

// 厂商选项（含获取API Key的网址）
const providerOptions = ref([
  { value: 'openai', label: 'OpenAI', url: 'platform.openai.com' },
  { value: 'zhipu', label: '智谱AI', url: 'open.bigmodel.cn' },
  { value: 'alibaba', label: '阿里云', url: 'dashscope.console.aliyun.com' },
  { value: 'moonshot', label: '月之暗面', url: 'platform.moonshot.cn' },
  { value: 'baidu', label: '百度', url: 'console.bce.baidu.com' },
  { value: 'deepseek', label: 'DeepSeek', url: 'platform.deepseek.com' },
  { value: 'anthropic', label: 'Anthropic', url: 'console.anthropic.com' },
  { value: 'ollama', label: '本地部署', url: 'ollama.com' }
])

// 厂商API地址映射
const providerApiUrls = {
  openai: 'https://api.openai.com/v1/chat/completions',
  zhipu: 'https://open.bigmodel.cn/api/paas/v4/chat/completions',
  alibaba: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
  moonshot: 'https://api.moonshot.cn/v1/chat/completions',
  baidu: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro',
  deepseek: 'https://api.deepseek.com/v1/chat/completions',
  anthropic: 'https://api.anthropic.com/v1/messages',
  ollama: 'http://localhost:11434/v1/chat/completions'
}

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  serviceName: null,
  provider: null,
  enabled: null
})

const form = ref({})

// 判断API Key是否是脱敏状态
const isKeyMasked = computed(() => {
  return form.value.apiKey && form.value.apiKey.includes('****')
})

const rules = {
  serviceName: [{ required: true, message: '请输入服务名称', trigger: 'blur' }],
  serviceCode: [{ required: true, message: '请输入服务代码', trigger: 'blur' }],
  provider: [{ required: true, message: '请选择厂商', trigger: 'change' }],
  modelCode: [{ required: true, message: '请输入模型代码', trigger: 'blur' }],
  apiUrl: [{ required: true, message: '请输入API地址', trigger: 'blur' }]
}

function getList() {
  loading.value = true
  listService(queryParams.value).then(response => {
    serviceList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.serviceId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

function reset() {
  form.value = {
    serviceId: null,
    serviceName: '',
    serviceCode: '',
    provider: '',
    providerName: '',
    modelCode: '',
    apiUrl: '',
    apiKey: '',
    apiSecret: '',
    temperature: 0.7,
    topP: 0.95,
    maxTokens: 4096,
    systemPrompt: '',
    supportsStream: '1',
    supportsVision: '0',
    supportsTools: '0',
    supportsThinking: '0',
    supportsSearch: '0',
    supportsFiles: '0',
    enabled: '1',
    sortOrder: 0,
    remark: ''
  }
  proxy.resetForm('serviceRef')
}

function handleAdd() {
  reset()
  open.value = true
  title.value = '新增AI服务'
}

function handleUpdate(row) {
  reset()
  const serviceId = row.serviceId || ids.value[0]
  getService(serviceId).then(response => {
    form.value = response.data
    open.value = true
    title.value = '修改AI服务'
  })
}

// 查看完整API Key
function handleViewKey() {
  if (!form.value.serviceId) return
  proxy.$modal.confirm('查看完整API Key是敏感操作，确认继续？').then(() => {
    viewApiKey(form.value.serviceId).then(response => {
      if (response.data) {
        form.value.apiKey = response.data.apiKey || ''
        form.value.apiSecret = response.data.apiSecret || ''
        proxy.$modal.msgSuccess('已显示完整密钥')
      }
    })
  }).catch(() => {})
}

function handleProviderChange(val) {
  // 自动填充API地址
  if (providerApiUrls[val]) {
    form.value.apiUrl = providerApiUrls[val]
  }
  // 自动填充厂商名称
  const provider = providerOptions.value.find(p => p.value === val)
  if (provider) {
    form.value.providerName = provider.label
  }
}

function submitForm() {
  proxy.$refs['serviceRef'].validate(valid => {
    if (valid) {
      if (form.value.serviceId) {
        updateService(form.value).then(() => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addService(form.value).then(() => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

function cancel() {
  open.value = false
  reset()
}

function handleDelete(row) {
  const serviceIds = row.serviceId ? [row.serviceId] : ids.value
  proxy.$modal.confirm('确认删除选中的AI服务吗？').then(() => {
    return delService(serviceIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {})
}

function handleStatusChange(row) {
  const text = row.enabled === '1' ? '启用' : '停用'
  proxy.$modal.confirm(`确认${text}「${row.serviceName}」吗？`).then(() => {
    return updateService({ serviceId: row.serviceId, enabled: row.enabled })
  }).then(() => {
    proxy.$modal.msgSuccess(`${text}成功`)
  }).catch(() => {
    row.enabled = row.enabled === '1' ? '0' : '1'
  })
}

function handleSetDefault(row) {
  proxy.$modal.confirm(`确认将「${row.serviceName}」设为默认服务吗？`).then(() => {
    return setDefaultService(row.serviceId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('设置成功')
  }).catch(() => {})
}

function getProviderTagType(provider) {
  const typeMap = {
    openai: 'success',
    zhipu: 'primary',
    alibaba: 'warning',
    moonshot: 'info',
    baidu: 'danger',
    deepseek: '',
    anthropic: 'success',
    ollama: 'info'
  }
  return typeMap[provider] || ''
}

getList()
</script>

<style scoped>
.search-form {
  background: #fff;
  padding: 20px 20px 0;
  border-radius: 4px;
  margin-bottom: 16px;
}

.service-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.default-tag {
  flex-shrink: 0;
}

.capability-icons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  flex-wrap: wrap;
}

:deep(.el-divider__text) {
  font-weight: 600;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 帮助图标样式 */
.help-icon {
  color: #909399;
  font-size: 14px;
  margin-left: 4px;
  cursor: help;
  vertical-align: middle;
  transition: color 0.2s;
}

.help-icon:hover {
  color: #409eff;
}

/* 厂商下拉选项样式 */
.provider-url {
  float: right;
  color: #8492a6;
  font-size: 12px;
}

/* 表单提示文字 */
.form-tip {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}

/* API Key 输入框容器 */
.key-input-wrapper {
  width: 100%;
  
  .view-key-btn {
    margin-top: 4px;
    font-size: 12px;
    color: #409eff;
    
    .el-icon {
      margin-right: 4px;
    }
  }
}

/* 对话框表单样式优化 */
:deep(.service-dialog) {
  .el-form-item__label {
    display: flex;
    align-items: center;
  }
  
  .el-divider {
    margin: 20px 0 16px;
  }
}
</style>
