import { hideLoading, navigateTo, showLoading, showModal, showToast } from "@tarojs/taro";
import { onMounted, watch } from "@vue/runtime-core";
import { useAuthData } from "any-hooks/auth/useAuthData";
import { useLogOut } from "any-hooks/auth/useLogOut";
import { useNetSocketStore } from "any-hooks/communication/useNetSocketStore";
import { useInjector, useRequest } from "vue-vulcan";

export function useSocketHandle() {
  const { status, initConnect, reconnect, close, currentMsg } = useInjector(useNetSocketStore); 
  const { authData } = useInjector(useAuthData);   
  const [,requestAuthState] = useRequest<any>('/getUserCallStatus', {auto: false});  
  const { submitLogOut } = useLogOut();

  onMounted(() => {
    console.log('handle', authData)
    if(authData.value) {
      requestAuthState({user_id: authData.value.id}) 
        .then(res => {
          if(res.callState === '1') {
            showToast({title: '当前用户处于通话状态, 无法覆盖登录'});
            return;
          }
          if(res.is_signin === '0') {
            initConnect(authData.value)
          } else {
            showModal({
              title:'当前账号已在线，是否确认登录?',
              success: e => { 
                if(e.confirm){
                  initConnect(authData.value);                
                } else if(e.cancel){
                  submitLogOut({login_id: authData.value.id}).then(_ => navigateTo({url: '/pages/login/index'}));
                }
              }
            })
          }        
        })
    }
  })  
  

  watch(status, val => {
    switch(val) {
      case 'reconnect':
        showLoading({title: '重连中...'});
      break;
      case 'opening':
        hideLoading();
      break;
      case 'closed':
      case 'onerror':
        if(authData.value) {
          reconnect()
        } else{
          // setTimeout( () => {
          //   showToast({title: '链接已关闭，请重启小程序', icon: 'none'});
          // }, 1500)            
        }        
      break;
    }
  })

  watch(currentMsg, msg => {
    console.log(msg.msgSubFlag)
    if(msg.msgSubFlag === 'OtherLoginIn'){
      showToast({
        title: '当前账号在其他设备登录，您已自动下线',
        icon: 'none'
      });      
      submitLogOut({login_id: authData.value.id}).then(_ => {
        close(); 
        navigateTo({url: '/pages/login/index'});          
      });      
    }
  })
  

  watch(status, val => {
    console.log('socket status', val)
  })
}