import { UserData, WorkGroupData } from "../types/user";
import { useInjector, useRequest, useState } from "vue-vulcan";
import { computed, watch} from "vue";
import { useAuthData } from "../auth/useAuthData";
import { useNetSocketStore } from "any-hooks/communication/useNetSocketStore";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";

export function useContacts() {
  const { authData } = useInjector(useAuthData);
  const [ userList, getUserList ] = useRequest<UserData[]>('/getUserList', { auto: false });
  const { currentMsg, status } = useInjector(useNetSocketStore);   
  const [groups, requestGroups] = useRequest<WorkGroupData[]>('/getWorkGroupList');
  const [keyword, setKeyWord] = useState('');

  const contacts = computed( () => {
    return userList.value?.filter( item => item.id !== authData.value?.id )
                          .filter( item => item.nickname.includes(keyword.value))
  });

  const filterGroups = computed( () => {
    return groups.value?.filter(item => item.title.includes(keyword.value))
  })

  const roleContacts = computed( () => {
    const contactHome = {} as {[props: string]: UserData[]}
    contacts.value?.forEach( item => {
      if(['3','4'].includes(item.permission) ) {
        if(!contactHome[item.group_name]) contactHome[item.group_name] = [];
        contactHome[item.group_name].push(item);
      };      
    })
    return contactHome
  })

  const freeContacts = computed( () => {
    const list = contacts.value.filter( item => item.is_calling === '0' && item.is_signin === '1');
    const frees = {} as {[props: string]: UserData[]}
    list?.forEach( item => {
      if(['3','4'].includes(item.permission) ) {
        if(!frees[item.group_name]) frees[item.group_name] = [];
        frees[item.group_name].push(item);
      };      
    })
    return frees
  })

  const freeList = computed(() => userList.value.filter( item => item.is_calling === '0' && item.is_signin === '1'))

  const getContactById = (pid: string, type?: 'uid'|'pid') => {        
    const index = userList.value.findIndex( user => user[type==='uid' ? 'id' : 'peer_id'] === pid );
    console.log(`根据${type  === 'uid' ?'id': 'peer_id'}${pid}查找`, index)
    return userList.value[index];
  }

  const getContactsByGroup = (groupId: string) => {
    return userList.value.filter( item => item.diy_group === groupId );
  } 

  const getContactsOfFree = () => {
    return userList.value.filter( item => item.is_calling === '0' && item.is_signin === '1');
  }

  // 监听socket的home类型消息 实时更新contacts联系人数据
  const req$ = new Subject();
  req$
    .pipe(debounceTime(500))
    .subscribe( _ => getUserList())
  watch(currentMsg, msg => {
    if(msg.msgMainFlag !== 'Home') return;
    if(msg.msgSubFlag === 'UpdateUserList') req$.next();
  })

  watch(status, val => {
    if(val === 'opening') req$.next();
  })

  return {
    contacts,
    freeContacts,
    roleContacts,    
    keyword,
    groups,
    filterGroups,
    freeList,
    requestGroups,
    setKeyWord,
    getUserList,
    getContactById,
    getContactsByGroup,
    getContactsOfFree
  }
}