<template>
  <div>
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item label="显示模式">
          <el-radio-group v-model="viewMode" @change="handleViewModeChange">
            <el-radio-button value="list">列表视图</el-radio-button>
            <el-radio-button value="group">分组视图</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <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 v-if="viewMode === 'list'" class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" @click="openDialog">新增</el-button>
        <el-button type="success" @click="openSyncDialog">同步模型</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column label="ID" prop="ID" width="80" />
        <el-table-column label="模型名称" prop="name" width="200" />
        <el-table-column label="显示名称" prop="display_name" width="150" />
        <el-table-column label="提供商" width="150">
          <template #default="scope">
            <el-tag>{{ scope.row.provider?.name || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="绑定预设" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.preset" type="success">
              {{ scope.row.preset.name }}
            </el-tag>
            <el-tag v-else type="info">未绑定</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Max Tokens" prop="max_tokens" width="120" />
        <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="description" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="updateModel(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="deleteModel(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>

    <!-- 分组视图 -->
    <div v-else class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" @click="openDialog">新增</el-button>
        <el-button type="success" @click="openSyncDialog">同步模型</el-button>
      </div>
      <el-collapse v-model="activeProviders" accordion>
        <el-collapse-item
          v-for="provider in groupedModels"
          :key="provider.id"
          :name="provider.id"
        >
          <template #title>
            <div class="provider-header">
              <el-tag :type="provider.enabled ? 'success' : 'info'" style="margin-right: 10px">
                {{ provider.name }}
              </el-tag>
              <span class="model-count">{{ provider.models.length }} 个模型</span>
              <span class="enabled-count">
                ({{ provider.models.filter(m => m.enabled).length }} 已启用)
              </span>
            </div>
          </template>
          <el-table :data="provider.models" style="width: 100%">
            <el-table-column label="模型名称" prop="name" width="200" />
            <el-table-column label="显示名称" prop="display_name" width="150" />
            <el-table-column label="绑定预设" width="150">
              <template #default="scope">
                <el-tag v-if="scope.row.preset" type="success">
                  {{ scope.row.preset.name }}
                </el-tag>
                <el-tag v-else type="info">未绑定</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="Max Tokens" prop="max_tokens" width="120" />
            <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="description" min-width="200" show-overflow-tooltip />
            <el-table-column label="操作" fixed="right" width="200">
              <template #default="scope">
                <el-button type="primary" link @click="updateModel(scope.row)">编辑</el-button>
                <el-button type="danger" link @click="deleteModel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="type === 'create' ? '新增模型' : '编辑模型'"
      width="700px"
    >
      <el-form ref="modelForm" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="模型名称" prop="name">
          <el-input v-model="formData.name" placeholder="如: gpt-4" clearable />
        </el-form-item>
        <el-form-item label="显示名称" prop="display_name">
          <el-input v-model="formData.display_name" placeholder="如: GPT-4" clearable />
        </el-form-item>
        <el-form-item label="提供商" prop="provider_id">
          <el-select v-model="formData.provider_id" placeholder="请选择提供商" style="width: 100%">
            <el-option
              v-for="provider in providerList"
              :key="provider.ID"
              :label="provider.name"
              :value="provider.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定预设" prop="preset_id">
          <el-select
            v-model="formData.preset_id"
            placeholder="选择要绑定的预设（可选）"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="preset in presetList"
              :key="preset.ID"
              :label="preset.name"
              :value="preset.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Max Tokens" prop="max_tokens">
          <el-input-number v-model="formData.max_tokens" :min="1" :max="200000" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="模型描述"
          />
        </el-form-item>
        <el-form-item label="启用" prop="enabled">
          <el-switch v-model="formData.enabled" />
        </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>

    <!-- 同步模型对话框 -->
    <el-dialog v-model="syncDialogVisible" title="同步提供商模型" width="500px">
      <el-form label-width="100px">
        <el-form-item label="选择提供商">
          <el-select v-model="syncProviderId" placeholder="请选择提供商" style="width: 100%">
            <el-option
              v-for="provider in providerList"
              :key="provider.ID"
              :label="provider.name"
              :value="provider.ID"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-alert
        title="同步说明"
        type="info"
        :closable="false"
        style="margin-top: 10px"
      >
        <p>将从提供商的 /v1/models 接口获取可用模型列表</p>
        <p>新模型将被添加到系统中（默认禁用状态）</p>
        <p>已存在的模型不会被修改</p>
      </el-alert>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="syncDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSync" :loading="syncing">开始同步</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAiModelList,
  createAiModel,
  updateAiModel,
  deleteAiModel,
  syncProviderModels
} from '@/api/aiModel'
import { getAiProviderList } from '@/api/aiProvider'
import { getAiPresetList } from '@/api/aiPreset'

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

const dialogFormVisible = ref(false)
const syncDialogVisible = ref(false)
const type = ref('')
const modelForm = ref(null)
const syncProviderId = ref(null)
const syncing = ref(false)

const formData = ref({
  name: '',
  display_name: '',
  provider_id: null,
  preset_id: null,
  max_tokens: 4096,
  description: '',
  enabled: true
})

const rules = reactive({
  name: [{ required: true, message: '请输入模型名称', trigger: 'blur' }],
  provider_id: [{ required: true, message: '请选择提供商', trigger: 'change' }]
})

// 按提供商分组模型
const groupedModels = computed(() => {
  const groups = {}

  tableData.value.forEach(model => {
    const providerId = model.provider?.ID
    const providerName = model.provider?.name || '未知提供商'

    if (!groups[providerId]) {
      groups[providerId] = {
        id: providerId,
        name: providerName,
        enabled: model.provider?.enabled || false,
        models: []
      }
    }

    groups[providerId].models.push(model)
  })

  return Object.values(groups).sort((a, b) => a.name.localeCompare(b.name))
})

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

const handleViewModeChange = () => {
  if (viewMode.value === 'group') {
    // 切换到分组视图时，默认展开第一个提供商
    if (groupedModels.value.length > 0) {
      activeProviders.value = [groupedModels.value[0].id]
    }
  }
}

const getTableData = async () => {
  const table = await getAiModelList({
    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 loadProviders = async () => {
  const res = await getAiProviderList({ page: 1, pageSize: 100 })
  if (res.code === 0) {
    providerList.value = res.data.list
  }
}

const loadPresets = async () => {
  const res = await getAiPresetList({ page: 1, pageSize: 100 })
  if (res.code === 0) {
    presetList.value = res.data.list
  }
}

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 handleStatusChange = async (row) => {
  const res = await updateAiModel(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: '',
    display_name: '',
    provider_id: null,
    preset_id: null,
    max_tokens: 4096,
    description: '',
    enabled: true
  }
}

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

const updateModel = (row) => {
  type.value = 'update'
  formData.value = { ...row, provider_id: row.provider?.ID, preset_id: row.preset?.ID }
  dialogFormVisible.value = true
}

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

const openSyncDialog = () => {
  syncProviderId.value = null
  syncDialogVisible.value = true
}

const handleSync = async () => {
  if (!syncProviderId.value) {
    ElMessage.warning('请选择提供商')
    return
  }

  syncing.value = true
  try {
    const res = await syncProviderModels({ ID: syncProviderId.value })
    if (res.code === 0) {
      ElMessage.success('同步成功')
      syncDialogVisible.value = false
      getTableData()
    }
  } finally {
    syncing.value = false
  }
}

getTableData()
loadProviders()
loadPresets()
</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;
}

.provider-header {
  display: flex;
  align-items: center;
  width: 100%;
}

.model-count {
  color: #606266;
  font-size: 14px;
  margin-right: 10px;
}

.enabled-count {
  color: #67c23a;
  font-size: 12px;
}

:deep(.el-collapse-item__header) {
  font-weight: 500;
  font-size: 15px;
}

:deep(.el-collapse-item__content) {
  padding: 10px 20px;
}
</style>
