// 萤石云设备检查工具
import tokenManager from './ezvizTokenManager.js'

class EzvizDeviceChecker {
  constructor() {
    this.baseUrl = 'https://open.ys7.com/api/lapp'
  }

  // 检查设备是否存在
  async checkDevice(deviceSerial) {
    try {
      console.log('🔍 检查设备:', deviceSerial)
      
      const accessToken = await tokenManager.getValidAccessToken()
      
      const response = await uni.request({
        url: `${this.baseUrl}/device/info`,
        method: 'POST',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: {
          accessToken: accessToken,
          deviceSerial: deviceSerial
        }
      })

      console.log('📡 设备信息响应:', response)

      if (response.data && response.data.code === '200') {
        const deviceInfo = response.data.data
        console.log('✅ 设备信息:', deviceInfo)
        
        return {
          success: true,
          device: deviceInfo,
          isOnline: deviceInfo.status === 1,
          deviceName: deviceInfo.deviceName,
          deviceType: deviceInfo.deviceType
        }
      } else {
        console.log('❌ 设备查询失败:', response.data?.msg)
        return {
          success: false,
          error: response.data?.msg || '设备查询失败'
        }
      }
      
    } catch (error) {
      console.error('❌ 设备检查异常:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 获取设备列表
  async getDeviceList() {
    try {
      console.log('📋 获取设备列表')
      
      const accessToken = await tokenManager.getValidAccessToken()
      
      const response = await uni.request({
        url: `${this.baseUrl}/device/list`,
        method: 'POST',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: {
          accessToken: accessToken,
          pageStart: 0,
          pageSize: 50
        }
      })

      console.log('📡 设备列表响应:', response)

      if (response.data && response.data.code === '200') {
        const devices = response.data.data
        console.log('✅ 设备列表:', devices)
        
        return {
          success: true,
          devices: devices,
          total: devices.length
        }
      } else {
        console.log('❌ 设备列表获取失败:', response.data?.msg)
        return {
          success: false,
          error: response.data?.msg || '设备列表获取失败'
        }
      }
      
    } catch (error) {
      console.error('❌ 设备列表获取异常:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 检查直播地址是否有效
  async checkLiveUrl(deviceSerial, channelNo = 1) {
    try {
      console.log('🎥 检查直播地址:', deviceSerial, channelNo)
      
      const accessToken = await tokenManager.getValidAccessToken()
      
      const response = await uni.request({
        url: `${this.baseUrl}/device/live`,
        method: 'POST',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: {
          accessToken: accessToken,
          deviceSerial: deviceSerial,
          channelNo: channelNo,
          protocol: 1 // 1-rtmp，2-hls，3-flv
        }
      })

      console.log('📡 直播地址响应:', response)

      if (response.data && response.data.code === '200') {
        const liveInfo = response.data.data
        console.log('✅ 直播地址信息:', liveInfo)
        
        return {
          success: true,
          liveUrl: liveInfo.url,
          hd: liveInfo.hd,
          sd: liveInfo.sd
        }
      } else {
        console.log('❌ 直播地址获取失败:', response.data?.msg)
        return {
          success: false,
          error: response.data?.msg || '直播地址获取失败'
        }
      }
      
    } catch (error) {
      console.error('❌ 直播地址检查异常:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 从URL中提取设备序列号
  extractDeviceSerial(playUrl) {
    try {
      // ezopen://open.ys7.com/K74237657/1.hd.live
      const match = playUrl.match(/ezopen:\/\/open\.ys7\.com\/([^\/]+)\//)
      return match ? match[1] : null
    } catch (error) {
      console.error('提取设备序列号失败:', error)
      return null
    }
  }

  // 综合检查
  async comprehensiveCheck(playUrl) {
    console.log('🔍 开始综合检查播放地址:', playUrl)
    
    const deviceSerial = this.extractDeviceSerial(playUrl)
    if (!deviceSerial) {
      return {
        success: false,
        error: '无法从播放地址中提取设备序列号'
      }
    }

    console.log('📱 提取到设备序列号:', deviceSerial)

    // 检查设备信息
    const deviceCheck = await this.checkDevice(deviceSerial)
    if (!deviceCheck.success) {
      return {
        success: false,
        error: `设备检查失败: ${deviceCheck.error}`,
        deviceSerial: deviceSerial
      }
    }

    // 检查直播地址
    const liveCheck = await this.checkLiveUrl(deviceSerial)
    
    return {
      success: true,
      deviceSerial: deviceSerial,
      device: deviceCheck.device,
      isOnline: deviceCheck.isOnline,
      liveUrl: liveCheck.success ? liveCheck.liveUrl : null,
      liveError: liveCheck.success ? null : liveCheck.error
    }
  }
}

// 导出单例
const deviceChecker = new EzvizDeviceChecker()
export default deviceChecker

