<template>
  <div class="page-container">
    <h2 class="page-title">我的任务</h2>

    <el-tabs v-model="activeTab" class="task-tabs">
      <el-tab-pane label="待处理" name="pending">
        <TaskTable :tasks="pendingTasks" @refresh="fetchData" @label="openLabel" />
      </el-tab-pane>
      <el-tab-pane label="进行中" name="in_progress">
        <TaskTable :tasks="inProgressTasks" @refresh="fetchData" @label="openLabel" />
      </el-tab-pane>
      <el-tab-pane label="已完成" name="completed">
        <TaskTable :tasks="completedTasks" @refresh="fetchData" @label="openLabel" />
      </el-tab-pane>
    </el-tabs>

    <!-- Label Dialog -->
    <el-dialog
      v-model="labelDialogVisible"
      :title="`数据打标 - ${currentTask?.name || ''}`"
      width="92%"
      top="4vh"
      destroy-on-close
      class="label-dialog"
    >
      <div class="label-header">
        <div class="label-stats">
          <span>共 {{ labelItems.length }} 个字段</span>
          <el-tag type="success" size="small">已保存: {{ savedCount }}</el-tag>
          <el-tag type="warning" size="small">待保存: {{ unsavedCount }}</el-tag>
        </div>
        <el-input v-model="labelKeyword" placeholder="搜索字段/表/注释" clearable size="small" style="width: 220px" />
      </div>

      <el-table
        :data="filteredLabelItems"
        height="calc(100vh - 260px)"
        stripe
        size="default"
        border
        @cell-click="handleCellClick"
      >
        <el-table-column prop="column_name" label="字段名" width="150" />
        <el-table-column prop="data_type" label="类型" width="90" />
        <el-table-column prop="comment" label="注释" min-width="140" show-overflow-tooltip />
        <el-table-column prop="table_name" label="所属表" width="130" />
        <el-table-column prop="source_name" label="数据源" width="110" />
        <el-table-column label="分类" width="150">
          <template #default="{ row }">
            <el-select
              v-model="row._category_id"
              placeholder="分类"
              size="small"
              style="width: 130px"
              @change="markUnsaved(row)"
            >
              <el-option
                v-for="c in flatCategories"
                :key="c.id"
                :label="c.name"
                :value="c.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="分级" width="110">
          <template #default="{ row }">
            <el-select
              v-model="row._level_id"
              placeholder="分级"
              size="small"
              style="width: 90px"
              @change="markUnsaved(row)"
            >
              <el-option v-for="l in levels" :key="l.id" :value="l.id">
                <el-tag size="small" :color="l.color" effect="dark">{{ l.code }}</el-tag>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="来源" width="80">
          <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 label="置信度" width="80">
          <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="状态" width="80">
          <template #default="{ row }">
            <el-tag v-if="row._unsaved" size="small" type="danger">待保存</el-tag>
            <el-tag v-else size="small" type="success">已保存</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="labelDialogVisible = false">关闭</el-button>
        <el-button type="primary" :loading="saveLoading" @click="handleBatchSave">批量保存</el-button>
        <el-button type="success" :loading="completeLoading" @click="handleCompleteTask">完成任务</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, h } from 'vue'
import { ElMessage, ElMessageBox, ElButton, ElTag, ElSelect, ElOption } from 'element-plus'
import { getMyTasks, getTaskItems, startTask, completeTask, labelResult } from '@/api/task'
import { getCategoryTree, getDataLevels } from '@/api/classification'
import type { TaskItem, TaskResultItem } from '@/api/task'

const activeTab = ref('pending')
const tasks = ref<TaskItem[]>([])
const currentTask = ref<TaskItem | null>(null)

const pendingTasks = computed(() => tasks.value.filter((t) => t.status === 'pending'))
const inProgressTasks = computed(() => tasks.value.filter((t) => t.status === 'in_progress'))
const completedTasks = computed(() => tasks.value.filter((t) => t.status === 'completed'))

const labelDialogVisible = ref(false)
const labelItems = ref<(TaskResultItem & { _category_id?: number; _level_id?: number; _unsaved?: boolean })[]>([])
const labelKeyword = ref('')
const levels = ref<any[]>([])
const flatCategories = ref<any[]>([])
const saveLoading = ref(false)
const completeLoading = ref(false)

const savedCount = computed(() => labelItems.value.filter((i) => !i._unsaved).length)
const unsavedCount = computed(() => labelItems.value.filter((i) => i._unsaved).length)

const filteredLabelItems = computed(() => {
  if (!labelKeyword.value) return labelItems.value
  const kw = labelKeyword.value.toLowerCase()
  return labelItems.value.filter(
    (i) =>
      i.column_name?.toLowerCase().includes(kw) ||
      i.comment?.toLowerCase().includes(kw) ||
      i.table_name?.toLowerCase().includes(kw)
  )
})

async function fetchData() {
  try {
    const res: any = await getMyTasks()
    tasks.value = res.data || []
  } catch (e: any) {
    ElMessage.error(e?.message || '加载失败')
  }
}

async function fetchMeta() {
  try {
    const [catRes, levelRes] = await Promise.all([getCategoryTree(), getDataLevels()])
    levels.value = (levelRes as any)?.data || []
    flatCategories.value = flattenCategories((catRes as any)?.data || [])
  } catch (e) {
    // ignore
  }
}

function flattenCategories(tree: any[]): any[] {
  const result: any[] = []
  function walk(nodes: any[]) {
    for (const n of nodes) {
      result.push({ id: n.id, name: n.name })
      if (n.children?.length) walk(n.children)
    }
  }
  walk(tree)
  return result
}

async function openLabel(task: TaskItem) {
  currentTask.value = task
  if (task.status === 'pending') {
    try { await startTask(task.id) } catch (e) { /* ignore */ }
    fetchData()
  }
  try {
    const res: any = await getTaskItems(task.id)
    labelItems.value = (res.data || []).map((item: any) => ({
      ...item,
      _category_id: item.category_id,
      _level_id: item.level_id,
      _unsaved: false,
    }))
    labelDialogVisible.value = true
  } catch (e: any) {
    ElMessage.error(e?.message || '加载失败')
  }
}

function markUnsaved(row: any) {
  row._unsaved = true
}

function handleCellClick(row: any, column: any) {
  // Auto-focus for better mobile experience
}

async function handleBatchSave() {
  const unsaved = labelItems.value.filter((i) => i._unsaved && i._category_id && i._level_id)
  if (unsaved.length === 0) {
    ElMessage.info('没有需要保存的变更')
    return
  }
  saveLoading.value = true
  try {
    for (const item of unsaved) {
      await labelResult(item.result_id, {
        category_id: item._category_id!,
        level_id: item._level_id!,
      })
      item._unsaved = false
    }
    ElMessage.success(`成功保存 ${unsaved.length} 条记录`)
  } catch (e: any) {
    ElMessage.error(e?.message || '保存失败')
  } finally {
    saveLoading.value = false
  }
}

async function handleCompleteTask() {
  if (unsavedCount.value > 0) {
    try {
      await ElMessageBox.confirm('还有未保存的变更，是否先保存后再完成任务？', '提示')
      await handleBatchSave()
    } catch (e) {
      if (e === 'cancel') return
    }
  }
  completeLoading.value = true
  try {
    if (currentTask.value) {
      await completeTask(currentTask.value.id)
      ElMessage.success('任务已完成')
      labelDialogVisible.value = false
      fetchData()
    }
  } catch (e: any) {
    ElMessage.error(e?.message || '操作失败')
  } finally {
    completeLoading.value = false
  }
}

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

// TaskTable sub-component
const TaskTable = {
  props: ['tasks'],
  emits: ['refresh', 'label'],
  setup(props: any, { emit }: any) {
    return () =>
      h(
        'div',
        { class: 'task-table-wrapper' },
        props.tasks.length === 0
          ? h('el-empty', { description: '暂无任务' })
          : h(
              'el-table',
              { data: props.tasks, stripe: true, size: 'default' },
              {
                default: () => [
                  h('el-table-column', { prop: 'name', label: '任务名称', minWidth: '180' }),
                  h('el-table-column', { prop: 'project_name', label: '所属项目', minWidth: '140' }),
                  h('el-table-column', { prop: 'status', label: '状态', width: '100' }, {
                    default: ({ row }: any) =>
                      h(ElTag, { size: 'small', type: row.status === 'pending' ? 'warning' : row.status === 'completed' ? 'success' : 'primary' },
                        row.status === 'pending' ? '待处理' : row.status === 'in_progress' ? '进行中' : '已完成'
                      ),
                  }),
                  h('el-table-column', { prop: 'deadline', label: '截止时间', width: '160' }),
                  h('el-table-column', { label: '操作', width: '120', fixed: 'right' }, {
                    default: ({ row }: any) =>
                      h(ElButton, { type: 'primary', link: true, size: 'small', onClick: () => emit('label', row) }, () => '去打标'),
                  }),
                ],
              }
            )
      )
  },
}

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

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

.task-tabs {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
}

.label-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  flex-wrap: wrap;
  gap: 12px;

  .label-stats {
    display: flex;
    align-items: center;
    gap: 12px;
  }
}

.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; }

:deep(.label-dialog) {
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 10px;
  }
}
</style>
