import { ref, computed } from 'vue'
import notificationService from './notificationService'
import websocketService from './websocketService'

export interface ProcurementItem {
  id: string
  equipmentName: string
  applicantName: string
  status: 'PENDING' | 'APPROVED' | 'REJECTED' | 'PROCESSING' | 'COMPLETED' | 'CANCELLED'
  createTime: string
  updateTime: string
  priority: 'LOW' | 'NORMAL' | 'HIGH' | 'URGENT'
  category: string
  description?: string
  budget?: number
  quantity: number
  unit: string
  expectedDelivery?: string
  approvalHistory: ApprovalRecord[]
  metadata?: Record<string, any>
}

export interface ApprovalRecord {
  id: string
  approverName: string
  action: 'APPROVE' | 'REJECT' | 'COMMENT'
  comment?: string
  timestamp: string
  status: 'PENDING' | 'COMPLETED'
}

class ProcurementSyncService {
  private procurements = ref<ProcurementItem[]>([])
  private isInitialized = ref(false)
  
  // 计算属性
  public readonly pendingCount = computed(() => 
    this.procurements.value.filter(p => p.status === 'PENDING').length
  )
  
  public readonly approvedCount = computed(() => 
    this.procurements.value.filter(p => p.status === 'APPROVED').length
  )
  
  public readonly rejectedCount = computed(() => 
    this.procurements.value.filter(p => p.status === 'REJECTED').length
  )
  
  public readonly processingCount = computed(() => 
    this.procurements.value.filter(p => p.status === 'PROCESSING').length
  )
  
  public readonly completedCount = computed(() => 
    this.procurements.value.filter(p => p.status === 'COMPLETED').length
  )
  
  public readonly urgentCount = computed(() => 
    this.procurements.value.filter(p => p.priority === 'URGENT' && p.status === 'PENDING').length
  )
  
  public readonly highPriorityCount = computed(() => 
    this.procurements.value.filter(p => 
      (p.priority === 'HIGH' || p.priority === 'URGENT') && 
      p.status === 'PENDING'
    ).length
  )
  
  // 获取所有采购项目
  public getAllProcurements() {
    return this.procurements.value
  }
  
  // 获取特定状态的采购项目
  public getProcurementsByStatus(status: ProcurementItem['status']) {
    return this.procurements.value.filter(p => p.status === status)
  }
  
  // 获取特定优先级的采购项目
  public getProcurementsByPriority(priority: ProcurementItem['priority']) {
    return this.procurements.value.filter(p => p.priority === priority)
  }
  
  // 获取待审批的采购项目
  public getPendingProcurements() {
    return this.procurements.value.filter(p => p.status === 'PENDING')
  }
  
  // 获取紧急采购项目
  public getUrgentProcurements() {
    return this.procurements.value.filter(p => 
      p.priority === 'URGENT' && p.status === 'PENDING'
    )
  }
  
  // 根据ID获取采购项目
  public getProcurementById(id: string) {
    return this.procurements.value.find(p => p.id === id)
  }
  
  // 添加采购申请
  public addProcurement(procurement: Omit<ProcurementItem, 'id' | 'createTime' | 'updateTime' | 'approvalHistory'>) {
    const newProcurement: ProcurementItem = {
      ...procurement,
      id: this.generateId(),
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      approvalHistory: []
    }
    
    this.procurements.value.unshift(newProcurement)
    
    // 限制数量，避免内存泄漏
    if (this.procurements.value.length > 500) {
      this.procurements.value = this.procurements.value.slice(0, 500)
    }
    
    // 添加通知
    notificationService.addProcurementNotification(
      newProcurement.equipmentName,
      newProcurement.applicantName
    )
    
    // 触发WebSocket更新
    this.broadcastProcurementUpdate('ADD', newProcurement)
    
    // 保存到本地存储
    this.saveToStorage()
    
    return newProcurement
  }
  
  // 更新采购状态
  public updateProcurementStatus(id: string, status: ProcurementItem['status'], approverName?: string, comment?: string) {
    const procurement = this.procurements.value.find(p => p.id === id)
    if (!procurement) {
      console.warn(`采购项目 ${id} 不存在`)
      return false
    }
    
    const oldStatus = procurement.status
    procurement.status = status
    procurement.updateTime = new Date().toISOString()
    
    // 添加审批记录
    if (approverName) {
      const approvalRecord: ApprovalRecord = {
        id: this.generateId(),
        approverName,
        action: status === 'APPROVED' ? 'APPROVE' : 'REJECT',
        comment,
        timestamp: new Date().toISOString(),
        status: 'COMPLETED'
      }
      procurement.approvalHistory.push(approvalRecord)
    }
    
    // 添加通知
    if (status === 'APPROVED' || status === 'REJECTED') {
      notificationService.addApprovalNotification(
        procurement.equipmentName,
        status,
        approverName || '系统'
      )
    }
    
    // 触发WebSocket更新
    this.broadcastProcurementUpdate('UPDATE', procurement)
    
    // 保存到本地存储
    this.saveToStorage()
    
    console.log(`采购项目 ${id} 状态从 ${oldStatus} 更新为 ${status}`)
    return true
  }
  
  // 批量更新状态
  public batchUpdateStatus(ids: string[], status: ProcurementItem['status'], approverName: string, comment?: string) {
    const results = ids.map(id => this.updateProcurementStatus(id, status, approverName, comment))
    return results.every(result => result)
  }
  
  // 删除采购项目
  public removeProcurement(id: string) {
    const index = this.procurements.value.findIndex(p => p.id === id)
    if (index > -1) {
      const procurement = this.procurements.value[index]
      this.procurements.value.splice(index, 1)
      
      // 触发WebSocket更新
      this.broadcastProcurementUpdate('REMOVE', { id })
      
      // 保存到本地存储
      this.saveToStorage()
      
      return true
    }
    return false
  }
  
  // 搜索采购项目
  public searchProcurements(keyword: string) {
    if (!keyword.trim()) {
      return this.procurements.value
    }
    
    const lowerKeyword = keyword.toLowerCase()
    return this.procurements.value.filter(p => 
      p.equipmentName.toLowerCase().includes(lowerKeyword) ||
      p.applicantName.toLowerCase().includes(lowerKeyword) ||
      p.description?.toLowerCase().includes(lowerKeyword) ||
      p.category.toLowerCase().includes(lowerKeyword)
    )
  }
  
  // 按优先级排序
  public sortByPriority() {
    const priorityOrder = { 'URGENT': 4, 'HIGH': 3, 'NORMAL': 2, 'LOW': 1 }
    
    this.procurements.value.sort((a, b) => {
      const aPriority = priorityOrder[a.priority] || 2
      const bPriority = priorityOrder[b.priority] || 2
      
      if (aPriority !== bPriority) {
        return bPriority - aPriority
      }
      
      // 优先级相同时，按时间倒序
      return new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
    })
  }
  
  // 按时间排序
  public sortByTime() {
    this.procurements.value.sort((a, b) => 
      new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
    )
  }
  
  // 按状态分组
  public groupByStatus() {
    const groups: Record<string, ProcurementItem[]> = {}
    
    this.procurements.value.forEach(procurement => {
      const status = procurement.status
      if (!groups[status]) {
        groups[status] = []
      }
      groups[status].push(procurement)
    })
    
    return groups
  }
  
  // 获取统计信息
  public getStats() {
    const total = this.procurements.value.length
    const pending = this.pendingCount.value
    const approved = this.approvedCount.value
    const rejected = this.rejectedCount.value
    const processing = this.processingCount.value
    const completed = this.completedCount.value
    const urgent = this.urgentCount.value
    const highPriority = this.highPriorityCount.value
    
    return {
      total,
      pending,
      approved,
      rejected,
      processing,
      completed,
      urgent,
      highPriority,
      approvalRate: total > 0 ? ((approved + completed) / total * 100).toFixed(1) : '0.0'
    }
  }
  
  // 导出采购数据
  public exportProcurements() {
    try {
      const data = JSON.stringify(this.procurements.value, null, 2)
      const blob = new Blob([data], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `procurements_${new Date().toISOString().split('T')[0]}.json`
      a.click()
      URL.revokeObjectURL(url)
    } catch (error) {
      console.error('导出采购数据失败:', error)
    }
  }
  
  // 导入采购数据
  public importProcurements(data: string) {
    try {
      const procurements = JSON.parse(data)
      if (Array.isArray(procurements)) {
        this.procurements.value = [...this.procurements.value, ...procurements]
        this.saveToStorage()
        return true
      }
      return false
    } catch (error) {
      console.error('导入采购数据失败:', error)
      return false
    }
  }
  
  // 清空所有数据
  public clearAll() {
    this.procurements.value = []
    this.saveToStorage()
  }
  
  // 初始化服务
  public async initialize() {
    if (this.isInitialized.value) {
      return
    }
    
    try {
      // 从本地存储加载数据
      this.loadFromStorage()
      
      // 设置WebSocket监听
      this.setupWebSocketListeners()
      
      // 设置定期同步
      this.setupPeriodicSync()
      
      this.isInitialized.value = true
      console.log('采购同步服务初始化完成')
    } catch (error) {
      console.error('采购同步服务初始化失败:', error)
    }
  }
  
  // 设置WebSocket监听
  private setupWebSocketListeners() {
    // 监听采购更新消息
    websocketService.on('PROCUREMENT_UPDATE', (data: any) => {
      this.handleWebSocketMessage(data)
    })
    
    // 监听审批更新消息
    websocketService.on('APPROVAL_UPDATE', (data: any) => {
      this.handleApprovalUpdate(data)
    })
    
    // 监听设备状态更新
    websocketService.on('EQUIPMENT_STATUS_UPDATE', (data: any) => {
      this.handleEquipmentStatusUpdate(data)
    })
  }
  
  // 处理WebSocket消息
  private handleWebSocketMessage(data: any) {
    try {
      const { action, procurement } = data
      
      switch (action) {
        case 'ADD':
          if (procurement && !this.procurements.value.find(p => p.id === procurement.id)) {
            this.procurements.value.unshift(procurement)
          }
          break
          
        case 'UPDATE':
          if (procurement) {
            const index = this.procurements.value.findIndex(p => p.id === procurement.id)
            if (index > -1) {
              this.procurements.value[index] = procurement
            }
          }
          break
          
        case 'REMOVE':
          if (data.id) {
            const index = this.procurements.value.findIndex(p => p.id === data.id)
            if (index > -1) {
              this.procurements.value.splice(index, 1)
            }
          }
          break
      }
      
      // 保存到本地存储
      this.saveToStorage()
    } catch (error) {
      console.error('处理WebSocket采购消息失败:', error)
    }
  }
  
  // 处理审批更新
  private handleApprovalUpdate(data: any) {
    try {
      const { procurementId, status, approverName, comment } = data
      this.updateProcurementStatus(procurementId, status, approverName, comment)
    } catch (error) {
      console.error('处理审批更新失败:', error)
    }
  }
  
  // 处理设备状态更新
  private handleEquipmentStatusUpdate(data: any) {
    try {
      const { procurementId, equipmentStatus } = data
      const procurement = this.procurements.value.find(p => p.id === procurementId)
      
      if (procurement) {
        // 根据设备状态更新采购状态
        if (equipmentStatus === 'INSTALLED') {
          this.updateProcurementStatus(procurementId, 'COMPLETED')
        } else if (equipmentStatus === 'IN_TRANSIT') {
          this.updateProcurementStatus(procurementId, 'PROCESSING')
        }
      }
    } catch (error) {
      console.error('处理设备状态更新失败:', error)
    }
  }
  
  // 设置定期同步
  private setupPeriodicSync() {
    // 每5分钟同步一次状态
    setInterval(() => {
      this.syncProcurementStatus()
    }, 5 * 60 * 1000)
  }
  
  // 同步采购状态
  private async syncProcurementStatus() {
    try {
      // 这里可以调用后端API同步最新状态
      // const response = await api.getProcurementStatus()
      // 更新本地状态
      console.log('定期同步采购状态...')
    } catch (error) {
      console.error('同步采购状态失败:', error)
    }
  }
  
  // 广播采购更新
  private broadcastProcurementUpdate(action: string, data: any) {
    if (websocketService.connected.value) {
      websocketService.send({
        type: 'PROCUREMENT_UPDATE',
        data: { action, ...data },
        timestamp: Date.now()
      })
    }
  }
  
  // 生成唯一ID
  private generateId(): string {
    return `procurement_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }
  
  // 持久化存储
  public saveToStorage() {
    try {
      localStorage.setItem('procurements', JSON.stringify(this.procurements.value))
    } catch (error) {
      console.error('保存采购数据到本地存储失败:', error)
    }
  }
  
  public loadFromStorage() {
    try {
      const stored = localStorage.getItem('procurements')
      if (stored) {
        this.procurements.value = JSON.parse(stored)
        
        // 重新排序
        this.sortByPriority()
      }
    } catch (error) {
      console.error('从本地存储加载采购数据失败:', error)
    }
  }
  
  // 获取初始化状态
  public getInitializationStatus() {
    return this.isInitialized.value
  }
}

// 创建单例实例
const procurementSyncService = new ProcurementSyncService()

export default procurementSyncService
