import { create } from 'zustand'
import { FarmingTask, TaskTemplate, ResourceAllocation, Workflow } from '@api/modules/operation'
import { operationApi } from '@api'
import { QueryRequest } from '@api/types'

interface OperationState {
  // 任务数据
  taskList: FarmingTask[]
  selectedTask: FarmingTask | null
  taskLoading: boolean
  taskError: string | null
  taskPagination: {
    page: number
    pageSize: number
    total: number
  }

  // 模板数据
  templateList: TaskTemplate[]
  selectedTemplate: TaskTemplate | null
  templateLoading: boolean

  // 资源分配数据
  resourceAllocationList: ResourceAllocation[]
  selectedResourceAllocation: ResourceAllocation | null
  resourceLoading: boolean

  // 工作流数据
  workflowList: Workflow[]
  selectedWorkflow: Workflow | null
  workflowLoading: boolean
  workflowPagination: {
    page: number
    pageSize: number
    total: number
  }
}

interface OperationActions {
  // 任务操作
  fetchTaskList: (params?: QueryRequest) => Promise<void>
  fetchTaskDetail: (id: string) => Promise<void>
  createTask: (data: Omit<FarmingTask, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>
  updateTask: (id: string, data: Partial<FarmingTask>) => Promise<void>
  deleteTask: (id: string) => Promise<void>
  updateTaskStatus: (id: string, status: FarmingTask['status']) => Promise<void>
  setSelectedTask: (task: FarmingTask | null) => void
  clearTaskError: () => void

  // 模板操作
  fetchTemplateList: (params?: QueryRequest) => Promise<void>
  createTemplate: (data: Omit<TaskTemplate, 'id'>) => Promise<void>
  updateTemplate: (id: string, data: Partial<TaskTemplate>) => Promise<void>
  deleteTemplate: (id: string) => Promise<void>

  // 资源分配操作
  fetchResourceAllocations: (params?: QueryRequest) => Promise<void>
  allocateResource: (data: Omit<ResourceAllocation, 'id' | 'allocatedDate'>) => Promise<void>
  returnResource: (id: string) => Promise<void>

  // 工作流操作
  fetchWorkflowList: (params?: QueryRequest) => Promise<void>
  fetchWorkflowDetail: (id: string) => Promise<void>
  createWorkflow: (data: Omit<Workflow, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>
  updateWorkflow: (id: string, data: Partial<Workflow>) => Promise<void>
  deleteWorkflow: (id: string) => Promise<void>
  setSelectedWorkflow: (workflow: Workflow | null) => void
}

export const useOperationStore = create<OperationState & OperationActions>((set, get) => ({
  // 初始状态
  taskList: [],
  selectedTask: null,
  taskLoading: false,
  taskError: null,
  taskPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  templateList: [],
  selectedTemplate: null,
  templateLoading: false,

  resourceAllocationList: [],
  selectedResourceAllocation: null,
  resourceLoading: false,

  workflowList: [],
  selectedWorkflow: null,
  workflowLoading: false,
  workflowPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  // 任务操作
  fetchTaskList: async (params) => {
    try {
      set({ taskLoading: true, taskError: null })
      const response = await operationApi.getTaskList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })

      set({
        taskList: response.data.items,
        taskPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        taskLoading: false
      })
    } catch (error) {
      set({
        taskError: error instanceof Error ? error.message : '获取任务列表失败',
        taskLoading: false
      })
    }
  },

  fetchTaskDetail: async (id) => {
    try {
      set({ taskLoading: true, taskError: null })
      const response = await operationApi.getTaskDetail(id)
      set({
        selectedTask: response.data,
        taskLoading: false
      })
    } catch (error) {
      set({
        taskError: error instanceof Error ? error.message : '获取任务详情失败',
        taskLoading: false
      })
    }
  },

  createTask: async (data) => {
    try {
      const response = await operationApi.createTask(data)
      const currentList = get().taskList
      set({
        taskList: [response.data, ...currentList]
      })
    } catch (error) {
      set({
        taskError: error instanceof Error ? error.message : '创建任务失败'
      })
    }
  },

  updateTask: async (id, data) => {
    try {
      const response = await operationApi.updateTask(id, data)
      const currentList = get().taskList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        taskList: updatedList,
        selectedTask: response.data
      })
    } catch (error) {
      set({
        taskError: error instanceof Error ? error.message : '更新任务失败'
      })
    }
  },

  deleteTask: async (id) => {
    try {
      await operationApi.deleteTask(id)
      const currentList = get().taskList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        taskList: updatedList,
        selectedTask: null
      })
    } catch (error) {
      set({
        taskError: error instanceof Error ? error.message : '删除任务失败'
      })
    }
  },

  updateTaskStatus: async (id, status) => {
    try {
      const response = await operationApi.updateTaskStatus(id, status)
      const currentList = get().taskList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        taskList: updatedList,
        selectedTask: response.data
      })
    } catch (error) {
      set({
        taskError: error instanceof Error ? error.message : '更新任务状态失败'
      })
    }
  },

  setSelectedTask: (task) => set({ selectedTask: task }),
  clearTaskError: () => set({ taskError: null }),

  // 模板操作
  fetchTemplateList: async (params) => {
    try {
      set({ templateLoading: true })
      const response = await operationApi.getTaskTemplateList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 50,
        ...params
      })
      set({
        templateList: response.data.items,
        templateLoading: false
      })
    } catch (error) {
      console.error('获取模板列表失败:', error)
      set({ templateLoading: false })
    }
  },

  createTemplate: async (data) => {
    try {
      const response = await operationApi.createTaskTemplate(data)
      const currentList = get().templateList
      set({
        templateList: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('创建模板失败:', error)
    }
  },

  updateTemplate: async (id, data) => {
    try {
      const response = await operationApi.updateTaskTemplate(id, data)
      const currentList = get().templateList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        templateList: updatedList,
        selectedTemplate: response.data
      })
    } catch (error) {
      console.error('更新模板失败:', error)
    }
  },

  deleteTemplate: async (id) => {
    try {
      await operationApi.deleteTaskTemplate(id)
      const currentList = get().templateList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        templateList: updatedList,
        selectedTemplate: null
      })
    } catch (error) {
      console.error('删除模板失败:', error)
    }
  },

  // 资源分配操作
  fetchResourceAllocations: async (params) => {
    try {
      set({ resourceLoading: true })
      const response = await operationApi.getResourceAllocations({
        page: params?.page || 1,
        pageSize: params?.pageSize || 20,
        ...params
      })
      set({
        resourceAllocationList: response.data.items,
        resourceLoading: false
      })
    } catch (error) {
      console.error('获取资源分配列表失败:', error)
      set({ resourceLoading: false })
    }
  },

  allocateResource: async (data) => {
    try {
      const response = await operationApi.allocateResource(data)
      const currentList = get().resourceAllocationList
      set({
        resourceAllocationList: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('分配资源失败:', error)
    }
  },

  returnResource: async (id) => {
    try {
      await operationApi.returnResource(id)
      const currentList = get().resourceAllocationList
      const updatedList = currentList.map(item =>
        item.id === id ? { ...item, status: 'returned' as const } : item
      )
      set({
        resourceAllocationList: updatedList
      })
    } catch (error) {
      console.error('归还资源失败:', error)
    }
  },

  // 工作流操作
  fetchWorkflowList: async (params) => {
    try {
      set({ workflowLoading: true })
      const response = await operationApi.getWorkflowList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })

      set({
        workflowList: response.data.items,
        workflowPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        workflowLoading: false
      })
    } catch (error) {
      console.error('获取工作流列表失败:', error)
      set({ workflowLoading: false })
    }
  },

  fetchWorkflowDetail: async (id) => {
    try {
      set({ workflowLoading: true })
      const response = await operationApi.getWorkflowDetail(id)
      set({
        selectedWorkflow: response.data,
        workflowLoading: false
      })
    } catch (error) {
      console.error('获取工作流详情失败:', error)
      set({ workflowLoading: false })
    }
  },

  createWorkflow: async (data) => {
    try {
      const response = await operationApi.createWorkflow(data)
      const currentList = get().workflowList
      set({
        workflowList: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('创建工作流失败:', error)
    }
  },

  updateWorkflow: async (id, data) => {
    try {
      const response = await operationApi.updateWorkflow(id, data)
      const currentList = get().workflowList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        workflowList: updatedList,
        selectedWorkflow: response.data
      })
    } catch (error) {
      console.error('更新工作流失败:', error)
    }
  },

  deleteWorkflow: async (id) => {
    try {
      await operationApi.deleteWorkflow(id)
      const currentList = get().workflowList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        workflowList: updatedList,
        selectedWorkflow: null
      })
    } catch (error) {
      console.error('删除工作流失败:', error)
    }
  },

  setSelectedWorkflow: (workflow) => set({ selectedWorkflow: workflow })
}))