<script setup>
import { storeToRefs } from 'pinia';
import useVoiceStore from "@/store/modules/voice";
import { ElMessageBox } from 'element-plus';
import useUserStore from '@/store/modules/user';
import ResetPwdDialog from '@/components/ResetPwdDialog'
import { workbenchApi } from '@/api/voice/workbench';
import TelCallBoard from './TelCallBoard.vue'
import NoticePopover from './NoticePopover.vue'

const voiceStore = useVoiceStore();
const { proxy } = getCurrentInstance();

const { callAnswered, systemState } = storeToRefs(voiceStore);

const userStore = useUserStore();
const dialogVisible = ref(false);

const SYSTEM_STAT_ENUM = [
  {label: '置闲', state: true, icon: 'online-icon'},
  {label: '置忙', state: false, icon: 'offline-icon'}
];

// 修改在线状态
const handlePopoverItem = async ({ state, label }) => {
  /**
   * HSCTIERRORCODE ：
   * 100001: SDK 状态不可用，CTIStatus 的状态为 Terminated
   * 100002: 获取坐席媒体权限失败
   * 
   * AGENTSTATUS : 
   * 1 置忙 2 置闲
   * */ 

  /**
   * 疑问：中途切换 获取坐席状态
   * */ 
  await voiceStore.getAgentStatus();
  // console.log( "坐席状态", voiceStore.AGENTSTATUS );
  // console.log( "系统状态", voiceStore.HSCTIERRORCODE );
  if ( voiceStore.AGENTSTATUS == 0 && ![100001, 100002].includes(Number(voiceStore.HSCTIERRORCODE))) {

 
    workbenchApi.getSeatsByUser({ userId: userStore.id }).then(async({ data }) => {
      if (!data) return;
      await useVoice.HS_CTI_INSTANCE(data.outId); 
      setTimeout(async() => {
        await voiceStore.getAgentStatus();
          // console.log( "坐席状态 下", voiceStore.AGENTSTATUS );
          // console.log( "系统状态 下", voiceStore.HSCTIERRORCODE );
          // if ( !([100001, 100002].includes( Number(voiceStore.HSCTIERRORCODE)) ) ) {
        if ( voiceStore.AGENTSTATUS != 0 ) {
          state ? await voiceStore.setIdle() : await voiceStore.setBusy();
          proxy.$modal[state ? 'msgSuccess' : 'msgWarning']('当前坐席状态: ' + label);
        } else {
          voiceStore.systemState = false;
        }
      }, 1000);
    })
  } else {
    /**
     * 坐席状态是 2 系统状态是100002
     * */
    if (([100001, 100002].includes(Number(voiceStore.HSCTIERRORCODE)))) {
      return ElMessageBox.alert(
        `
          <p>您的系统出现异常，可能导致无法正常接听电话(${voiceStore.HSCTIERRORCODE})</p>
          <p>请检查麦克风权限是否开启。</p>
        `,
        '提醒',
        {
          dangerouslyUseHTMLString: true,
        }
      )
    }
    state ? await voiceStore.setIdle() : await voiceStore.setBusy();
    proxy.$modal[state ? 'msgSuccess' : 'msgWarning']('当前坐席状态: ' + label);
  }
}

// 
const handleCommand = (command) => {
  switch (command) {
    case "logout":
      logout();
      break;
    case 'user':
      userCenter();
      break;
    default:
      break;
  }
}

const userCenter = () => {
  dialogVisible.value = true;
}

const logout = () => {
  ElMessageBox.confirm('确定退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
   
  /**
     * HSCTIERRORCODE ：
     * 100001: SDK 状态不可用，CTIStatus 的状态为 Terminated
     * 100002: 获取坐席媒体权限失败
     * 
     * AGENTSTATUS : 
     * 0 未登录 1 置忙 2 置闲
     * */ 
    //  voiceStore.getAgentStatus();
      // console.log( "退出 坐席状态", voiceStore.AGENTSTATUS );
      // console.log( "退出 系统状态", voiceStore.HSCTIERRORCODE );
      // && voiceStore.AGENTSTATUS != 0 && !([100001, 100002].includes(Number(voiceStore.HSCTIERRORCODE)))
    if ( voiceStore.isAuthPane ) {
      sessionStorage.removeItem('VOICE_STATUS')
      await voiceStore.unInit();
    }
    userStore.logOut().then(() => {
      location.href = '/index';
    })
  }).catch(() => { });
}

onMounted( () => {
 
})

</script>

<template>
  <header class="header-container">
    <div class="navbar-left flex items-center space-x-[8px]">
      <img src="@/assets/images/logo/logo.png" alt="" class="w-[28px] h-[28px]">
      <img src="@/assets/images/logo/logo-text.svg" alt="" class="w-[150px] h-[30px]">
    </div>

    <div class="navbar-right flex items-center space-x-[12px]">
      <el-dropdown trigger="click" popper-class="custom-dropdown" size="small" :disabled="callAnswered" class="forbid" v-if="voiceStore.isAuthPane">
        <div :class="['system-state-wrapper', {forbid: callAnswered}]">
          <div :class="['system-state-btn', {forbid: callAnswered}]">
            <p class="flex items-center space-x-[4px]">
              <span :class="['icon', systemState ? 'online-icon' : 'offline-icon']"></span>
              <span>{{ systemState ? '置闲' : '置忙' }}</span>
            </p>
            <el-icon size="10"><ArrowDown /></el-icon>
          </div>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-for="item in SYSTEM_STAT_ENUM" :key="item.label" @click="handlePopoverItem(item)">
              <div class="system-state-btn">
                <p class="flex items-center space-x-[4px]">
                  <span :class="['icon', item.icon]"></span>
                  <span>{{ item.label }}</span>
                </p>
              </div> 
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      
      <TelCallBoard v-if="voiceStore.isAuthPane"/>

      <NoticePopover></NoticePopover>

      <div class="avatar-wrapper flex items-center space-x-[4px]">
        <div class="avatar-img">
          <img :src="userStore.avatar" alt="" class="img">
        </div>
        <el-dropdown @command="handleCommand" class="right-menu-item hover-effect" trigger="click" size="small" :disabled="callAnswered">
          <div class="h-[36px] flex items-center space-x-[4px]">
            <div class="user-name">{{ userStore.nickName }}</div>
            <el-icon><caret-bottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="user">
                <span class="text-[#1D2129] text-[14px] py-[4px]">个人中心</span>
              </el-dropdown-item>
              <el-dropdown-item command="logout">
                <span class="text-[#1D2129] text-[14px] py-[4px]">退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </header>
  <ResetPwdDialog v-model="dialogVisible"></ResetPwdDialog>
</template>
<style lang="scss">
.custom-dropdown {
  width: 86px;
  .el-dropdown-menu__item {
    padding: 8px !important;
  }
}
.forbid:hover {
  cursor: not-allowed !important;
}
</style>
<style lang="scss" scoped>
.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 92px;
  padding: 34px 20px 22px 20px;
  
  .navbar-left, .navbar-right {
    height: 100%;
  }

  .avatar-wrapper {
    font-size: 14px;
    color: #1D2129;
    font-weight: bold;
    .avatar-img {
      flex-shrink: 0;
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background: #fff;
      overflow: hidden;
      .img {
        width: 100%;
        height: 100%;
        border-radius: 100%;
      }
    }
    .user-name {
      max-width: 100px;
      overflow:hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow:ellipsis;
    }
  }
}

.system-state-wrapper {
    width: 86px;
    height: 36px;
    padding: 9px 8px;
    border-radius: 8px;
    overflow: hidden;
    background: #fff;
  }

.system-state-btn {
  display: flex;
  align-items: center;
  justify-content: space-between;
  line-height: 18px;
  text-align: center;
  font-size: 14px;
  color: #1D2129;
  cursor: pointer;

  .icon {
    display: block;
    width: 18px;
    height: 18px;
  }

  .online-icon {
    background: url('@/assets/images/header/icon-phone-online.svg') center center no-repeat;
  }
  .offline-icon {
    background: url('@/assets/images/header/icon-phone-offline.svg') center center no-repeat;
  }
}


</style>