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

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 === 'auditing').length)
  const confirmedCount = computed(() => tasks.value.filter(t => t.status === 'approved').length)
  const scheduledCount = computed(() => tasks.value.filter(t => t.status === 'assigned').length)
  const assignedCount = scheduledCount
  const todayCount = computed(() => tasks.value.filter(t => t.status === 'in_progress').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 = computed(() => {
    const tomorrow = new Date()
    tomorrow.setDate(tomorrow.getDate() + 1)
    const tomorrowStr = formatDate(tomorrow, 'YYYY-MM-DD')
    return tasks.value.filter((t: any) => t.planDate === tomorrowStr || t.scheduleDate === tomorrowStr).length
  })
  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 fetchMyTasks(planDate?: string) {
    loading.value = true
    try {
      const res = await getMyTasks(planDate)
      tasks.value = (res || []) as any
      total.value = tasks.value.length
    } 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 => String((t as any).id ?? (t as any).taskId) === String(taskId)) || null
  }

  async function advanceStep(taskId: number, stepCode: string) {
    await executeSopStep({
      taskId,
      stepCode,
      action: 'execute',
    })
    await fetchTaskDetail(taskId)
  }

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