import { reactive } from 'vue'
import router from '@/router'
import { useSidebarStore } from '@/store/sidebar'
import { fetchDeviceInfo } from '@/api/deviceAuthorize'
import '@/utils/mqtt/dist/mqtt.min'
import { useUserInfo } from '@/store/user'
interface IModal {
  // 是否显示,隐藏对话框
  open: boolean
  title: string
  showModal: () => void
  hiddenModal: () => void
}
/**
 *
 * @param field 查询字段
 * @returns
 */
export const useQuery = (field: string = '') => {
  if (!field) return
  let url = location.hash
  let urlStr = url?.split('?')?.[1]
  if (!urlStr) return
  // 创建空对象存储参数
  let obj: any = {}
  // 再通过 & 将每一个参数单独分割出来
  let paramsArr = urlStr.split('&')
  for (let i = 0, len = paramsArr.length; i < len; i++) {
    // 再通过 = 将每一个参数分割为 key:value 的形式
    let arr = paramsArr[i].split('=')
    obj[arr[0]] = arr[1]
  }
  return obj?.[field]
}
/**
 *
 * @param title 对话框名称
 * @returns
 */
export const useModal = (title: string) => {
  const modal: IModal = {
    open: false,
    title: title || '',
    showModal() {
      this.open = true
    },
    hiddenModal() {
      this.open = false
    }
  }

  return reactive(modal)
}

export const useRequest = (getData: () => void, immediately = false) => {
  const table: any = {
    loading: false,
    tableData: {},
    items: [],
    data: [],
    async getData() {
      try {
        this.loading = true
        const data: any = (await getData()) as unknown
        this.data = data
        this.items = data?.items as []
      } finally {
        this.loading = false
      }
    }
  }
  if (immediately) {
    table.getData()
  }
  return reactive(table)
}
/** 设备id */
type ID = string
/**
 * 1 起升机构 2 吊车机构
 */
type IType = 1 | 2
export const useToDetail = async (id: ID, _typeNo?: IType) => {
  const data: any = await fetchDeviceInfo(id)
  const type = data.type
  const sidebar = useSidebarStore()
  sidebar.setEquipmentId(id)
  const screenWidth = window.screen.width
  const screenHeight = window.screen.height
  // sidebar.setIsEquipment(false)
  if (type == 2) {
    router.push(`/equipment-center/european-gourd?id=${id}`)
  } else {

    router.push(`/equipment-center/real-time-data?id=${id}`)
  }
}

declare const window: any

export var _mqttMessageCallback: any


export const mqttMessageCallback = (callback: any) => {
  _mqttMessageCallback = callback
}

/**
 * 实时数据
 */
export const useMqtt = () => {
  const userInfo = JSON.parse(localStorage.getItem('user') as string)
  console.log(userInfo)
  const { userId, securityCode } = userInfo
  const { mqtt } = window as any
  const mqttOptions = {
    clean: true,
    connectTimeout: 10000,
    port: 443,
    clientId: `2${Date.now()}`, //提取到配置文件
    username: `${userId}`, //提取到配置文件
    password: securityCode //提取到配置文件
  }

  if (window.client == null) {
    // console.log('初始化mqtt')
    window.client = mqtt.connect('wss://mqtt.hldcloud.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')
    // console.log(e.message)
    if (e.code == 4) {
      //用户名密码错误
      window.client.end()
      window.client = null
      alert("该账号在多个设备上登录，为避免部分功能无法使用，请退出账号重新登录")
    }
  })

  window.client?.on('message', (topic: string, payload: any) => {
    if (_mqttMessageCallback != null) {
      _mqttMessageCallback(topic, payload)
    }
  })

  window.onSubscribe = (topic: string) => {
    window.client?.subscribe(topic, function () {
      // console.log('订阅成功' + topic)
    })
  }

  window.onUnsubscribe = (topic: string) => {
    window.client?.unsubscribe(topic, function () {
      // console.log('取消订阅成功' + topic)
      _mqttMessageCallback = null
    })
  }
}
