import { onMounted } from "@vue/runtime-core";
import { useAuthData } from "any-hooks/auth/useAuthData";
import { useSocket } from "any-hooks/common/useSocket";
import { AnyRemoteSocketMessage, SocketSettings } from "any-hooks/types/socket";
import { UserData } from "any-hooks/types/user";
import { useInjector, useState } from "vue-vulcan";
import { SOCKET_SETTINGS } from "./token";

enum NetStates {
  off = 0,
  bad,
  normal,
  good,
  best
}

// 在线socket连接中心，会议中心、呼叫中心的基础
export function useNetSocketStore() {
  
  const { authData }                  = useInjector(useAuthData);   
  const [ netState, setNetState ]     = useState<NetStates>(0);
  const { baseUrl }                   = useInjector<SocketSettings>(SOCKET_SETTINGS, 'optional');
  const { connect, reconnect, send, close, onOpen, currentMsg, startHeartConnect, status } = useSocket<AnyRemoteSocketMessage>();    
  const [deviceCode, setDevice]       = useState(null, {key: 'device', storage: 'custome'})

  onMounted(() => {
    if(!deviceCode.value) {
      setDevice(new Date().getTime())
    }
  })  

  const initConnect = (data: UserData) => {    
    connect(
      `${baseUrl}?fromID=${data.id}&fromName=${data.nickname}&signID=${deviceCode.value}&companyID=${data.company_id}`
    )
    startHeartConnect({
      fromID: authData.value.id,
      fromName: authData.value.nickname,
      toID: '0',
      msgMainFlag: 'Heart'
    })
    
    onOpen(() => {
      console.log('ws初始化peerid', authData.value.peer_id)
      sendMsg({
        msgMainFlag: 'SetAtts',
        msgSubFlag: "UpdateUserList",
        toID: '0',
        msgData: {
          peerID: authData.value.peer_id,
          avatar: authData.value.avatar,
          permission: authData.value.permission
        }
      })
    })       
  }

  const sendMsg = (data: AnyRemoteSocketMessage) => {
    send({
      ...data, 
      fromID: authData.value.id, 
      fromName: authData.value.nickname, 
      avatar: authData.value.avatar,
      permission: authData.value.permission,
      msgData: {
        peerID: authData.value.peer_id,
        avatar: authData.value.avatar,
        permission: authData.value.permission
      }
    })
  }

  return {
    sendMsg,
    setNetState,
    initConnect,
    reconnect,
    close,
    currentMsg,
    netState,
    status
  }
}