import { create } from 'zustand'
import {
  IrrigationSystem,
  IrrigationZone,
  IrrigationSchedule,
  MonitoringData,
  ControlCommand
} from '@api/modules/irrigation'
import { irrigationApi } from '@api'
import { QueryRequest } from '@api/types'

interface IrrigationState {
  // 系统数据
  systemList: IrrigationSystem[]
  selectedSystem: IrrigationSystem | null
  systemLoading: boolean
  systemPagination: {
    page: number
    pageSize: number
    total: number
  }

  // 分区数据
  zoneList: IrrigationZone[]
  selectedZone: IrrigationZone | null
  zoneLoading: boolean

  // 调度数据
  scheduleList: IrrigationSchedule[]
  selectedSchedule: IrrigationSchedule | null
  scheduleLoading: boolean
  schedulePagination: {
    page: number
    pageSize: number
    total: number
  }

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

  // 控制命令
  controlCommands: ControlCommand[]
  controlLoading: boolean
}

interface IrrigationActions {
  // 系统操作
  fetchSystemList: (params?: QueryRequest) => Promise<void>
  fetchSystemDetail: (id: string) => Promise<void>
  createSystem: (data: Omit<IrrigationSystem, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>
  updateSystem: (id: string, data: Partial<IrrigationSystem>) => Promise<void>
  deleteSystem: (id: string) => Promise<void>
  startIrrigation: (systemId: string, zoneId?: string, duration?: number) => Promise<void>
  stopIrrigation: (systemId: string, zoneId?: string) => Promise<void>
  setSelectedSystem: (system: IrrigationSystem | null) => void

  // 分区操作
  fetchZoneList: (systemId: string, params?: QueryRequest) => Promise<void>
  fetchZoneDetail: (id: string) => Promise<void>
  createZone: (data: Omit<IrrigationZone, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>
  updateZone: (id: string, data: Partial<IrrigationZone>) => Promise<void>
  deleteZone: (id: string) => Promise<void>
  setSelectedZone: (zone: IrrigationZone | null) => void

  // 调度操作
  fetchScheduleList: (params?: QueryRequest) => Promise<void>
  fetchScheduleDetail: (id: string) => Promise<void>
  createSchedule: (data: Omit<IrrigationSchedule, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>
  updateSchedule: (id: string, data: Partial<IrrigationSchedule>) => Promise<void>
  deleteSchedule: (id: string) => Promise<void>
  pauseSchedule: (id: string) => Promise<void>
  resumeSchedule: (id: string) => Promise<void>
  setSelectedSchedule: (schedule: IrrigationSchedule | null) => void

  // 监控操作
  fetchMonitoringData: (zoneId: string, params?: QueryRequest & { sensorType?: string }) => Promise<void>
  fetchRealTimeData: (zoneId: string) => Promise<void>

  // 清理操作
  clearData: () => void
}

export const useIrrigationStore = create<IrrigationState & IrrigationActions>((set, get) => ({
  // 初始状态
  systemList: [],
  selectedSystem: null,
  systemLoading: false,
  systemPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  zoneList: [],
  selectedZone: null,
  zoneLoading: false,

  scheduleList: [],
  selectedSchedule: null,
  scheduleLoading: false,
  schedulePagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

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

  controlCommands: [],
  controlLoading: false,

  // 系统操作
  fetchSystemList: async (params) => {
    try {
      set({ systemLoading: true })
      const response = await irrigationApi.getSystemList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })
      set({
        systemList: response.data.items,
        systemPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        systemLoading: false
      })
    } catch (error) {
      console.error('获取灌溉系统列表失败:', error)
      set({ systemLoading: false })
    }
  },

  fetchSystemDetail: async (id) => {
    try {
      set({ systemLoading: true })
      const response = await irrigationApi.getSystemDetail(id)
      set({
        selectedSystem: response.data,
        systemLoading: false
      })
    } catch (error) {
      console.error('获取灌溉系统详情失败:', error)
      set({ systemLoading: false })
    }
  },

  createSystem: async (data) => {
    try {
      const response = await irrigationApi.createSystem(data)
      const currentList = get().systemList
      set({
        systemList: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('创建灌溉系统失败:', error)
    }
  },

  updateSystem: async (id, data) => {
    try {
      const response = await irrigationApi.updateSystem(id, data)
      const currentList = get().systemList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        systemList: updatedList,
        selectedSystem: response.data
      })
    } catch (error) {
      console.error('更新灌溉系统失败:', error)
    }
  },

  deleteSystem: async (id) => {
    try {
      await irrigationApi.deleteSystem(id)
      const currentList = get().systemList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        systemList: updatedList,
        selectedSystem: null
      })
    } catch (error) {
      console.error('删除灌溉系统失败:', error)
    }
  },

  startIrrigation: async (systemId, zoneId, duration) => {
    try {
      set({ controlLoading: true })
      const response = await irrigationApi.startIrrigation(systemId, zoneId, duration)
      const currentCommands = get().controlCommands
      set({
        controlCommands: [response.data, ...currentCommands],
        controlLoading: false
      })
    } catch (error) {
      console.error('启动灌溉失败:', error)
      set({ controlLoading: false })
    }
  },

  stopIrrigation: async (systemId, zoneId) => {
    try {
      set({ controlLoading: true })
      const response = await irrigationApi.stopIrrigation(systemId, zoneId)
      const currentCommands = get().controlCommands
      set({
        controlCommands: [response.data, ...currentCommands],
        controlLoading: false
      })
    } catch (error) {
      console.error('停止灌溉失败:', error)
      set({ controlLoading: false })
    }
  },

  setSelectedSystem: (system) => set({ selectedSystem: system }),

  // 分区操作
  fetchZoneList: async (systemId, params) => {
    try {
      set({ zoneLoading: true })
      const response = await irrigationApi.getZoneList(systemId, {
        page: params?.page || 1,
        pageSize: params?.pageSize || 20,
        ...params
      })
      set({
        zoneList: response.data.items,
        zoneLoading: false
      })
    } catch (error) {
      console.error('获取灌溉分区列表失败:', error)
      set({ zoneLoading: false })
    }
  },

  fetchZoneDetail: async (id) => {
    try {
      set({ zoneLoading: true })
      const response = await irrigationApi.getZoneDetail(id)
      set({
        selectedZone: response.data,
        zoneLoading: false
      })
    } catch (error) {
      console.error('获取灌溉分区详情失败:', error)
      set({ zoneLoading: false })
    }
  },

  createZone: async (data) => {
    try {
      const response = await irrigationApi.createZone(data)
      const currentList = get().zoneList
      set({
        zoneList: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('创建灌溉分区失败:', error)
    }
  },

  updateZone: async (id, data) => {
    try {
      const response = await irrigationApi.updateZone(id, data)
      const currentList = get().zoneList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        zoneList: updatedList,
        selectedZone: response.data
      })
    } catch (error) {
      console.error('更新灌溉分区失败:', error)
    }
  },

  deleteZone: async (id) => {
    try {
      await irrigationApi.deleteZone(id)
      const currentList = get().zoneList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        zoneList: updatedList,
        selectedZone: null
      })
    } catch (error) {
      console.error('删除灌溉分区失败:', error)
    }
  },

  setSelectedZone: (zone) => set({ selectedZone: zone }),

  // 调度操作
  fetchScheduleList: async (params) => {
    try {
      set({ scheduleLoading: true })
      const response = await irrigationApi.getScheduleList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })
      set({
        scheduleList: response.data.items,
        schedulePagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        scheduleLoading: false
      })
    } catch (error) {
      console.error('获取灌溉调度列表失败:', error)
      set({ scheduleLoading: false })
    }
  },

  fetchScheduleDetail: async (id) => {
    try {
      set({ scheduleLoading: true })
      const response = await irrigationApi.getScheduleDetail(id)
      set({
        selectedSchedule: response.data,
        scheduleLoading: false
      })
    } catch (error) {
      console.error('获取灌溉调度详情失败:', error)
      set({ scheduleLoading: false })
    }
  },

  createSchedule: async (data) => {
    try {
      const response = await irrigationApi.createSchedule(data)
      const currentList = get().scheduleList
      set({
        scheduleList: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('创建灌溉调度失败:', error)
    }
  },

  updateSchedule: async (id, data) => {
    try {
      const response = await irrigationApi.updateSchedule(id, data)
      const currentList = get().scheduleList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        scheduleList: updatedList,
        selectedSchedule: response.data
      })
    } catch (error) {
      console.error('更新灌溉调度失败:', error)
    }
  },

  deleteSchedule: async (id) => {
    try {
      await irrigationApi.deleteSchedule(id)
      const currentList = get().scheduleList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        scheduleList: updatedList,
        selectedSchedule: null
      })
    } catch (error) {
      console.error('删除灌溉调度失败:', error)
    }
  },

  pauseSchedule: async (id) => {
    try {
      const response = await irrigationApi.pauseSchedule(id)
      const currentList = get().scheduleList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        scheduleList: updatedList,
        selectedSchedule: response.data
      })
    } catch (error) {
      console.error('暂停灌溉调度失败:', error)
    }
  },

  resumeSchedule: async (id) => {
    try {
      const response = await irrigationApi.resumeSchedule(id)
      const currentList = get().scheduleList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        scheduleList: updatedList,
        selectedSchedule: response.data
      })
    } catch (error) {
      console.error('恢复灌溉调度失败:', error)
    }
  },

  setSelectedSchedule: (schedule) => set({ selectedSchedule: schedule }),

  // 监控操作
  fetchMonitoringData: async (zoneId, params) => {
    try {
      set({ monitoringLoading: true })
      const response = await irrigationApi.getMonitoringData(zoneId, {
        page: params?.page || 1,
        pageSize: params?.pageSize || 50,
        ...params
      })
      set({
        monitoringData: response.data.items,
        monitoringLoading: false
      })
    } catch (error) {
      console.error('获取监控数据失败:', error)
      set({ monitoringLoading: false })
    }
  },

  fetchRealTimeData: async (zoneId) => {
    try {
      const response = await irrigationApi.getRealTimeData(zoneId)
      set({
        realTimeData: response.data
      })
    } catch (error) {
      console.error('获取实时数据失败:', error)
    }
  },

  clearData: () => set({
    zoneList: [],
    selectedZone: null,
    scheduleList: [],
    selectedSchedule: null,
    monitoringData: [],
    realTimeData: [],
    controlCommands: []
  })
}))