<script lang="ts" setup>
  import { useInjector } from 'vue-vulcan';
  import { useContacts } from 'any-hooks/contacts/useContacts';
  import { useCallCenter } from 'any-hooks/communication/useCallCenter';
  import { navigateTo, showToast } from '@tarojs/taro';
  import { useAppInitInfo } from 'src/hooks/common/useAppInitInfo';
  import { UserData } from 'any-hooks/types/user';
  import { reactive } from '@vue/reactivity';
  import { useDebounce } from 'any-hooks/common/useDebounce';

  const { callContact, myCallState } = useInjector(useCallCenter);
  const { contacts, roleContacts }   = useInjector(useContacts);
  const { checkCamearSetting }       = useInjector(useAppInitInfo);
  
  const gotoDetail = (id: string) => {
    navigateTo({url: '/pages/contact-detail/index?id='+ id})
  }

  const onTapCall = useDebounce(
    (data: UserData) => {
      if(myCallState.value !== 'idle') {
        showToast({title: '您当前已在通话中，无法发起呼叫', icon: 'none'})
      } else {
        console.log('检查摄像头权限')
        checkCamearSetting().then( r => {
          r ? callContact(data) : showToast({title: '您未授权摄像头权限，请在设置中打开摄像头授权', icon: 'none'});
        })      
      }
    },
    500
  ) 

  // 联系人折叠隐藏功能
  const hideConfig = reactive({});
  const toggleHideByIndex = (index: number) => {
    hideConfig[index] = !hideConfig[index]
  }
</script>

<template>
  <view class="contact-list">    
    <view class="contact-role-group" v-for="(group, key, index) in roleContacts" :key="index">
      <view class="role-name pd-2" :class="{hide: hideConfig[index]}" @tap="toggleHideByIndex(index)">{{key}}</view>
      <view class="white-box" :style="{display: hideConfig[index] ? 'none' : 'block'}">        
        <view class="contact-item" v-for="(item, i) in group" :key="i"  @tap="gotoDetail(item.id)">
          <image class="avatar" :src="item.avatar" />
          <view class="info">
            <view>{{item.nickname}}</view>
            <text style="color:#999">{{item.group_name}}</text>              
          </view>
          <image v-if="item.is_signin === '1'" @tap.stop="onTapCall(item)" class="call" src="../../assets/call3x.png" mode="widthFix"/>
          <image v-else class="call" src="../../assets/call-no3x.png" mode="widthFix"/>
        </view>
      </view>      
    </view>
    <data-empty v-if="!contacts?.length"></data-empty>
  </view>
</template>

<style lang="less">
  .contact-list{
    .contact-role-group{      
      background-color: #fff;
      .role-name{
        // background-color: #f5f5f5;
        position: relative;
        padding-left: 60px;
        &.hide::before{
          transform: rotate(-90deg);
        }
        &::before{
          content: '';
          width: 0;
          height: 0;
          position: absolute;
          border-left: 10px solid transparent;
          border-right: 10px solid transparent;
          border-top: 16px solid #aaa;
          left:25px;
          top:37px;
        }
      }      
    }
  }
</style>