import '../../public/mqtt/dist/mqtt.min'
declare const window: any
var _mqttMessageCallback: any = null

/**
 * mqtt订阅
 * @param topics 主题['a','b']
 * @param callback 消息回调
 */
export const onSubscribe = (topics: string[], callback: any) => {
  console.log(topics)
  _mqttMessageCallback = callback
  if (window.client == null) {
    useMqtt()
  }
  topics.forEach(topic => {
    window.client?.subscribe(topic, () => { })
  })
  window.client?.on('message', (topic: string, payload: any) => {
    if (_mqttMessageCallback != null) {
      _mqttMessageCallback(topic, payload)
    }
  })
}

/**
 * mqtt取消订阅
 * @param topic 主题
 */
export const onUnsubscribe = (topic: string) => {
  window.client?.unsubscribe(topic, () => {
    _mqttMessageCallback = null
  })
}

/**
 * 实时数据
 */
export const useMqtt = () => {
  const userInfo = JSON.parse(localStorage.getItem('gdyt_user') as string)
  const { userId, securityCode } = userInfo
  const { mqtt } = window as any
  const mqttOptions = {
    clean: true,
    connectTimeout: 10000,
    port: 80,
    clientId: `2${Date.now()}`, //提取到配置文件
    username: `${userId}`, //提取到配置文件
    password: securityCode //提取到配置文件
  }
  console.log(mqttOptions)
  if (window.client == null) {
    //console.log('初始化mqtt')
    window.client = mqtt.connect('ws://cloud-mqtt.gd-yt.cn/mqtt', mqttOptions)
  }
  window.client.on('connect', () => {
    console.log('mqtt连接成功')
  })

  window.client.on('reconnect', () => {
    console.log('mqtt正在重连')
  })

  window.client.on('disconnect', () => {
    console.log('mqtt断开连接disconnect')
  })

  window.client.on('close', () => {
    console.log('mqtt断开连接close')
  })

  window.client.on('error', (e: any) => {
    console.log('mqtt无法连接error' + e.message)
    if (e.code == 4) {
      //用户名密码错误
      window.client.end()
      window.client = null
      alert("该账号在多个设备上登录，为避免部分功能无法使用，请退出账号重新登录")
    }
  })

}

export function isTrue(e: any) {
  if (e === true || e === 'true') {
    return true
  }
  return false
}

/**
 * 清除对象中的字符串前后空格
 * @param target 目标对象
 * @returns 去除前后空格后的对象
 */
export const recordValueTrim = (target: Record<string, any>) => {
  // 不为空且是对象或数组
  if (target && typeof target === 'object') {
    // 如果数组则使用数组解构，如果是对象则使用对象结构
    const query: any = target instanceof Array ? [...target] : { ...target }
    const keys = Object.keys(query)
    keys.forEach((key) => {
      // 是string则进行trim
      if (typeof query[key] === 'string') {
        query[key] = (query[key] as string).trim()
        return
      }
      // 如果是数组，则递归处理
      if (query[key] instanceof Array) {
        query[key] = query[key].map((item: any) => {
          return typeof item === 'string' ? item.trim() : recordValueTrim(item)
        })
        return
      }
      // 如果是对象则处理对象
      if (typeof query[key] === 'object') {
        query[key] = recordValueTrim(query[key])
      }
    })

    return query
  }

  return target
}

//格式化档位
export function formatGears(gear: any) {
  let gears = gear.gears
  if(gears == null){
    gears = []
  }
  if (gear.variableType == 1) {
    if (gears.length == 0) {
      return '零位'
    } else {
      if (gears.length > 1) {
        return gears[0] + gears[gears.length - 1]
      } else {
        return gears[0]
      }
    }
  } else {
    if (gears.length == 0) {
      return '零位'
    } else {
      return gears[gears.length - 1]
    }
  }
}

/** value值,  translate 系数*/
export const formatValue = (value: any, translate: any) => {
  if (value == null) return '--'
  if (value == "闭合" || value == "开启") {
    return value
  }

  let num = parseFloat(value) * translate;
  let surplus = num % 1;
  if (surplus != 0.0) {
    return (Math.floor(num * 100) / 100).toFixed(2)
  } else {
    //无小数
    return parseInt(num.toString());
  }

}

//解析档位
export function parseGear(gear: any, code: any, value: any) {
  if (gear != null) {
    //取出当前档位
    let option = gear.options.find((f: any) => f.variableCode == code)
    if (option != null) {
      //当前档位
      let currentGearName = option.displayName

      if (value === true || value === 'true') {
        //不存在添加（加档）
        let g = gear.gears.find((f: any) => f == currentGearName)
        if (g == null) {
          gear.gears.push(currentGearName)
        }
      } else {
        //存在删除（减档）
        gear.gears = gear.gears.filter((f: any) => f != currentGearName)
      }
      return true
    }
    return false
  }
  return false
}

/**
 *
 * @param light 处理载荷 灯
 * @returns
 */
export function formatWeightLight(light: any) {
  const obj: any = {
    green: '#6AD28C',
    red: '#FE5656',
    yellow: '#F49F51',
    gray: '#9999'
  }
  if (light == null) {
    return obj['gray']
  }

  if (light.value == 'true' || light.value == true) {
    return obj['red']
  } else {
    return obj['green']
  }
}

