<!--
 * @Author: Mm
 * @Date: 2025-02-20 09:55:11
 * @LastEditors: Mm
 * @LastEditTime: 2025-06-13 14:46:28
 * 不写bug的程序员不是一个好程序员!
-->
<script lang="ts" setup>
import { computed, h, onMounted, watch, ref, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';

import { AuthenticationLoginExpiredModal,useVbenModal } from '@vben/common-ui';
import { VBEN_DOC_URL, VBEN_GITHUB_URL } from '@vben/constants';
import { useWatermark } from '@vben/hooks';
import {
  BookOpenText,
  CircleHelp,
  GiteeIcon,
  GitHubOutlined,
  UserOutlined,
} from '@vben/icons';
import {
  BasicLayout,
  LockScreen,
  Notification,
  UserDropdown,
} from '@vben/layouts';
import { preferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';
import { openWindow } from '@vben/utils';

import { message, Modal,Badge  } from 'ant-design-vue';
import { CommentOutlined  } from '@ant-design/icons-vue';
import { TenantToggle } from '#/components/tenant-toggle';
import { $t } from '#/locales';
import { resetRoutes } from '#/router';
import { useAuthStore, useNotifyStore } from '#/store';
import { useTenantStore } from '#/store/tenant';
import LoginForm from '#/views/_core/authentication/login.vue';
import fkDetailModal from '#/views/tasks/fk-detail-modal.vue';
// 反馈详情弹窗
const [FkDetailModal, fkDetailModalApi] = useVbenModal({
  connectedComponent: fkDetailModal,
});
import { isReadMsg } from '#/api/im/index';
import Chat from '#/views/chat/index.vue';
const userStore = useUserStore();
const authStore = useAuthStore();
const accessStore = useAccessStore();
const router = useRouter();
const { destroyWatermark, updateWatermark } = useWatermark();

const tenantStore = useTenantStore();
const menus = computed(() => {
  const defaultMenus = [
    {
      handler: () => {
        router.push('/profile');
      },
      icon: UserOutlined,
      text: $t('ui.widgets.profile'),
    },
  ];
  /**
   * 租户选中状态 不显示个人中心
   */
  if (tenantStore.checked) {
    defaultMenus.splice(1, 1);
  }
  return defaultMenus;
});

const avatar = computed(() => {
  return userStore.userInfo?.avatar ?? preferences.app.defaultAvatar;
});

async function handleLogout() {
  /**
   * 主动登出不需要带跳转地址
   */
  await authStore.logout(false);
  resetRoutes();
}

const notifyStore = useNotifyStore();

onMounted(() => notifyStore.startListeningMessage());

function handleViewAll() {
  message.warning('暂未开放');
}
watch(
  () => preferences.app.watermark,
  async (enable) => {
    if (enable) {
      await updateWatermark({
        content: `${userStore.userInfo?.username}`,
      });
    } else {
      destroyWatermark();
    }
  },
  {
    immediate: true,
  },
);

const isShowChat = ref(false);
// function showChat() {
//   isShowChat.value = true;
// }
// 定时器 检验是否有未读消息
const timer = ref<ReturnType<typeof setInterval> | null>(null);

const isRead = ref(false);
function checkIsReadMsg() {

  const accessToken = localStorage.getItem('im_access_token');
  isReadMsg({accessToken}).then(res=>{
    isRead.value = res
  })
}
function handleAsynChatCount(count:any){
  isRead.value = count > 0;
}
onMounted(() => {
    // timer.value = setInterval(() => {
    //   checkIsReadMsg()
    // }, 10000);
    window.addEventListener('message', (e)=>{
    if (e.data.type == 'feedback') {
      fkDetailModalApi.setData({
        taskNo:e.data.taskNo,
        feedbackId:e.data.feedbackId
      });
      fkDetailModalApi.open();
    }
  });
});

onUnmounted(() => {
  // if (timer.value) {
  //   clearInterval(timer.value);
  // }
});
function gotoTask(item:any){
  if(item.type == 1){
    router.push({
      path:'/tasks/index'
    })
  }else if(item.type == 2){
    router.push({
      path:'/tasks/dwsp'
    })
  }else if(item.type == 3){
    router.push({
      path:'/tasks/dwbl'
    })
  }
}
</script>

<template>
  <BasicLayout @clear-preferences-and-logout="handleLogout">
    <template #header-right-1>
      <TenantToggle />
    </template>
    <template #user-dropdown>
      <UserDropdown
        :avatar
        :menus
        :text="userStore.userInfo?.realName"
        :description="userStore.userInfo?.username"
        tag-text=""
        @logout="handleLogout"
      />
    </template>
    <template #notification>
      <Notification
        :dot="notifyStore.showDot"
        :notifications="notifyStore.notifications"
        @clear="notifyStore.clearAllMessage"
        @make-all="notifyStore.setAllRead"
        @read="notifyStore.setRead"
        @tz="gotoTask"
        @view-all="handleViewAll"
      />
      <div @click="isShowChat = true"  class="chat" title="聊天">
        <Badge :dot="isRead" :offset="[5,-2]">
          <CommentOutlined style="font-size:16px;color:rgb(50, 54, 57)" />
        </Badge>
      </div>
    </template>
    <template #extra>
      <AuthenticationLoginExpiredModal
        v-model:open="accessStore.loginExpired"
        :avatar
      >
        <LoginForm />
      </AuthenticationLoginExpiredModal>
    </template>
    <template #lock-screen>
      <LockScreen :avatar @to-login="handleLogout" />
    </template>
  </BasicLayout>
  <Chat v-show="isShowChat" v-model="isShowChat" @asynChatCount="handleAsynChatCount" />
   <!-- 反馈单详情  -->
   <FkDetailModal  />
</template>
<style lang="less" scoped>
.chat{
  width: 32px;
  height: 32px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 16px;
  transition: all .3s;
  &:hover{
    cursor: pointer;
    background: hsl(240 5% 96%);

  }
}
</style>
<style>
.ant-badge-dot{
  width: 8px!important;
  height: 8px!important;
}
</style>
