import { create } from 'zustand'
import {
  Tenant,
  User,
  SystemParameter,
  SystemLog,
  Message
} from '@api/modules/config'
import { configApi } from '@api'
import { QueryRequest } from '@api/types'

interface ConfigState {
  // 租户数据
  tenantList: Tenant[]
  selectedTenant: Tenant | null
  tenantLoading: boolean
  tenantPagination: {
    page: number
    pageSize: number
    total: number
  }

  // 用户数据
  userList: User[]
  selectedUser: User | null
  userLoading: boolean
  userPagination: {
    page: number
    pageSize: number
    total: number
  }

  // 系统参数数据
  parameterList: SystemParameter[]
  selectedParameter: SystemParameter | null
  parameterLoading: boolean
  parameterPagination: {
    page: number
    pageSize: number
    total: number
  }

  // 系统日志数据
  logList: SystemLog[]
  logLoading: boolean
  logPagination: {
    page: number
    pageSize: number
    total: number
  }

  // 消息数据
  messageList: Message[]
  selectedMessage: Message | null
  messageLoading: boolean
  messagePagination: {
    page: number
    pageSize: number
    total: number
  }
  unreadCount: number

  // 系统指标数据
  systemMetrics: {
    totalUsers: number
    activeUsers: number
    totalTenants: number
    activeTenants: number
    systemUptime: number
    cpuUsage: number
    memoryUsage: number
    diskUsage: number
    databaseConnections: number
  } | null

  systemHealth: {
    status: 'healthy' | 'warning' | 'critical'
    services: Array<{
      name: string
      status: 'up' | 'down'
      responseTime: number
      lastCheck: string
    }>
    issues: Array<{
      type: 'error' | 'warning'
      message: string
      timestamp: string
    }>
  } | null
}

interface ConfigActions {
  // 租户操作
  fetchTenantList: (params?: QueryRequest) => Promise<void>
  fetchTenantDetail: (id: string) => Promise<void>
  createTenant: (data: Omit<Tenant, 'id' | 'createdAt' | 'updatedAt' | 'currentUsers'>) => Promise<void>
  updateTenant: (id: string, data: Partial<Tenant>) => Promise<void>
  deleteTenant: (id: string) => Promise<void>
  suspendTenant: (id: string) => Promise<void>
  activateTenant: (id: string) => Promise<void>
  setSelectedTenant: (tenant: Tenant | null) => void

  // 用户操作
  fetchUserList: (params?: QueryRequest) => Promise<void>
  fetchUserDetail: (id: string) => Promise<void>
  createUser: (data: Omit<User, 'id' | 'createdAt' | 'updatedAt' | 'lastLoginAt'>) => Promise<void>
  updateUser: (id: string, data: Partial<User>) => Promise<void>
  deleteUser: (id: string) => Promise<void>
  resetPassword: (id: string, newPassword: string) => Promise<void>
  lockUser: (id: string) => Promise<void>
  unlockUser: (id: string) => Promise<void>
  setSelectedUser: (user: User | null) => void

  // 系统参数操作
  fetchParameterList: (params?: QueryRequest) => Promise<void>
  fetchParameterDetail: (id: string) => Promise<void>
  createParameter: (data: Omit<SystemParameter, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>
  updateParameter: (id: string, data: Partial<SystemParameter>) => Promise<void>
  deleteParameter: (id: string) => Promise<void>
  getParametersByCategory: (category: string) => Promise<void>
  setSelectedParameter: (parameter: SystemParameter | null) => void

  // 系统监控操作
  fetchSystemLogs: (params?: QueryRequest & { level?: string; category?: string }) => Promise<void>
  fetchSystemMetrics: () => Promise<void>
  fetchSystemHealth: () => Promise<void>

  // 消息操作
  fetchMessageList: (params?: QueryRequest) => Promise<void>
  fetchMessageDetail: (id: string) => Promise<void>
  createMessage: (data: Omit<Message, 'id' | 'createdAt' | 'readAt' | 'status'>) => Promise<void>
  markMessageAsRead: (id: string) => Promise<void>
  archiveMessage: (id: string) => Promise<void>
  deleteMessage: (id: string) => Promise<void>
  getUnreadCount: () => Promise<void>
  setSelectedMessage: (message: Message | null) => void
}

export const useConfigStore = create<ConfigState & ConfigActions>((set, get) => ({
  // 初始状态
  tenantList: [],
  selectedTenant: null,
  tenantLoading: false,
  tenantPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  userList: [],
  selectedUser: null,
  userLoading: false,
  userPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  parameterList: [],
  selectedParameter: null,
  parameterLoading: false,
  parameterPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  logList: [],
  logLoading: false,
  logPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  messageList: [],
  selectedMessage: null,
  messageLoading: false,
  messagePagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },
  unreadCount: 0,

  systemMetrics: null,
  systemHealth: null,

  // 租户操作
  fetchTenantList: async (params) => {
    try {
      set({ tenantLoading: true })
      const response = await configApi.getTenantList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })
      set({
        tenantList: response.data.items,
        tenantPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        tenantLoading: false
      })
    } catch (error) {
      console.error('获取租户列表失败:', error)
      set({ tenantLoading: false })
    }
  },

  fetchTenantDetail: async (id) => {
    try {
      set({ tenantLoading: true })
      const response = await configApi.getTenantDetail(id)
      set({
        selectedTenant: response.data,
        tenantLoading: false
      })
    } catch (error) {
      console.error('获取租户详情失败:', error)
      set({ tenantLoading: false })
    }
  },

  createTenant: async (data) => {
    try {
      const response = await configApi.createTenant(data)
      const currentList = get().tenantList
      set({
        tenantList: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('创建租户失败:', error)
    }
  },

  updateTenant: async (id, data) => {
    try {
      const response = await configApi.updateTenant(id, data)
      const currentList = get().tenantList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        tenantList: updatedList,
        selectedTenant: response.data
      })
    } catch (error) {
      console.error('更新租户失败:', error)
    }
  },

  deleteTenant: async (id) => {
    try {
      await configApi.deleteTenant(id)
      const currentList = get().tenantList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        tenantList: updatedList,
        selectedTenant: null
      })
    } catch (error) {
      console.error('删除租户失败:', error)
    }
  },

  suspendTenant: async (id) => {
    try {
      const response = await configApi.suspendTenant(id)
      const currentList = get().tenantList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        tenantList: updatedList,
        selectedTenant: response.data
      })
    } catch (error) {
      console.error('暂停租户失败:', error)
    }
  },

  activateTenant: async (id) => {
    try {
      const response = await configApi.activateTenant(id)
      const currentList = get().tenantList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        tenantList: updatedList,
        selectedTenant: response.data
      })
    } catch (error) {
      console.error('激活租户失败:', error)
    }
  },

  setSelectedTenant: (tenant) => set({ selectedTenant: tenant }),

  // 用户操作
  fetchUserList: async (params) => {
    try {
      set({ userLoading: true })
      const response = await configApi.getUserList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })
      set({
        userList: response.data.items,
        userPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        userLoading: false
      })
    } catch (error) {
      console.error('获取用户列表失败:', error)
      set({ userLoading: false })
    }
  },

  fetchUserDetail: async (id) => {
    try {
      set({ userLoading: true })
      const response = await configApi.getUserDetail(id)
      set({
        selectedUser: response.data,
        userLoading: false
      })
    } catch (error) {
      console.error('获取用户详情失败:', error)
      set({ userLoading: false })
    }
  },

  createUser: async (data) => {
    try {
      const response = await configApi.createUser(data)
      const currentList = get().userList
      set({
        userList: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('创建用户失败:', error)
    }
  },

  updateUser: async (id, data) => {
    try {
      const response = await configApi.updateUser(id, data)
      const currentList = get().userList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        userList: updatedList,
        selectedUser: response.data
      })
    } catch (error) {
      console.error('更新用户失败:', error)
    }
  },

  deleteUser: async (id) => {
    try {
      await configApi.deleteUser(id)
      const currentList = get().userList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        userList: updatedList,
        selectedUser: null
      })
    } catch (error) {
      console.error('删除用户失败:', error)
    }
  },

  resetPassword: async (id, newPassword) => {
    try {
      await configApi.resetPassword(id, newPassword)
    } catch (error) {
      console.error('重置密码失败:', error)
    }
  },

  lockUser: async (id) => {
    try {
      const response = await configApi.lockUser(id)
      const currentList = get().userList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        userList: updatedList,
        selectedUser: response.data
      })
    } catch (error) {
      console.error('锁定用户失败:', error)
    }
  },

  unlockUser: async (id) => {
    try {
      const response = await configApi.unlockUser(id)
      const currentList = get().userList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        userList: updatedList,
        selectedUser: response.data
      })
    } catch (error) {
      console.error('解锁用户失败:', error)
    }
  },

  setSelectedUser: (user) => set({ selectedUser: user }),

  // 系统参数操作
  fetchParameterList: async (params) => {
    try {
      set({ parameterLoading: true })
      const response = await configApi.getParameterList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })
      set({
        parameterList: response.data.items,
        parameterPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        parameterLoading: false
      })
    } catch (error) {
      console.error('获取系统参数列表失败:', error)
      set({ parameterLoading: false })
    }
  },

  fetchParameterDetail: async (id) => {
    try {
      set({ parameterLoading: true })
      const response = await configApi.getParameterDetail(id)
      set({
        selectedParameter: response.data,
        parameterLoading: false
      })
    } catch (error) {
      console.error('获取系统参数详情失败:', error)
      set({ parameterLoading: false })
    }
  },

  createParameter: async (data) => {
    try {
      const response = await configApi.createParameter(data)
      const currentList = get().parameterList
      set({
        parameterList: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('创建系统参数失败:', error)
    }
  },

  updateParameter: async (id, data) => {
    try {
      const response = await configApi.updateParameter(id, data)
      const currentList = get().parameterList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        parameterList: updatedList,
        selectedParameter: response.data
      })
    } catch (error) {
      console.error('更新系统参数失败:', error)
    }
  },

  deleteParameter: async (id) => {
    try {
      await configApi.deleteParameter(id)
      const currentList = get().parameterList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        parameterList: updatedList,
        selectedParameter: null
      })
    } catch (error) {
      console.error('删除系统参数失败:', error)
    }
  },

  getParametersByCategory: async (category) => {
    try {
      set({ parameterLoading: true })
      const response = await configApi.getParametersByCategory(category)
      set({
        parameterList: response.data,
        parameterLoading: false
      })
    } catch (error) {
      console.error('获取分类参数失败:', error)
      set({ parameterLoading: false })
    }
  },

  setSelectedParameter: (parameter) => set({ selectedParameter: parameter }),

  // 系统监控操作
  fetchSystemLogs: async (params) => {
    try {
      set({ logLoading: true })
      const response = await configApi.getSystemLogs({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })
      set({
        logList: response.data.items,
        logPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        logLoading: false
      })
    } catch (error) {
      console.error('获取系统日志失败:', error)
      set({ logLoading: false })
    }
  },

  fetchSystemMetrics: async () => {
    try {
      const response = await configApi.getSystemMetrics()
      set({
        systemMetrics: response.data
      })
    } catch (error) {
      console.error('获取系统指标失败:', error)
    }
  },

  fetchSystemHealth: async () => {
    try {
      const response = await configApi.getSystemHealth()
      set({
        systemHealth: response.data
      })
    } catch (error) {
      console.error('获取系统健康状态失败:', error)
    }
  },

  // 消息操作
  fetchMessageList: async (params) => {
    try {
      set({ messageLoading: true })
      const response = await configApi.getMessageList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })
      set({
        messageList: response.data.items,
        messagePagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        messageLoading: false
      })
    } catch (error) {
      console.error('获取消息列表失败:', error)
      set({ messageLoading: false })
    }
  },

  fetchMessageDetail: async (id) => {
    try {
      set({ messageLoading: true })
      const response = await configApi.getMessageDetail(id)
      set({
        selectedMessage: response.data,
        messageLoading: false
      })
    } catch (error) {
      console.error('获取消息详情失败:', error)
      set({ messageLoading: false })
    }
  },

  createMessage: async (data) => {
    try {
      const response = await configApi.createMessage(data)
      const currentList = get().messageList
      set({
        messageList: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('创建消息失败:', error)
    }
  },

  markMessageAsRead: async (id) => {
    try {
      const response = await configApi.markMessageAsRead(id)
      const currentList = get().messageList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        messageList: updatedList,
        selectedMessage: response.data
      })
    } catch (error) {
      console.error('标记消息已读失败:', error)
    }
  },

  archiveMessage: async (id) => {
    try {
      const response = await configApi.archiveMessage(id)
      const currentList = get().messageList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        messageList: updatedList,
        selectedMessage: response.data
      })
    } catch (error) {
      console.error('归档消息失败:', error)
    }
  },

  deleteMessage: async (id) => {
    try {
      await configApi.deleteMessage(id)
      const currentList = get().messageList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        messageList: updatedList,
        selectedMessage: null
      })
    } catch (error) {
      console.error('删除消息失败:', error)
    }
  },

  getUnreadCount: async () => {
    try {
      const response = await configApi.getUnreadCount()
      set({
        unreadCount: response.data.count
      })
    } catch (error) {
      console.error('获取未读消息数量失败:', error)
    }
  },

  setSelectedMessage: (message) => set({ selectedMessage: message })
}))