<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" />
      </el-tab-pane>
      <el-tab-pane label="进行中" name="in_progress">
        <TaskTable :tasks="inProgressTasks" @refresh="fetchData" />
      </el-tab-pane>
      <el-tab-pane label="已完成" name="completed">
        <TaskTable :tasks="completedTasks" @refresh="fetchData" />
      </el-tab-pane>
    </el-tabs>

    <!-- Label Dialog -->
    <el-dialog
      v-model="labelDialogVisible"
      title="数据打标"
      width="90%"
      top="5vh"
      destroy-on-close
      class="label-dialog"
    >
      <div class="label-header">
        <span>共 {{ labelItems.length }} 个字段</span>
        <el-input v-model="labelKeyword" placeholder="搜索字段" clearable size="small" style="width: 200px" />
      </div>
      <el-table :data="filteredLabelItems" height="60vh" stripe size="default" border>
        <el-table-column prop="column_name" label="字段名" width="150" />
        <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="source_name" label="数据源" width="120" />
        <el-table-column label="当前分类" width="140">
          <template #default="{ row }">
            <el-tag v-if="row.category_name" size="small">{{ 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 label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-select
              v-model="row._category_id"
              placeholder="分类"
              size="small"
              style="width: 90px"
              class="inline-select"
            >
              <el-option v-for="c in flatCategories" :key="c.id" :label="c.name" :value="c.id" />
            </el-select>
            <el-select
              v-model="row._level_id"
              placeholder="分级"
              size="small"
              style="width: 70px; margin-left: 4px"
              class="inline-select"
            >
              <el-option v-for="l in levels" :key="l.id" :label="l.code" :value="l.id" />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="labelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchSave">批量保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, h } from 'vue'
import { ElMessage, ElButton } from 'element-plus'
import { getMyTasks, getTaskItems } 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 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 })[]>([])
const labelKeyword = ref('')
const levels = ref<any[]>([])
const flatCategories = ref<any[]>([])

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 || []
  } catch (e: any) {
    ElMessage.error(e?.message || '加载失败')
  }
}

async function fetchMeta() {
  try {
    const [catRes, levelRes] = await Promise.all([getCategoryTree(), getDataLevels()])
    levels.value = (levelRes as any) || []
    flatCategories.value = flattenCategories((catRes as any) || [])
  } 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) {
  try {
    const res: any = await getTaskItems(task.id)
    labelItems.value = (res || []).map((item: any) => ({
      ...item,
      _category_id: item.category_id,
      _level_id: item.level_id,
    }))
    labelDialogVisible.value = true
  } catch (e: any) {
    ElMessage.error(e?.message || '加载失败')
  }
}

async function handleBatchSave() {
  ElMessage.success('保存成功（演示模式）')
  labelDialogVisible.value = false
  fetchData()
}

// TaskTable sub-component
const TaskTable = {
  props: ['tasks'],
  emits: ['refresh'],
  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: 'status', label: '状态', width: '100' }, {
                    default: ({ row }: any) =>
                      h('el-tag', { 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: () => openLabel(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;
}

.empty-text {
  color: #c0c4cc;
}

.inline-select {
  :deep(.el-input__wrapper) {
    padding: 0 4px;
  }
}
</style>
