<template>
  <MainLayout>
    <div class="data-sources-page">
      <el-card>
      <template #header>
        <div class="card-header">
          <h2>数据源管理</h2>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            创建数据源
          </el-button>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="filters">
        <el-input
          v-model="searchText"
          placeholder="搜索数据源名称或描述"
          style="width: 300px"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select
          v-model="typeFilter"
          placeholder="类型筛选"
          style="width: 150px; margin-left: 10px"
          clearable
          @change="handleSearch"
        >
          <el-option label="MySQL" value="mysql" />
          <el-option label="PostgreSQL" value="postgresql" />
          <el-option label="API" value="api" />
          <el-option label="JSON" value="json" />
        </el-select>
        <el-select
          v-model="statusFilter"
          placeholder="状态筛选"
          style="width: 150px; margin-left: 10px"
          clearable
          @change="handleSearch"
        >
          <el-option label="活跃" value="active" />
          <el-option label="非活跃" value="inactive" />
          <el-option label="错误" value="error" />
        </el-select>
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>

      <!-- 数据源列表 -->
      <el-table
        v-loading="loading"
        :data="dataSources"
        style="width: 100%; margin-top: 20px"
        stripe
      >
        <el-table-column prop="name" label="名称" width="200" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.type.toUpperCase() }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="last_connected_at" label="最后连接" width="180">
          <template #default="{ row }">
            {{ row.last_connected_at ? formatDate(row.last_connected_at) : '从未连接' }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button link type="success" @click="handleTest(row)">
              <el-icon><Connection /></el-icon>
              测试连接
            </el-button>
            <el-button link type="info" @click="handleQuery(row)">
              <el-icon><Search /></el-icon>
              查询数据
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="handleDialogClose"
    >
      <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入数据源名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="选择数据源类型" @change="handleTypeChange">
            <el-option label="MySQL" value="mysql" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="API" value="api" />
            <el-option label="JSON文件" value="json" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入数据源描述"
          />
        </el-form-item>
        
        <!-- MySQL配置 -->
        <template v-if="form.type === 'mysql'">
          <el-form-item label="主机" prop="config.host">
            <el-input v-model="form.config.host" placeholder="localhost" />
          </el-form-item>
          <el-form-item label="端口" prop="config.port">
            <el-input-number v-model="form.config.port" :min="1" :max="65535" />
          </el-form-item>
          <el-form-item label="数据库" prop="config.database">
            <el-input v-model="form.config.database" />
          </el-form-item>
          <el-form-item label="用户名" prop="config.username">
            <el-input v-model="form.config.username" />
          </el-form-item>
          <el-form-item label="密码" prop="config.password">
            <el-input v-model="form.config.password" type="password" show-password />
          </el-form-item>
        </template>

        <!-- PostgreSQL配置 -->
        <template v-if="form.type === 'postgresql'">
          <el-form-item label="主机" prop="config.host">
            <el-input v-model="form.config.host" placeholder="localhost" />
          </el-form-item>
          <el-form-item label="端口" prop="config.port">
            <el-input-number v-model="form.config.port" :min="1" :max="65535" />
          </el-form-item>
          <el-form-item label="数据库" prop="config.database">
            <el-input v-model="form.config.database" />
          </el-form-item>
          <el-form-item label="用户名" prop="config.username">
            <el-input v-model="form.config.username" />
          </el-form-item>
          <el-form-item label="密码" prop="config.password">
            <el-input v-model="form.config.password" type="password" show-password />
          </el-form-item>
        </template>

        <!-- API配置 -->
        <template v-if="form.type === 'api'">
          <el-form-item label="API地址" prop="config.url">
            <el-input v-model="form.config.url" placeholder="https://api.example.com" />
          </el-form-item>
          <el-form-item label="请求方法" prop="config.method">
            <el-select v-model="form.config.method">
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
              <el-option label="PUT" value="PUT" />
              <el-option label="DELETE" value="DELETE" />
            </el-select>
          </el-form-item>
          <el-form-item label="请求头" prop="config.headers">
            <el-input
              v-model="form.config.headers"
              type="textarea"
              :rows="3"
              placeholder='{"Authorization": "Bearer token"}'
            />
          </el-form-item>
        </template>

        <!-- JSON文件配置 -->
        <template v-if="form.type === 'json'">
          <el-form-item label="文件路径" prop="config.file_path">
            <el-input v-model="form.config.file_path" placeholder="/path/to/file.json" />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 测试连接对话框 -->
    <el-dialog v-model="testDialogVisible" title="测试连接" width="500px">
      <div v-if="testing">
        <el-icon class="is-loading"><Loading /></el-icon>
        正在测试连接...
      </div>
      <div v-else-if="testResult">
        <el-alert
          :type="testResult.status === 'success' ? 'success' : 'error'"
          :title="testResult.message"
          :closable="false"
        />
      </div>
    </el-dialog>

    <!-- 查询数据对话框 -->
    <el-dialog v-model="queryDialogVisible" title="查询数据" width="800px">
      <el-form :model="queryForm" label-width="120px">
        <el-form-item label="查询参数">
          <el-input
            v-model="queryForm.query"
            type="textarea"
            :rows="5"
            placeholder='对于MySQL/PostgreSQL，输入SQL查询；对于API，输入查询参数JSON；对于JSON文件，输入路径'
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleExecuteQuery" :loading="querying">
            执行查询
          </el-button>
        </el-form-item>
      </el-form>
      <div v-if="queryResult" style="margin-top: 20px">
        <h4>查询结果：</h4>
        <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; max-height: 400px; overflow: auto">{{ JSON.stringify(queryResult, null, 2) }}</pre>
      </div>
    </el-dialog>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import MainLayout from '@/components/MainLayout.vue'
import {
  Plus,
  Search,
  Refresh,
  Edit,
  Delete,
  Connection,
  Loading
} from '@element-plus/icons-vue'
import api from '@/api'

// 数据源列表
const dataSources = ref<any[]>([])
const loading = ref(false)
const total = ref(0)

// 搜索和筛选
const searchText = ref('')
const typeFilter = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(20)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('创建数据源')
const formRef = ref()
const submitting = ref(false)
const currentDataSourceId = ref<string | null>(null)
const form = reactive({
  name: '',
  type: 'mysql',
  description: '',
  config: {} as any
})

// 测试连接
const testDialogVisible = ref(false)
const testing = ref(false)
const testResult = ref<any>(null)
const currentTestDataSource = ref<any>(null)

// 查询数据
const queryDialogVisible = ref(false)
const querying = ref(false)
const queryResult = ref<any>(null)
const queryForm = reactive({
  query: ''
})
const currentQueryDataSource = ref<any>(null)

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入数据源名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择数据源类型', trigger: 'change' }
  ]
}

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    active: 'success',
    inactive: 'info',
    error: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    active: '活跃',
    inactive: '非活跃',
    error: '错误'
  }
  return textMap[status] || status
}

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

// 类型变化
const handleTypeChange = () => {
  // 根据类型初始化配置
  if (form.type === 'mysql' || form.type === 'postgresql') {
    form.config = {
      host: 'localhost',
      port: form.type === 'mysql' ? 3306 : 5432,
      database: '',
      username: '',
      password: ''
    }
  } else if (form.type === 'api') {
    form.config = {
      url: '',
      method: 'GET',
      headers: '{}'
    }
  } else if (form.type === 'json') {
    form.config = {
      file_path: ''
    }
  }
}

// 搜索
const handleSearch = async () => {
  currentPage.value = 1
  await loadDataSources()
}

// 刷新
const handleRefresh = async () => {
  searchText.value = ''
  typeFilter.value = ''
  statusFilter.value = ''
  currentPage.value = 1
  await loadDataSources()
}

// 加载数据源列表
const loadDataSources = async () => {
  loading.value = true
  try {
    const params: any = {
      skip: (currentPage.value - 1) * pageSize.value,
      limit: pageSize.value
    }
    if (searchText.value) params.search = searchText.value
    if (typeFilter.value) params.type = typeFilter.value
    if (statusFilter.value) params.status = statusFilter.value
    
    const response = await api.get('/api/v1/data-sources', { params })
    dataSources.value = response.data
    total.value = response.data.length
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '加载数据源列表失败')
  } finally {
    loading.value = false
  }
}

// 创建
const handleCreate = () => {
  dialogTitle.value = '创建数据源'
  currentDataSourceId.value = null
  form.name = ''
  form.type = 'mysql'
  form.description = ''
  handleTypeChange()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (dataSource: any) => {
  dialogTitle.value = '编辑数据源'
  currentDataSourceId.value = dataSource.id
  form.name = dataSource.name
  form.type = dataSource.type
  form.description = dataSource.description || ''
  form.config = { ...dataSource.config }
  dialogVisible.value = true
}

// 测试连接
const handleTest = async (dataSource: any) => {
  currentTestDataSource.value = dataSource
  testDialogVisible.value = true
  testing.value = true
  testResult.value = null
  
  try {
    const response = await api.post(`/api/v1/data-sources/${dataSource.id}/test`)
    testResult.value = response.data
    if (testResult.value.status === 'success') {
      ElMessage.success('连接测试成功')
      await loadDataSources() // 刷新列表以更新状态
    } else {
      ElMessage.error(testResult.value.message || '连接测试失败')
    }
  } catch (error: any) {
    testResult.value = {
      status: 'error',
      message: error.response?.data?.detail || '连接测试失败'
    }
    ElMessage.error(testResult.value.message)
  } finally {
    testing.value = false
  }
}

// 查询数据
const handleQuery = (dataSource: any) => {
  currentQueryDataSource.value = dataSource
  queryForm.query = ''
  queryResult.value = null
  queryDialogVisible.value = true
}

// 执行查询
const handleExecuteQuery = async () => {
  if (!queryForm.query.trim()) {
    ElMessage.warning('请输入查询参数')
    return
  }
  
  querying.value = true
  try {
    let queryParams: any = {}
    
    // 根据数据源类型构建查询参数
    if (currentQueryDataSource.value.type === 'mysql' || currentQueryDataSource.value.type === 'postgresql') {
      queryParams = { query: queryForm.query }
    } else if (currentQueryDataSource.value.type === 'api') {
      try {
        queryParams = JSON.parse(queryForm.query)
      } catch {
        queryParams = { query: queryForm.query }
      }
    } else if (currentQueryDataSource.value.type === 'json') {
      queryParams = { path: queryForm.query }
    }
    
    const response = await api.post(
      `/api/v1/data-sources/${currentQueryDataSource.value.id}/query`,
      queryParams
    )
    queryResult.value = response.data
    ElMessage.success('查询成功')
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '查询失败')
    queryResult.value = null
  } finally {
    querying.value = false
  }
}

// 删除
const handleDelete = async (dataSource: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据源 "${dataSource.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        type: 'error'
      }
    )
    await api.delete(`/api/v1/data-sources/${dataSource.id}`)
    ElMessage.success('删除成功')
    await loadDataSources()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.detail || '删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    submitting.value = true
    try {
      const data: any = {
        name: form.name,
        type: form.type,
        description: form.description,
        config: { ...form.config }
      }
      
      // 处理API的headers（如果是字符串，尝试解析为JSON）
      if (form.type === 'api' && typeof data.config.headers === 'string') {
        try {
          data.config.headers = JSON.parse(data.config.headers)
        } catch {
          // 如果解析失败，保持原样
        }
      }
      
      if (currentDataSourceId.value) {
        // 更新
        await api.put(`/api/v1/data-sources/${currentDataSourceId.value}`, data)
        ElMessage.success('更新成功')
      } else {
        // 创建
        await api.post('/api/v1/data-sources', data)
        ElMessage.success('创建成功')
      }
      dialogVisible.value = false
      await loadDataSources()
    } catch (error: any) {
      ElMessage.error(error.response?.data?.detail || '操作失败')
    } finally {
      submitting.value = false
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
  currentDataSourceId.value = null
}

// 分页变化
const handlePageChange = () => {
  loadDataSources()
}

// 初始化
onMounted(() => {
  loadDataSources()
})
</script>

<style scoped>
.data-sources-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
}

.filters {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

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