<template>
  <div class="page-container">
    <h2 class="page-title">分类分级结果</h2>

    <div class="filter-bar card-shadow">
      <el-select v-model="filterProjectId" placeholder="选择项目" clearable style="width: 180px">
        <el-option v-for="p in projects" :key="p.id" :label="p.name" :value="p.id" />
      </el-select>
      <el-select v-model="filterLevelId" placeholder="选择分级" clearable style="width: 140px; margin-left: 12px">
        <el-option v-for="l in levels" :key="l.id" :label="l.name" :value="l.id">
          <el-tag size="small" :color="l.color" effect="dark">{{ l.code }}</el-tag>
          {{ l.name }}
        </el-option>
      </el-select>
      <el-input v-model="filterKeyword" placeholder="搜索字段名/注释" clearable style="width: 200px; margin-left: 12px" />
      <el-button type="primary" style="margin-left: 12px" @click="handleSearch">
        <el-icon><Search /></el-icon>查询
      </el-button>
      <el-button v-if="filterProjectId" type="warning" style="margin-left: 12px" :loading="mlLoading" @click="handleGetMLSuggestions">
        ML推荐
      </el-button>
      <el-button type="info" style="margin-left: 12px" :loading="trainLoading" @click="handleTrainML">
        训练模型
      </el-button>
    </div>

    <div class="table-card card-shadow">
      <el-table :data="resultList" v-loading="loading" stripe size="default" border>
        <el-table-column prop="column_name" label="字段名" min-width="140" />
        <el-table-column prop="data_type" label="类型" width="100" />
        <el-table-column prop="comment" label="注释" min-width="150" show-overflow-tooltip />
        <el-table-column prop="table_name" label="所属表" width="140" />
        <el-table-column prop="database_name" label="所属库" width="120" />
        <el-table-column prop="source_name" label="数据源" width="120" />
        <el-table-column label="分类" width="140">
          <template #default="{ row }">
            <el-tag v-if="row.category_name" size="small" type="info">{{ row.category_name }}</el-tag>
            <span v-else class="empty-text">--</span>
          </template>
        </el-table-column>
        <el-table-column label="分级" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.level_name" size="small" :color="row.level_color" effect="dark">
              {{ row.level_name }}
            </el-tag>
            <span v-else class="empty-text">--</span>
          </template>
        </el-table-column>
        <el-table-column label="来源" width="90">
          <template #default="{ row }">
            <el-tag size="small" :type="row.source === 'auto' ? 'warning' : 'success'">
              {{ row.source === 'auto' ? '自动' : '人工' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="confidence" label="置信度" width="90">
          <template #default="{ row }">
            <span v-if="row.confidence > 0" :class="confidenceClass(row.confidence)">
              {{ (row.confidence * 100).toFixed(0) }}%
            </span>
            <span v-else class="empty-text">--</span>
          </template>
        </el-table-column>
        <el-table-column label="ML推荐" width="160">
          <template #default="{ row }">
            <div v-if="mlSuggestMap[row.column_id]?.suggestions?.length">
              <el-tag size="small" type="warning">
                {{ mlSuggestMap[row.column_id].suggestions[0].category_name }}
              </el-tag>
              <span class="ml-confidence">{{ (mlSuggestMap[row.column_id].suggestions[0].confidence * 100).toFixed(0) }}%</span>
            </div>
            <span v-else class="empty-text">--</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              v-if="mlSuggestMap[row.column_id]?.suggestions?.length"
              type="primary"
              link
              size="small"
              @click="handleAdoptML(row)"
            >采纳ML</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-bar">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @change="fetchData"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getProjects } from '@/api/project'
import { getDataLevels, getClassificationResults, getMLSuggestions, trainMLModel } from '@/api/classification'
import { labelResult } from '@/api/task'

const loading = ref(false)
const resultList = ref<any[]>([])
const page = ref(1)
const pageSize = ref(50)
const total = ref(0)

const filterProjectId = ref<number | undefined>(undefined)
const filterLevelId = ref<number | undefined>(undefined)
const filterKeyword = ref('')

const projects = ref<any[]>([])
const levels = ref<any[]>([])
const mlLoading = ref(false)
const trainLoading = ref(false)
const mlSuggestMap = ref<Record<number, any>>({})

function confidenceClass(v: number) {
  if (v >= 0.8) return 'confidence-high'
  if (v >= 0.5) return 'confidence-mid'
  return 'confidence-low'
}

async function fetchData() {
  loading.value = true
  try {
    const res: any = await getClassificationResults({
      project_id: filterProjectId.value || undefined,
      level_id: filterLevelId.value || undefined,
      keyword: filterKeyword.value || undefined,
      page: page.value,
      page_size: pageSize.value,
    })
    resultList.value = res.data || []
    total.value = res.total || 0
  } catch (e: any) {
    ElMessage.error(e?.message || '加载失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  page.value = 1
  fetchData()
}

async function fetchMeta() {
  try {
    const [pRes, lRes] = await Promise.all([getProjects({ page: 1, page_size: 100 }), getDataLevels()])
    projects.value = (pRes as any)?.data || []
    levels.value = (lRes as any)?.data || []
  } catch (e) {
    // ignore
  }
}

async function handleGetMLSuggestions() {
  if (!filterProjectId.value) {
    ElMessage.warning('请先选择项目')
    return
  }
  mlLoading.value = true
  try {
    const res: any = await getMLSuggestions(filterProjectId.value)
    const suggestions = res.data || []
    const map: Record<number, any> = {}
    suggestions.forEach((s: any) => {
      map[s.column_id] = s
    })
    mlSuggestMap.value = map
    ElMessage.success(`获取到 ${suggestions.length} 条ML推荐`)
  } catch (e: any) {
    ElMessage.error(e?.message || '获取ML推荐失败')
  } finally {
    mlLoading.value = false
  }
}

async function handleAdoptML(row: any) {
  const sug = mlSuggestMap.value[row.column_id]?.suggestions?.[0]
  if (!sug) return
  try {
    await labelResult(row.id, { category_id: sug.category_id, level_id: row.level_id })
    ElMessage.success('已采纳ML推荐')
    fetchData()
  } catch (e: any) {
    ElMessage.error(e?.message || '采纳失败')
  }
}

async function handleTrainML() {
  trainLoading.value = true
  try {
    const res: any = await trainMLModel(true)
    if (res.data?.task_id) {
      ElMessage.info('模型训练任务已提交后台')
    } else {
      ElMessage.success(`模型训练完成，准确率: ${(res.data?.accuracy * 100).toFixed(1)}%`)
    }
  } catch (e: any) {
    ElMessage.error(e?.message || '训练失败')
  } finally {
    trainLoading.value = false
  }
}

onMounted(() => {
  fetchMeta()
  fetchData()
})
</script>

<style scoped lang="scss">
.page-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #303133;
}

.filter-bar {
  padding: 16px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.table-card {
  padding: 16px;
  background: #fff;
  border-radius: 8px;
}

.pagination-bar {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.empty-text {
  color: #c0c4cc;
}

.confidence-high {
  color: #67c23a;
  font-weight: 600;
}

.confidence-mid {
  color: #e6a23c;
  font-weight: 600;
}

.confidence-low {
  color: #f56c6c;
  font-weight: 600;
}

.ml-confidence {
  font-size: 11px;
  color: #909399;
  margin-left: 4px;
}
</style>
