<template>
  <div>
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item label="提供商名称">
          <el-input v-model="searchInfo.name" placeholder="搜索提供商名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" @click="openDialog">新增</el-button>
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        @sort-change="sortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="ID" prop="ID" width="80" />
        <el-table-column label="名称" prop="name" width="150" />
        <el-table-column label="类型" prop="type" width="100">
          <template #default="scope">
            <el-tag :type="getTypeColor(scope.row.type)">{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Base URL" prop="base_url" min-width="200" show-overflow-tooltip />
        <el-table-column label="模型" prop="model" width="150" />
        <el-table-column label="优先级" prop="priority" width="80" />
        <el-table-column label="超时(秒)" prop="timeout" width="100" />
        <el-table-column label="默认" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.is_default" type="success">默认</el-tag>
            <el-button v-else type="primary" link size="small" @click="setDefault(scope.row)">
              设为默认
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="enabled" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.enabled"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="CreatedAt" width="180">
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="updateProvider(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="deleteProvider(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <el-dialog
      v-model="dialogFormVisible"
      :title="type === 'create' ? '新增提供商' : '编辑提供商'"
      width="800px"
    >
      <el-form ref="providerForm" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入提供商名称" clearable />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择类型" style="width: 100%">
            <el-option label="OpenAI" value="openai" />
            <el-option label="Claude" value="claude" />
            <el-option label="Gemini" value="gemini" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="Base URL" prop="base_url">
          <el-input v-model="formData.base_url" placeholder="https://api.openai.com" clearable />
        </el-form-item>
        <el-form-item label="API Key" prop="api_key">
          <el-input
            v-model="formData.api_key"
            type="password"
            placeholder="请输入API密钥"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item label="默认模型" prop="model">
          <el-input v-model="formData.model" placeholder="gpt-4" clearable />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="formData.priority" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="超时时间(秒)" prop="timeout">
          <el-input-number v-model="formData.timeout" :min="10" :max="300" />
        </el-form-item>
        <el-form-item label="最大重试次数" prop="max_retries">
          <el-input-number v-model="formData.max_retries" :min="0" :max="10" />
        </el-form-item>
        <el-form-item label="启用" prop="enabled">
          <el-switch v-model="formData.enabled" />
        </el-form-item>
        <el-form-item label="设为默认" prop="is_default">
          <el-switch v-model="formData.is_default" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="enterDialog">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAiProviderList,
  createAiProvider,
  updateAiProvider,
  deleteAiProvider
} from '@/api/aiProvider'

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const searchInfo = reactive({
  name: ''
})

const dialogFormVisible = ref(false)
const type = ref('')
const providerForm = ref(null)
const formData = ref({
  name: '',
  type: 'openai',
  base_url: '',
  api_key: '',
  model: '',
  priority: 0,
  timeout: 60,
  max_retries: 3,
  enabled: true,
  is_default: false
})

const rules = reactive({
  name: [{ required: true, message: '请输入提供商名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  base_url: [{ required: true, message: '请输入Base URL', trigger: 'blur' }],
  api_key: [{ required: true, message: '请输入API Key', trigger: 'blur' }]
})

const getTypeColor = (type) => {
  const colors = {
    openai: 'success',
    claude: 'warning',
    gemini: 'primary',
    other: 'info'
  }
  return colors[type] || 'info'
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

const getTableData = async () => {
  const table = await getAiProviderList({
    page: page.value,
    pageSize: pageSize.value,
    ...searchInfo
  })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

const onSubmit = () => {
  page.value = 1
  getTableData()
}

const onReset = () => {
  searchInfo.name = ''
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const sortChange = ({ prop, order }) => {
  // 排序逻辑
}

const handleStatusChange = async (row) => {
  const res = await updateAiProvider(row)
  if (res.code === 0) {
    ElMessage.success('状态更新成功')
  } else {
    row.enabled = !row.enabled
    ElMessage.error('状态更新失败')
  }
}

const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    name: '',
    type: 'openai',
    base_url: '',
    api_key: '',
    model: '',
    priority: 0,
    timeout: 60,
    max_retries: 3,
    enabled: true,
    is_default: false
  }
}

const enterDialog = async () => {
  providerForm.value.validate(async (valid) => {
    if (valid) {
      let res
      if (type.value === 'create') {
        res = await createAiProvider(formData.value)
      } else {
        res = await updateAiProvider(formData.value)
      }
      if (res.code === 0) {
        ElMessage.success(type.value === 'create' ? '创建成功' : '更新成功')
        closeDialog()
        getTableData()
      }
    }
  })
}

const updateProvider = (row) => {
  type.value = 'update'
  formData.value = { ...row }
  dialogFormVisible.value = true
}

const deleteProvider = (row) => {
  ElMessageBox.confirm('确定要删除该提供商吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deleteAiProvider({ ID: row.ID })
    if (res.code === 0) {
      ElMessage.success('删除成功')
      getTableData()
    }
  })
}

const setDefault = async (row) => {
  const res = await updateAiProvider({ ...row, is_default: true })
  if (res.code === 0) {
    ElMessage.success('已设为默认提供商')
    getTableData()
  } else {
    ElMessage.error('设置失败')
  }
}

getTableData()
</script>

<style scoped>
.gva-search-box {
  padding: 20px;
  background: #fff;
  margin-bottom: 10px;
}

.gva-table-box {
  padding: 20px;
  background: #fff;
}

.gva-btn-list {
  margin-bottom: 10px;
}

.gva-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
