<template>
  <message-component>
    <div ref="messageIcon" v-bind="$attrs" class="message-icon" @click="openMsgDialog">
      <span v-show="unReadMessages?.newCount" class="un-read-num">
        {{ (unReadMessages?.newCount || 0) > 99 ? '99+' : unReadMessages?.newCount }}
      </span>
      <!-- <svg-icon v-if="inLayout" name="message" class="bell"></svg-icon> -->
      <!-- <svg-icon v-else name="message2" class="bell"></svg-icon> -->
      <el-tooltip effect="light" content="消息" placement="bottom">
        <div class="msg-box">
          <img v-if="inLayout" class="bell-img" src="../../../assets/images/bel_img.png" />
          <svg-icon v-else name="message" class="bell"></svg-icon>
          <p class="tip">消息</p>
        </div>
      </el-tooltip>
    </div>
    <message-window
      v-model="visibleMessageWindow"
      v-model:type="messageWindowType"
      v-model:replyUserId="replyUserId"
      :paper-path="props.paperPath"
      :secret-number="props.secretNumber"
    ></message-window>
  </message-component>
</template>

<script setup lang="ts" name="Message">
/** 头部消息组件 */
import { defineComponent, withDefaults, ref, useSlots, watch, inject, ShallowRef } from 'vue'
import { ElPopover } from 'element-plus'
import dayjs from 'dayjs'
import useVW from '@/hooks/useVW'
import useVModel from '@/hooks/useVModel'
import useMessageLoop, { lastMsgs, setLastMsgs } from '@/hooks/useMessageLoop'
import useMainStore from '@/store/main'
import MessageWindow from '@/components/shared/message/MessageWindow.vue'
import ConfirmButton from '@/components/common/ConfirmButton.vue'
import SvgIcon from '@/components/common/SvgIcon.vue'
import bus from '@/utils/bus'

const props = withDefaults(
  defineProps<{
    type?: 'view' | 'send'
    replyUserId?: number | null
    messageVisible?: boolean | null
    paperPath?: string | null
    inLayout?: boolean
    secretNumber?: string | number | null
  }>(),
  { type: 'view', replyUserId: null, paperPath: null, messageVisible: false, secretNumber: null }
)
const transContent = (content: any) => {
  return content
    .replaceAll(/<[^>]+>/gim, ' ')
    .replace('&quot;', '"')
    .replace('&amp;', '&')
    .replace('&lt;', '<')
    .replace('&gt;', '>')
    .replace('&nbsp;', ' ')
}
const MessageComponent = defineComponent({
  setup() {
    const mainStore = useMainStore()
    return {
      mainStore,
    }
  },
  render() {
    const slots = useSlots()
    return this.mainStore?.myUserInfo?.role === 'ADMIN' ? null : slots.default?.()
  },
})

const setMessageVisible = inject<(visible: boolean) => void>('setMessageVisible')
const setReplyUserId = inject<(replyUserId: number | null) => void>('setReplyUserId')

const messageIcon = ref<HTMLDivElement>()

const unReadMessages = useMessageLoop()
watch(
  () => (unReadMessages as ShallowRef).value,
  (val) => {
    if (!visibleMessageWindow.value) {
      let newMsgs = val.messages
      if (!newMsgs.length) {
        return
      }

      let newMsgTime = Math.max.apply(
        Math,
        newMsgs.map((item: any) => {
          return new Date(item.sendTime).getTime()
        })
      )
      // let hasRecentSixSecondsMsg = new Date(newMsgs[0].sendTime).getTime() > Date.now() - 6000
      let hasRecentSixSecondsMsg = newMsgTime > Date.now() - 10000
      if (!lastMsgs.messages.length && hasRecentSixSecondsMsg) {
        messageWindowType.value = 'view'
        visibleMessageWindow.value = true
        return
      }
      let recentMsgTime = Math.max.apply(
        Math,
        lastMsgs.messages.map((item) => {
          return new Date(item.sendTime).getTime()
        })
      )
      // let newMsgTime = Math.max.apply(
      //   Math,
      //   newMsgs.map((item: any) => {
      //     return new Date(item.sendTime).getTime()
      //   })
      // )
      if (newMsgTime > recentMsgTime && hasRecentSixSecondsMsg) {
        messageWindowType.value = 'view'
        visibleMessageWindow.value = true
      }
    }
  }
)

const messageWindowType = useVModel(props, 'type')

const replyUserId = useVModel(props, 'replyUserId')

/** 发送/查看消息Modal */
const visibleMessageWindow = ref<boolean>(false)
bus.on('logout', () => {
  visibleMessageWindow.value = false
})
const openMsgDialog = () => {
  messageWindowType.value = 'view'
  visibleMessageWindow.value = true
}
watch(
  () => props.messageVisible,
  () => {
    if (props.messageVisible) {
      visibleMessageWindow.value = true
      messageWindowType.value = 'send'
    }
  }
)

watch(visibleMessageWindow, () => {
  if (!visibleMessageWindow.value) {
    setMessageVisible?.(false)
  }
})

watch(replyUserId, () => {
  setReplyUserId?.(replyUserId.value)
})

/** 收消息 */
const onReceiveMessage = (message: any) => {
  messageWindowType.value = 'view'
  visibleMessageWindow.value = true
}

/** 发消息 */
const onSendMessage = () => {
  messageWindowType.value = 'send'
  visibleMessageWindow.value = true
}
bus.on('fast-send-msg', () => {
  onSendMessage()
})
</script>

<style scoped lang="scss">
.message-icon {
  display: grid;
  place-items: center;
  font-size: $LargeFont;
  position: relative;
  .msg-box {
    text-align: center;
    cursor: pointer;
    &:hover {
      opacity: 0.7;
    }
    .tip {
      font-size: 12px;
    }
  }
  .bell-img {
    height: 16px;
  }
  .bell {
    &:hover {
      color: #fff;
    }
  }
  .un-read-num {
    position: absolute;
    width: 24px;
    height: 18px;
    line-height: 18px;
    right: -11px;
    top: -10px;
    text-align: center;
    color: $color--white;
    font-size: 10px;
    border-radius: 4px;
    background-color: $DangerColor;
    z-index: 1;
  }
}
.message-popover-content {
  color: $NormalColor;
  .title {
    .unread-count {
      font-size: $MediumFont;
      color: $DangerColor;
      margin-right: 4px;
    }
  }
  .message-list {
    border-bottom: $OnePixelLine;
    // margin: 10px 0 40px;
    height: 80px;
    margin: 10px 0;
    .message-row {
      padding: 0 4px;
      font-size: $BaseFont;
      font-weight: 400;
      border-top: $OnePixelLine;
      height: 40px;
      line-height: 40px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .send-user {
        width: 60px;
      }
      .send-content {
        width: calc(100% - 70px);
      }
      &:hover {
        background-color: #f5f5f5;
      }
      .message-send-user {
        width: 52px;
        margin-right: 0.5em;
        font-size: $SmallFont;
        overflow: hidden;
        .user-name {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-weight: 500;
          text-align: justify;
          text-align-last: justify;
        }
        .message-time {
          text-align: center;
          font-weight: 300;
        }
      }
      .message-content {
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        font-size: $SmallFont;
        white-space: pre-wrap;
      }
    }
  }
}
</style>
