import { create } from 'zustand'
import { Machinery, Driver, MonitoringData } from '@api/modules/machinery'
import { machineryApi } from '@api'
import { QueryRequest } from '@api/types'

interface MachineryState {
  // 农机数据
  machineryList: Machinery[]
  selectedMachinery: Machinery | null
  machineryLoading: boolean
  machineryError: string | null
  machineryPagination: {
    page: number
    pageSize: number
    total: number
  }

  // 驾驶员数据
  driverList: Driver[]
  selectedDriver: Driver | null
  driverLoading: boolean
  driverError: string | null
  driverPagination: {
    page: number
    pageSize: number
    total: number
  }

  // 监控数据
  monitoringData: MonitoringData[]
  realTimeData: MonitoringData | null
  monitoringLoading: boolean
}

interface MachineryActions {
  // 农机操作
  fetchMachineryList: (params?: QueryRequest) => Promise<void>
  fetchMachineryDetail: (id: string) => Promise<void>
  createMachinery: (data: Omit<Machinery, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>
  updateMachinery: (id: string, data: Partial<Machinery>) => Promise<void>
  deleteMachinery: (id: string) => Promise<void>
  setSelectedMachinery: (machinery: Machinery | null) => void
  clearMachineryError: () => void

  // 驾驶员操作
  fetchDriverList: (params?: QueryRequest) => Promise<void>
  fetchDriverDetail: (id: string) => Promise<void>
  createDriver: (data: Omit<Driver, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>
  updateDriver: (id: string, data: Partial<Driver>) => Promise<void>
  deleteDriver: (id: string) => Promise<void>
  setSelectedDriver: (driver: Driver | null) => void
  clearDriverError: () => void

  // 监控操作
  fetchRealTimeData: (machineryId: string) => Promise<void>
  fetchMonitoringHistory: (machineryId: string, params?: QueryRequest) => Promise<void>
}

export const useMachineryStore = create<MachineryState & MachineryActions>((set, get) => ({
  // 初始状态
  machineryList: [],
  selectedMachinery: null,
  machineryLoading: false,
  machineryError: null,
  machineryPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  driverList: [],
  selectedDriver: null,
  driverLoading: false,
  driverError: null,
  driverPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  monitoringData: [],
  realTimeData: null,
  monitoringLoading: false,

  // 农机操作
  fetchMachineryList: async (params) => {
    try {
      set({ machineryLoading: true, machineryError: null })
      const response = await machineryApi.getMachineryList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })

      set({
        machineryList: response.data.items,
        machineryPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        machineryLoading: false
      })
    } catch (error) {
      set({
        machineryError: error instanceof Error ? error.message : '获取农机列表失败',
        machineryLoading: false
      })
    }
  },

  fetchMachineryDetail: async (id) => {
    try {
      set({ machineryLoading: true, machineryError: null })
      const response = await machineryApi.getMachineryDetail(id)
      set({
        selectedMachinery: response.data,
        machineryLoading: false
      })
    } catch (error) {
      set({
        machineryError: error instanceof Error ? error.message : '获取农机详情失败',
        machineryLoading: false
      })
    }
  },

  createMachinery: async (data) => {
    try {
      const response = await machineryApi.createMachinery(data)
      const currentList = get().machineryList
      set({
        machineryList: [response.data, ...currentList]
      })
    } catch (error) {
      set({
        machineryError: error instanceof Error ? error.message : '创建农机失败'
      })
    }
  },

  updateMachinery: async (id, data) => {
    try {
      const response = await machineryApi.updateMachinery(id, data)
      const currentList = get().machineryList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        machineryList: updatedList,
        selectedMachinery: response.data
      })
    } catch (error) {
      set({
        machineryError: error instanceof Error ? error.message : '更新农机失败'
      })
    }
  },

  deleteMachinery: async (id) => {
    try {
      await machineryApi.deleteMachinery(id)
      const currentList = get().machineryList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        machineryList: updatedList,
        selectedMachinery: null
      })
    } catch (error) {
      set({
        machineryError: error instanceof Error ? error.message : '删除农机失败'
      })
    }
  },

  setSelectedMachinery: (machinery) => set({ selectedMachinery: machinery }),
  clearMachineryError: () => set({ machineryError: null }),

  // 驾驶员操作
  fetchDriverList: async (params) => {
    try {
      set({ driverLoading: true, driverError: null })
      const response = await machineryApi.getDriverList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })

      set({
        driverList: response.data.items,
        driverPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        driverLoading: false
      })
    } catch (error) {
      set({
        driverError: error instanceof Error ? error.message : '获取驾驶员列表失败',
        driverLoading: false
      })
    }
  },

  fetchDriverDetail: async (id) => {
    try {
      set({ driverLoading: true, driverError: null })
      const response = await machineryApi.getDriverDetail(id)
      set({
        selectedDriver: response.data,
        driverLoading: false
      })
    } catch (error) {
      set({
        driverError: error instanceof Error ? error.message : '获取驾驶员详情失败',
        driverLoading: false
      })
    }
  },

  createDriver: async (data) => {
    try {
      const response = await machineryApi.createDriver(data)
      const currentList = get().driverList
      set({
        driverList: [response.data, ...currentList]
      })
    } catch (error) {
      set({
        driverError: error instanceof Error ? error.message : '创建驾驶员失败'
      })
    }
  },

  updateDriver: async (id, data) => {
    try {
      const response = await machineryApi.updateDriver(id, data)
      const currentList = get().driverList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        driverList: updatedList,
        selectedDriver: response.data
      })
    } catch (error) {
      set({
        driverError: error instanceof Error ? error.message : '更新驾驶员失败'
      })
    }
  },

  deleteDriver: async (id) => {
    try {
      await machineryApi.deleteDriver(id)
      const currentList = get().driverList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        driverList: updatedList,
        selectedDriver: null
      })
    } catch (error) {
      set({
        driverError: error instanceof Error ? error.message : '删除驾驶员失败'
      })
    }
  },

  setSelectedDriver: (driver) => set({ selectedDriver: driver }),
  clearDriverError: () => set({ driverError: null }),

  // 监控操作
  fetchRealTimeData: async (machineryId) => {
    try {
      set({ monitoringLoading: true })
      const response = await machineryApi.getRealTimeData(machineryId)
      set({
        realTimeData: response.data,
        monitoringLoading: false
      })
    } catch (error) {
      console.error('获取实时数据失败:', error)
      set({ monitoringLoading: false })
    }
  },

  fetchMonitoringHistory: async (machineryId, params) => {
    try {
      set({ monitoringLoading: true })
      const response = await machineryApi.getMonitoringHistory(machineryId, {
        page: params?.page || 1,
        pageSize: params?.pageSize || 50,
        ...params
      })
      set({
        monitoringData: response.data.items,
        monitoringLoading: false
      })
    } catch (error) {
      console.error('获取监控历史失败:', error)
      set({ monitoringLoading: false })
    }
  }
}))