import { useAuthData } from "any-hooks/auth/useAuthData";
import { computed, watch } from "vue";
import { useInjector, useRequest, useState } from "vue-vulcan";
import { useNetSocketStore } from "./useNetSocketStore";

interface ChannelData {
  channel_id: string;
  agora_token: string;  
}

/** 频道中心功能，可以创建频道，并保存当前频道的信息，供呼叫中心、会议中心使用（目前同一时间仅允许存在一个频道） */
export function useChannelStore() {
  const [currentChannel, setChannel]   = useState<ChannelData>(null);
  const [channelMembers, setMembers]   = useState<string[]>([]);
  const [channelInfo, request]         = useRequest<ChannelData>('/getAgoraToken', {auto: false});
  const { authData }                   = useInjector(useAuthData);
  const { currentMsg }                 = useInjector(useNetSocketStore);

  const isEmpty = computed( () => channelMembers.value.length < 2); //频道剩余不到1人时，表示为空

  /* 创建新的频道(如果已存在一个频道则不调用创建接口，直接返回一个promise) */
  const createChannel = () => {    
    updateMembers([authData.value.id], 'join');
    console.log('创建频道前判断是否已存在频道', currentChannel.value);
    if(!currentChannel.value) return request();    
    return new Promise<ChannelData>(resolve => resolve(channelInfo.value));
  }  

  const getTokenByChannel = (cid: string) => {
    console.log('根据对方呼叫人的频道获取token');
    updateMembers([authData.value.id], 'join');
    return request({channel_id: cid});    
  }   

  const updateMembers = (ids: string[], type: 'join' | 'leave') => {
    const current = channelMembers.value;
    if(type === 'join') {      
     setMembers([...new Set([...current, ...ids])])
    } else  {
      setMembers(current.filter(item => !ids.includes(item)))
    }    
  }  

  const clearChannel = () => {
    setChannel(null);
    setMembers([]);
  }

  watch(channelInfo, val => {    
    setChannel(val);    
    updateMembers([authData.value.id], 'join');
  })

  //监听频道下的成员实时信息
  watch(currentMsg, msg => {
    if(msg.msgMainFlag !== 'ChannelChat') return;
    switch(msg.msgSubFlag) {
      case 'Hangup':
        updateMembers([msg.fromID], 'leave');
      break;
    }
  })


  return {
    currentChannel,
    channelMembers,
    isEmpty,
    getTokenByChannel,
    createChannel,
    updateMembers,
    clearChannel
  }
}