import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Task, TimelineRecord } from '../types'
import { getTaskList, getTaskDetail, advanceTaskStep, getTaskLogs } from '../api/task'

export const useTaskStore = defineStore('task', () => {
  // State
  const tasks = ref<Task[]>([])
  const currentTask = ref<Task | null>(null)
  const filterStatus = ref<string>('all')
  const loading = ref(false)
  const total = ref(0)

  // Getters
  const filteredTasks = computed(() => {
    if (filterStatus.value === 'all') return tasks.value
    return tasks.value.filter(t => t.status === filterStatus.value)
  })

  const pendingCount = computed(() => tasks.value.filter(t => t.status === 'pending').length)
  const confirmedCount = computed(() => tasks.value.filter(t => t.status === 'confirmed').length)
  const scheduledCount = computed(() => tasks.value.filter(t => t.status === 'scheduled').length)
  const todayCount = computed(() => tasks.value.filter(t => ['scheduled', 'departed', 'constructing'].includes(t.status)).length)
  const processingCount = computed(() => todayCount.value)
  const completedCount = computed(() => tasks.value.filter(t => t.status === 'completed').length)
  const rejectedCount = computed(() => tasks.value.filter(t => t.status === 'rejected').length)
  const emergencyCount = computed(() => tasks.value.filter(t => t.type === 'emergency').length)
  const departedCount = computed(() => tasks.value.filter(t => t.status === 'departed').length)
  const arrivedCount = computed(() => tasks.value.filter(t => t.status === 'arrived').length)
  const inspectingCount = computed(() => tasks.value.filter(t => t.status === 'inspecting').length)
  const tomorrowCount = ref(2)
  const historyCount = computed(() => completedCount.value)

  // Actions
  async function fetchTasks(pageNum = 1, pageSize = 10) {
    loading.value = true
    try {
      const res = await getTaskList(pageNum, pageSize)
      tasks.value = res.rows || []
      total.value = res.total || 0
    } finally {
      loading.value = false
    }
  }

  async function fetchTaskDetail(taskId: number) {
    loading.value = true
    try {
      const res = await getTaskDetail(taskId)
      // 转换日志为时间线
      if (res.logList) {
        res.timeline = res.logList.map((log: any) => ({
          time: log.createTime,
          action: log.action,
          operator: log.operatorName,
          role: log.operatorRole || 'dispatch',
        }))
      }
      currentTask.value = res
    } finally {
      loading.value = false
    }
  }

  function setFilter(status: string) {
    filterStatus.value = status
  }

  function setCurrentTask(taskId: string) {
    currentTask.value = tasks.value.find(t => t.id === taskId) || null
  }

  async function advanceStep(taskId: number, step: number) {
    await advanceTaskStep(taskId, step)
    // 重新获取任务详情
    await fetchTaskDetail(taskId)
  }

  return {
    tasks,
    currentTask,
    filterStatus,
    loading,
    total,
    filteredTasks,
    pendingCount,
    confirmedCount,
    scheduledCount,
    todayCount,
    processingCount,
    completedCount,
    rejectedCount,
    emergencyCount,
    departedCount,
    arrivedCount,
    inspectingCount,
    tomorrowCount,
    historyCount,
    fetchTasks,
    fetchTaskDetail,
    setFilter,
    setCurrentTask,
    advanceStep,
  }
})
