<script setup lang="ts">
import { ref, watch } from 'vue'
import { useWebSocket } from '@vueuse/core'
import { ElNotification } from 'element-plus'
import { useUserStore } from '../store/modules/user'
import { useDebounceFn } from '@vueuse/core'
import { useRouter } from 'vue-router'
const push = useRouter().push

const showDrawer = ref(false)

const handleClick = () => {
  showDrawer.value = true
}

const noticeList = ref<Recordable[]>([])
const isNotice = ref(false)

const wsUrl = import.meta.env.VITE_WS_API
// 关闭ws连接
const closeMethod = ref()
const sendMethod = ref()
const userStore = useUserStore()
watch(
  () => userStore.getToken,
  (val) => {
    if (val && wsUrl) {
      //全局消息提醒
      const { send, close } = useWebSocket(`${wsUrl}/websocket?accessToken=${val}`, {
        onConnected: function (ws) {
          console.log('websocket 连接成功！', ws)
        },
        onDisconnected: function (_ws, _event) {
          console.log('onDisconnected')
        },
        onError: function (_ws, _event) {
          console.log('onError')
          close()
        },
        onMessage: function (_ws, event) {
          // 记录关闭方法  用于关闭ws连接
          closeMethod.value = close
          sendMethod.value = send
          if (event.data) {
            const data = JSON.parse(event.data)

            // 根据appCode 来过滤ws的提示内容
            const flag = sessionStorage.getItem('flag')
            // if (flag && flag !== data.extra.appCode) return
            if (flag && !flag.includes(data.extra.appCode)) return

            // 推送来的消息存入 已推送过的不再存
            if (
              !noticeList.value.length ||
              !noticeList.value.find((item) => item.extra.msgId === data.extra.msgId)
            ) {
              noticeList.value.push(data)
            }
            // 多次推送的消息 只提醒一次
            if (!isNotice.value) {
              const elNotice = ElNotification({
                title: '消息提醒',
                type: 'warning',
                duration: 20000,
                customClass: 'ws-msg',
                dangerouslyUseHTMLString: true,
                onClick: () => {
                  elNotice.close()
                  showDrawer.value = true
                },
                // 门户页 不跳转   没path 不跳转
                message: `<div class="msg-box">
                              您有新的消息提醒
                              <div class="msg-box-read">点击查看</div>
                            </div>`
              })
              isNotice.value = true
            }
            noticeDebounce()
          }
        },
        heartbeat: {
          message: 'ping',
          interval: 600000,
          pongTimeout: 600000
        },
        autoReconnect: true,
        autoClose: true
      })
    } else {
      // 取消链接
      closeMethod.value && closeMethod.value()
    }
  },
  {
    immediate: true
  }
)

const noticeDebounce = useDebounceFn(() => {
  isNotice.value = false
}, 10000)

// 点击标为已读
const handleCLickRead = (item, index: number, router: boolean = false) => {
  // 为true 走跳转
  if (router) {
    push(item.extra.path)
    showDrawer.value = false
  }

  const sendData = {
    bizCode: 'internalMessageRead',
    content: item?.extra?.msgId
  }
  sendMethod.value && sendMethod.value(JSON.stringify(sendData))
  noticeList.value.splice(index, 1)
}
const handleClickReadAll = () => {
  ElMessageBox.confirm('是否确认将所有标记为已读?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      for (const item of noticeList.value) {
        const sendData = {
          bizCode: 'internalMessageRead',
          content: item?.extra?.msgId
        }
        sendMethod.value && sendMethod.value(JSON.stringify(sendData))
      }
      noticeList.value = []
    })
    .catch(() => {})
}
</script>

<template>
  <el-badge :is-dot="!!noticeList.length" class="mr-16px cursor-pointer" @click="handleClick">
    <el-icon size="20px" class="align-middle"><Bell /></el-icon>
    <el-drawer v-model="showDrawer" title="消息提醒" custom-class="notice-drawer">
      <el-empty description="暂无提醒" v-if="!noticeList.length" />
      <div class="ws-msg-list" v-else>
        <div class="overflow-hidden">
          <BaseButton size="small" class="mb-10px float-end" @click="handleClickReadAll"
            >所有标为已读</BaseButton
          >
        </div>
        <div
          v-for="(item, index) in noticeList"
          :key="index"
          class="ws-msg-item flex justify-between align-center gap-10px"
        >
          <div class="ws-msg-item-title">
            <el-icon color="#999" size="16px" class="align-middle mr-6px"><Bell /></el-icon>
            {{ item.content }}
            <div
              ><BaseButton
                link
                type="primary"
                @click="handleCLickRead(item, index, true)"
                v-if="item.extra.path"
                >点击跳转</BaseButton
              ></div
            >
          </div>
          <BaseButton link type="primary" @click="handleCLickRead(item, index)"
            >标为已读</BaseButton
          >
        </div>
      </div>
    </el-drawer>
  </el-badge>
</template>

<style lang="less" scoped>
:deep(.el-drawer) {
  .el-drawer__header {
    margin-bottom: 10px;
  }
}
.ws-msg-list {
  .ws-msg-item {
    font-size: 14px;
    & + .ws-msg-item {
      margin-top: 10px;
      border-top: 1px solid var(--el-border-color-light);
      padding-top: 10px;
    }
  }
}
</style>
<style lang="less">
.ws-msg {
  .msg-box-read {
    margin-top: 2px;
    color: var(--el-color-primary);
    cursor: pointer;
  }
}
</style>
