import { io } from 'socket.io-client'
import { useJobsStore } from '@/stores/jobs'
import { ElMessage, ElNotification } from 'element-plus'

/**
 * WebSocket 服務類
 */
class WebSocketService {
  constructor() {
    this.socket = null
    this.isConnected = false
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 5000
    this.jobSubscriptions = new Set()
  }

  /**
   * 初始化並連接 WebSocket
   */
  connect() {
    // 暫時禁用 WebSocket 連接
    console.warn('WebSocket 功能已暫時禁用，避免連接錯誤')
    return
    
    // 以下代碼已暫時禁用
    /*
    if (this.socket) {
      return
    }

    try {
      // 建立 Socket.IO 連接
      const wsUrl = import.meta.env.VITE_WS_BASE_URL || 'ws://127.0.0.1:5000'
      this.socket = io(wsUrl, {
        path: '/socket.io/',
        transports: ['websocket', 'polling'],
        upgrade: true,
        rememberUpgrade: true,
        autoConnect: true,
        forceNew: false,
        reconnection: true,
        reconnectionDelay: this.reconnectInterval,
        reconnectionAttempts: this.maxReconnectAttempts
      })

      this.setupEventHandlers()
    } catch (error) {
      console.error('WebSocket 連接失敗:', error)
    }
    */
  }

  /**
   * 設定事件處理器
   */
  setupEventHandlers() {
    if (!this.socket) return

    // 連接成功
    this.socket.on('connect', () => {
      console.log('WebSocket 已連接')
      this.isConnected = true
      this.reconnectAttempts = 0
      
      // 重新訂閱所有任務
      this.resubscribeJobs()
    })

    // 連接失敗
    this.socket.on('connect_error', (error) => {
      console.error('WebSocket 連接錯誤:', error)
      this.isConnected = false
    })

    // 斷線
    this.socket.on('disconnect', (reason) => {
      console.log('WebSocket 已斷線:', reason)
      this.isConnected = false
      
      if (reason === 'io server disconnect') {
        // 服務器主動斷線，需要重新連接
        this.socket.connect()
      }
    })

    // 任務狀態更新
    this.socket.on('job_status', (data) => {
      this.handleJobStatusUpdate(data)
    })

    // 系統通知
    this.socket.on('system_notification', (data) => {
      this.handleSystemNotification(data)
    })

    // 連接狀態回應
    this.socket.on('connected', (data) => {
      console.log('WebSocket 連接確認:', data)
    })

    // 訂閱成功回應
    this.socket.on('subscribed', (data) => {
      console.log('任務訂閱成功:', data.job_uuid)
    })

    // 取消訂閱成功回應
    this.socket.on('unsubscribed', (data) => {
      console.log('任務取消訂閱成功:', data.job_uuid)
    })

    // 錯誤處理
    this.socket.on('error', (error) => {
      console.error('WebSocket 錯誤:', error)
      ElMessage.error(error.message || 'WebSocket 連接錯誤')
    })
  }

  /**
   * 處理任務狀態更新
   * @param {Object} data - 狀態更新資料
   */
  handleJobStatusUpdate(data) {
    try {
      if (data.type === 'job_status' && data.data) {
        const jobsStore = useJobsStore()
        const { job_uuid, ...statusUpdate } = data.data
        
        // 更新任務狀態
        jobsStore.updateJobStatus(job_uuid, statusUpdate)
        
        console.log('任務狀態已更新:', job_uuid, statusUpdate)
      }
    } catch (error) {
      console.error('處理任務狀態更新失敗:', error)
    }
  }

  /**
   * 處理系統通知
   * @param {Object} data - 通知資料
   */
  handleSystemNotification(data) {
    const { type, message, title, level } = data
    
    switch (level) {
      case 'success':
        ElNotification.success({
          title: title || '系統通知',
          message: message,
          duration: 5000
        })
        break
        
      case 'warning':
        ElNotification.warning({
          title: title || '系統警告',
          message: message,
          duration: 8000
        })
        break
        
      case 'error':
        ElNotification.error({
          title: title || '系統錯誤',
          message: message,
          duration: 10000
        })
        break
        
      default:
        ElNotification({
          title: title || '系統消息',
          message: message,
          duration: 5000
        })
    }
  }

  /**
   * 訂閱任務狀態更新
   * @param {string} jobUuid - 任務 UUID
   */
  subscribeToJob(jobUuid) {
    if (!this.socket || !this.isConnected) {
      // 靜默處理，避免控制台警告
      return
    }

    if (this.jobSubscriptions.has(jobUuid)) {
      return // 已經訂閱過
    }

    this.socket.emit('subscribe_job', { job_uuid: jobUuid })
    this.jobSubscriptions.add(jobUuid)
  }

  /**
   * 取消訂閱任務狀態更新
   * @param {string} jobUuid - 任務 UUID
   */
  unsubscribeFromJob(jobUuid) {
    if (!this.socket || !this.isConnected) {
      return
    }

    this.socket.emit('unsubscribe_job', { job_uuid: jobUuid })
    this.jobSubscriptions.delete(jobUuid)
  }

  /**
   * 重新訂閱所有任務
   */
  resubscribeJobs() {
    if (!this.isConnected) return
    
    this.jobSubscriptions.forEach(jobUuid => {
      this.socket.emit('subscribe_job', { job_uuid: jobUuid })
    })
  }

  /**
   * 批量訂閱任務
   * @param {string[]} jobUuids - 任務 UUID 陣列
   */
  subscribeToJobs(jobUuids) {
    jobUuids.forEach(jobUuid => {
      this.subscribeToJob(jobUuid)
    })
  }

  /**
   * 批量取消訂閱任務
   * @param {string[]} jobUuids - 任務 UUID 陣列
   */
  unsubscribeFromJobs(jobUuids) {
    jobUuids.forEach(jobUuid => {
      this.unsubscribeFromJob(jobUuid)
    })
  }

  /**
   * 發送自定義事件
   * @param {string} event - 事件名稱
   * @param {Object} data - 事件資料
   */
  emit(event, data) {
    if (this.socket && this.isConnected) {
      this.socket.emit(event, data)
    }
  }

  /**
   * 監聽自定義事件
   * @param {string} event - 事件名稱
   * @param {Function} callback - 回調函數
   */
  on(event, callback) {
    if (this.socket) {
      this.socket.on(event, callback)
    }
  }

  /**
   * 取消監聽事件
   * @param {string} event - 事件名稱
   * @param {Function} callback - 回調函數
   */
  off(event, callback) {
    if (this.socket) {
      this.socket.off(event, callback)
    }
  }

  /**
   * 斷開連接
   */
  disconnect() {
    if (this.socket) {
      this.jobSubscriptions.clear()
      this.socket.disconnect()
      this.socket = null
      this.isConnected = false
      console.log('WebSocket 已主動斷開')
    }
  }

  /**
   * 重新連接
   */
  reconnect() {
    this.disconnect()
    setTimeout(() => {
      this.connect()
    }, 1000)
  }

  /**
   * 取得連接狀態
   */
  getConnectionStatus() {
    return {
      isConnected: this.isConnected,
      socket: this.socket,
      subscriptions: Array.from(this.jobSubscriptions)
    }
  }
}

// 創建全局實例
export const websocketService = new WebSocketService()

// 自動連接（在需要時）
export const initWebSocket = () => {
  websocketService.connect()
}

// 清理連接（在登出時）
export const cleanupWebSocket = () => {
  websocketService.disconnect()
}

export default websocketService