<template>
  <div class="websocket-progress">
    <a-progress
      :percent="progressValue"
      status="active"
      style="padding-right: 20px;" />

    <!-- 连接状态指示 -->
    <div v-if="showConnectionStatus" class="connection-status">
      <a-tooltip :title="connectionStatusText">
        <a-badge
          :status="connectionBadgeStatus"
          :text="connectionStatusText"
        />
      </a-tooltip>
    </div>
  </div>
</template>

<script>
import { useWebSocket } from '@vue2-client/utils/websocket/websocket'
import { isDebugUser } from '@vue2-client/utils/common'

export default {
  name: 'XWebSocketProgress',
  components: {
  },
  props: {
    // WebSocket 唯一标识
    websocketId: {
      type: String,
      required: true,
    },
    // 初始进度值
    initialValue: {
      type: Number,
      default: 0
    },
    // 自动重连
    autoReconnect: {
      type: Boolean,
      default: true
    },
    // 重连间隔（毫秒）
    reconnectInterval: {
      type: Number,
      default: 3000
    },
    // 最大重连次数
    maxReconnectAttempts: {
      type: Number,
      default: 1
    },
  },
  data () {
    return {
      progressValue: this.initialValue,
      connectionState: {
        isConnected: false,
        reconnectAttempts: 0
      },
      websocketUrl: '',
      wsSend: null,
      heartbeatTimer: null,
    }
  },
  computed: {
    // 是否显示连接状态
    showConnectionStatus () {
      return this.progressValue < 100 && isDebugUser()
    },

    connectionStatusText () {
      if (this.connectionState.isConnected) {
        return '已连接'
      } else if (this.connectionState.reconnectAttempts > 0) {
        return `重连中 (${this.connectionState.reconnectAttempts})`
      } else {
        return '未连接'
      }
    },

    // 连接状态徽章状态
    connectionBadgeStatus () {
      if (this.connectionState.isConnected) {
        return 'success'
      } else if (this.connectionState.reconnectAttempts > 0) {
        return 'processing'
      } else {
        return 'default'
      }
    }
  },
  mounted () {
    this.initWebSocket()
  },
  beforeDestroy () {
    this.cleanup()
  },
  watch: {
    // 初始值变更时重置当前进度显示
    initialValue (val) {
      const num = parseFloat(val)
      this.progressValue = isNaN(num) ? 0 : Math.max(0, Math.min(100, num))

      // 如果新值 >= 100，断开现有连接
      if (this.progressValue >= 100) {
        this.cleanup()
        this.connectionState.isConnected = false
        this.connectionState.reconnectAttempts = 0
        this.$emit('websocket-skipped', { reason: 'initial-value-complete' })
      }
    },
    // 标识变更时，断开旧连接并按新标识重连
    websocketId (newId, oldId) {
      if (newId === oldId) return
      this.cleanup()
      // 重置进度为新的初始值，确保界面先渲染初始值
      const num = parseFloat(this.initialValue)
      this.progressValue = isNaN(num) ? 0 : Math.max(0, Math.min(100, num))
      // 重新建立连接
      this.$nextTick(() => {
        this.initWebSocket()
      })
    }
  },
  methods: {
    /**
     * 初始化 WebSocket
     */
    initWebSocket () {
      if (!this.websocketId) {
        return
      }

      // 如果初始值 >= 100，不建立连接
      if (this.progressValue >= 100) {
        this.connectionState.isConnected = false
        this.connectionState.reconnectAttempts = 0
        this.$emit('websocket-skipped', { reason: 'initial-value-complete' })
        return
      }

      this.websocketUrl = `ws:${window.location.host}/socket/af-system/sendMessage?userId=${this.websocketId}`

      const wsOptions = {
        autoReconnect: this.autoReconnect,
        reconnectInterval: this.reconnectInterval,
        maxReconnectAttempts: this.maxReconnectAttempts
      }

      // 使用 WebSocket 工具
      const wsManager = useWebSocket(wsOptions)


      // 保存方法引用
      this.wsConnect = wsManager.connect
      this.wsDisconnect = wsManager.disconnect
      this.wsOn = wsManager.on
      this.wsSend = wsManager.send
      // 绑定事件监听器
      this.setupEventListeners()

      // 开始连接
      this.wsConnect(this.websocketUrl, wsOptions)
    },
    /**
     * 手动重置为初始值（供父组件可选调用）
     */
    resetToInitial () {
      const num = parseFloat(this.initialValue)
      this.progressValue = isNaN(num) ? 0 : Math.max(0, Math.min(100, num))
    },

    /**
     * 设置事件监听器
     */
    setupEventListeners () {
      // 连接成功
      this.wsOn('connected', (data) => {
        this.connectionState.isConnected = true
        this.connectionState.reconnectAttempts = 0
        this.$emit('websocket-connected', data)
        this.heartbeatTimer = setInterval(() => {
          console.log('>>>> 30秒 心跳')
          this.wsSend('ping')
        }, 30 * 1000)
      })

      // 连接中
      this.wsOn('connecting', (data) => {
        this.$emit('websocket-connecting', data)
      })

      // 消息接收
      this.wsOn('message', (data) => {
        this.handleWebSocketMessage(data)
        this.$emit('websocket-message', data)
      })

      // 连接关闭
      this.wsOn('closed', (data) => {
        this.connectionState.isConnected = false
        this.$emit('websocket-closed', data)
      })

      // 连接错误
      this.wsOn('error', (data) => {
        this.connectionState.isConnected = false
        this.$emit('websocket-error', data)
      })

      // 重连中
      this.wsOn('reconnecting', (data) => {
        this.connectionState.reconnectAttempts = data.attempts
        this.$emit('websocket-reconnecting', data)
      })

      // 重连失败
      this.wsOn('reconnect-failed', (data) => {
        this.connectionState.reconnectAttempts = data.attempts
        this.$emit('websocket-reconnect-failed', data)
      })

      // 断开连接
      this.wsOn('disconnected', (data) => {
        this.connectionState.isConnected = false
        this.connectionState.reconnectAttempts = 0
        this.$emit('websocket-disconnected', data)
      })
    },

    /**
     * 处理 WebSocket 消息
     * @param {Object} data 消息数据
     */
    handleWebSocketMessage (data) {
      const messageData = data.data

      // 更新进度值
      this.updateProgress(parseFloat(messageData))
    },

    /**
     * 更新进度值
     * @param {number} value 进度值
     */
    updateProgress (value) {
      const numValue = parseFloat(value)
      if (!isNaN(numValue)) {
        this.progressValue = Math.max(0, Math.min(100, numValue))
        this.$emit('progress-updated', {
          value: this.progressValue,
          originalValue: value
        })

        // 当进度 >= 100 时，关闭连接
        if (this.progressValue >= 100) {
          this.$emit('progress-completed', {
            value: this.progressValue,
            originalValue: value
          })
          this.cleanup()
        }
      }
    },

    /**
     * 清理资源
     */
    cleanup () {
      if (this.wsDisconnect) {
        this.wsDisconnect()
        if (this.heartbeatTimer) {
          clearInterval(this.heartbeatTimer)
        }
      }
    }
  }
}
</script>

<style scoped lang="less">
.websocket-progress {
  display: flex;
  align-items: center;
  gap: 8px;

  .connection-status {
    flex-shrink: 0;
  }
}
</style>
