<template>
  <div class="llm-config-list">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入配置名称"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.provider" placeholder="选择提供商" clearable @change="handleSearch">
            <el-option
              v-for="provider in providerOptions"
              :key="provider.value"
              :label="provider.label"
              :value="provider.value" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.is_enabled" placeholder="启用状态" clearable @change="handleSearch">
            <el-option label="已启用" value="true" />
            <el-option label="已禁用" value="false" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-col>
        <el-col :span="4" class="text-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增配置
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="配置名称" min-width="150" />
      <el-table-column prop="provider" label="提供商" width="120">
        <template #default="{ row }">
          <el-tag :type="getProviderTagType(row.provider) as any">
            {{ getProviderLabel(row.provider) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="model_name" label="模型名称" min-width="180" />
      <el-table-column prop="api_url" label="API地址" min-width="200" show-overflow-tooltip />
      <el-table-column prop="max_tokens" label="最大令牌" width="100" />
      <el-table-column prop="temperature" label="温度" width="80" />
      <el-table-column prop="is_enabled" label="状态" width="80">
        <template #default="{ row }">
          <el-switch v-model="row.is_enabled" @change="handleToggleStatus(row)" :loading="row.statusLoading" />
        </template>
      </el-table-column>
      <el-table-column prop="created_time" label="创建时间" width="160">
        <template #default="{ row }">
          {{ formatDate(row.created_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)"> 编辑 </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 移除分页组件 -->

    <!-- 批量操作 -->
    <div v-if="selectedRows.length > 0" class="batch-actions">
      <el-alert :title="`已选择 ${selectedRows.length} 项`" type="info" show-icon :closable="false">
        <template #default>
          <el-button type="danger" size="small" @click="handleBatchDelete"> 批量删除 </el-button>
          <el-button type="warning" size="small" @click="handleBatchDisable"> 批量禁用 </el-button>
          <el-button type="success" size="small" @click="handleBatchEnable"> 批量启用 </el-button>
        </template>
      </el-alert>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { llmConfigStorage } from '@/utils/llmStorage'

interface Props {
  onEdit: (data: any) => void
}

const props = defineProps<Props>()

// 搜索表单
const searchForm = reactive({
  name: '',
  provider: '',
  is_enabled: '',
})

// 提供商选项
const providerOptions = [
  { label: 'DeepSeek', value: 'deepseek' },
  { label: '通义千问', value: 'qwen' },
  { label: '自定义', value: 'custom' },
]

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)
const selectedRows = ref<any[]>([])

// 移除分页相关变量

// 获取提供商标签类型
const getProviderTagType = (provider: string) => {
  const typeMap: Record<string, string> = {
    deepseek: 'primary',
    qwen: 'success',
    custom: 'danger',
  }
  return typeMap[provider] || 'info'
}

// 获取提供商标签
const getProviderLabel = (provider: string) => {
  const option = providerOptions.find((item) => item.value === provider)
  return option?.label || provider
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 加载数据
const loadData = () => {
  loading.value = true
  try {
    // 获取所有数据
    let allData = llmConfigStorage.getAll()

    // 应用搜索过滤
    if (searchForm.name) {
      allData = allData.filter((item: any) => item.name.toLowerCase().includes(searchForm.name.toLowerCase()))
    }

    if (searchForm.provider) {
      allData = allData.filter((item: any) => item.provider === searchForm.provider)
    }

    if (searchForm.is_enabled) {
      const enabled = searchForm.is_enabled === 'true'
      allData = allData.filter((item: any) => item.is_enabled === enabled)
    }

    // 直接显示所有数据，不分页
    tableData.value = allData
  } catch (error: any) {
    ElMessage.error(error.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    provider: '',
    is_enabled: '',
  })
  handleSearch()
}

// 新增
const handleAdd = () => {
  props.onEdit({})
}

// 编辑
const handleEdit = (row: any) => {
  props.onEdit(row)
}

// 移除测试连接功能

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除配置 "${row.name}" 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    if (row.id) {
      llmConfigStorage.delete(row.id)
      ElMessage.success('删除成功')
      loadData()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 切换状态
const handleToggleStatus = async (row: any) => {
  if (!row.id) return

  row.statusLoading = true
  try {
    llmConfigStorage.update(row.id, { is_enabled: row.is_enabled })
    ElMessage.success(row.is_enabled ? '启用成功' : '禁用成功')
  } catch (error: any) {
    row.is_enabled = !row.is_enabled // 回滚状态
    ElMessage.error(error.message || '操作失败')
  } finally {
    row.statusLoading = false
  }
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个配置吗？`, '确认批量删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    selectedRows.value.filter((item) => item.id).forEach((item) => llmConfigStorage.delete(item.id))
    ElMessage.success('批量删除成功')
    loadData()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '批量删除失败')
    }
  }
}

// 批量禁用
const handleBatchDisable = async () => {
  try {
    selectedRows.value
      .filter((item) => item.id)
      .forEach((item) => llmConfigStorage.update(item.id, { is_enabled: false }))

    ElMessage.success('批量禁用成功')
    loadData()
  } catch (error: any) {
    ElMessage.error(error.message || '批量禁用失败')
  }
}

// 批量启用
const handleBatchEnable = async () => {
  try {
    selectedRows.value
      .filter((item) => item.id)
      .forEach((item) => llmConfigStorage.update(item.id, { is_enabled: true }))

    ElMessage.success('批量启用成功')
    loadData()
  } catch (error: any) {
    ElMessage.error(error.message || '批量启用失败')
  }
}

// 移除分页变化方法

// 暴露刷新方法
defineExpose({
  refresh: loadData,
})

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.llm-config-list {
  .search-bar {
    margin-bottom: 20px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 6px;
  }

  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }

  .batch-actions {
    margin-top: 20px;
  }

  .text-right {
    text-align: right;
  }
}
</style>
