import { create } from 'zustand'
import { LandParcel, LandClassification, MapLayer, SpatialAnalysis } from '@api/modules/land'
import { landApi } from '@api'
import { QueryRequest } from '@api/types'

interface LandState {
  // 地块数据
  landParcelList: LandParcel[]
  selectedLandParcel: LandParcel | null
  landLoading: boolean
  landError: string | null
  landPagination: {
    page: number
    pageSize: number
    total: number
  }

  // 分类数据
  classificationList: LandClassification[]
  selectedClassification: LandClassification | null
  classificationLoading: boolean

  // 地图数据
  mapLayers: MapLayer[]
  mapLoading: boolean

  // 分析数据
  analysisList: SpatialAnalysis[]
  selectedAnalysis: SpatialAnalysis | null
  analysisLoading: boolean
  analysisPagination: {
    page: number
    pageSize: number
    total: number
  }
}

interface LandActions {
  // 地块操作
  fetchLandParcelList: (params?: QueryRequest) => Promise<void>
  fetchLandParcelDetail: (id: string) => Promise<void>
  createLandParcel: (data: Omit<LandParcel, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>
  updateLandParcel: (id: string, data: Partial<LandParcel>) => Promise<void>
  deleteLandParcel: (id: string) => Promise<void>
  setSelectedLandParcel: (landParcel: LandParcel | null) => void
  clearLandError: () => void

  // 分类操作
  fetchClassificationList: (params?: QueryRequest) => Promise<void>
  createClassification: (data: Omit<LandClassification, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>
  updateClassification: (id: string, data: Partial<LandClassification>) => Promise<void>
  deleteClassification: (id: string) => Promise<void>

  // 地图操作
  fetchMapLayers: () => Promise<void>
  createMapLayer: (data: Omit<MapLayer, 'id'>) => Promise<void>
  updateMapLayer: (id: string, data: Partial<MapLayer>) => Promise<void>
  deleteMapLayer: (id: string) => Promise<void>

  // 分析操作
  performSpatialAnalysis: (data: Omit<SpatialAnalysis, 'id' | 'createdAt' | 'result'>) => Promise<void>
  fetchAnalysisHistory: (params?: QueryRequest) => Promise<void>
  setSelectedAnalysis: (analysis: SpatialAnalysis | null) => void
}

export const useLandStore = create<LandState & LandActions>((set, get) => ({
  // 初始状态
  landParcelList: [],
  selectedLandParcel: null,
  landLoading: false,
  landError: null,
  landPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  classificationList: [],
  selectedClassification: null,
  classificationLoading: false,

  mapLayers: [],
  mapLoading: false,

  analysisList: [],
  selectedAnalysis: null,
  analysisLoading: false,
  analysisPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  // 地块操作
  fetchLandParcelList: async (params) => {
    try {
      set({ landLoading: true, landError: null })
      const response = await landApi.getLandParcelList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })

      set({
        landParcelList: response.data.items,
        landPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        landLoading: false
      })
    } catch (error) {
      set({
        landError: error instanceof Error ? error.message : '获取地块列表失败',
        landLoading: false
      })
    }
  },

  fetchLandParcelDetail: async (id) => {
    try {
      set({ landLoading: true, landError: null })
      const response = await landApi.getLandParcelDetail(id)
      set({
        selectedLandParcel: response.data,
        landLoading: false
      })
    } catch (error) {
      set({
        landError: error instanceof Error ? error.message : '获取地块详情失败',
        landLoading: false
      })
    }
  },

  createLandParcel: async (data) => {
    try {
      const response = await landApi.createLandParcel(data)
      const currentList = get().landParcelList
      set({
        landParcelList: [response.data, ...currentList]
      })
    } catch (error) {
      set({
        landError: error instanceof Error ? error.message : '创建地块失败'
      })
    }
  },

  updateLandParcel: async (id, data) => {
    try {
      const response = await landApi.updateLandParcel(id, data)
      const currentList = get().landParcelList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        landParcelList: updatedList,
        selectedLandParcel: response.data
      })
    } catch (error) {
      set({
        landError: error instanceof Error ? error.message : '更新地块失败'
      })
    }
  },

  deleteLandParcel: async (id) => {
    try {
      await landApi.deleteLandParcel(id)
      const currentList = get().landParcelList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        landParcelList: updatedList,
        selectedLandParcel: null
      })
    } catch (error) {
      set({
        landError: error instanceof Error ? error.message : '删除地块失败'
      })
    }
  },

  setSelectedLandParcel: (landParcel) => set({ selectedLandParcel: landParcel }),
  clearLandError: () => set({ landError: null }),

  // 分类操作
  fetchClassificationList: async (params) => {
    try {
      set({ classificationLoading: true })
      const response = await landApi.getClassificationList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 50,
        ...params
      })
      set({
        classificationList: response.data.items,
        classificationLoading: false
      })
    } catch (error) {
      console.error('获取分类列表失败:', error)
      set({ classificationLoading: false })
    }
  },

  createClassification: async (data) => {
    try {
      const response = await landApi.createClassification(data)
      const currentList = get().classificationList
      set({
        classificationList: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('创建分类失败:', error)
    }
  },

  updateClassification: async (id, data) => {
    try {
      const response = await landApi.updateClassification(id, data)
      const currentList = get().classificationList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        classificationList: updatedList,
        selectedClassification: response.data
      })
    } catch (error) {
      console.error('更新分类失败:', error)
    }
  },

  deleteClassification: async (id) => {
    try {
      await landApi.deleteClassification(id)
      const currentList = get().classificationList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        classificationList: updatedList,
        selectedClassification: null
      })
    } catch (error) {
      console.error('删除分类失败:', error)
    }
  },

  // 地图操作
  fetchMapLayers: async () => {
    try {
      set({ mapLoading: true })
      const response = await landApi.getMapLayers()
      set({
        mapLayers: response.data,
        mapLoading: false
      })
    } catch (error) {
      console.error('获取地图图层失败:', error)
      set({ mapLoading: false })
    }
  },

  createMapLayer: async (data) => {
    try {
      const response = await landApi.createMapLayer(data)
      const currentList = get().mapLayers
      set({
        mapLayers: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('创建地图图层失败:', error)
    }
  },

  updateMapLayer: async (id, data) => {
    try {
      const response = await landApi.updateMapLayer(id, data)
      const currentList = get().mapLayers
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        mapLayers: updatedList
      })
    } catch (error) {
      console.error('更新地图图层失败:', error)
    }
  },

  deleteMapLayer: async (id) => {
    try {
      await landApi.deleteMapLayer(id)
      const currentList = get().mapLayers
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        mapLayers: updatedList
      })
    } catch (error) {
      console.error('删除地图图层失败:', error)
    }
  },

  // 分析操作
  performSpatialAnalysis: async (data) => {
    try {
      set({ analysisLoading: true })
      const response = await landApi.performSpatialAnalysis(data)
      const currentList = get().analysisList
      set({
        analysisList: [response.data, ...currentList],
        analysisLoading: false
      })
    } catch (error) {
      console.error('执行空间分析失败:', error)
      set({ analysisLoading: false })
    }
  },

  fetchAnalysisHistory: async (params) => {
    try {
      set({ analysisLoading: true })
      const response = await landApi.getAnalysisHistory({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })
      set({
        analysisList: response.data.items,
        analysisPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        analysisLoading: false
      })
    } catch (error) {
      console.error('获取分析历史失败:', error)
      set({ analysisLoading: false })
    }
  },

  setSelectedAnalysis: (analysis) => set({ selectedAnalysis: analysis })
}))