<template>
  <message-component>
    <div ref="messageIcon" v-bind="$attrs" class="message-icon">
      <span v-show="unReadMessages?.newCount" class="un-read-num">
        {{ (unReadMessages?.newCount || 0) > 99 ? '99+' : unReadMessages?.newCount }}
      </span>
      <svg-icon name="message" class="bell"></svg-icon>
    </div>
    <el-popover
      placement="bottom-start"
      :width="'400px'"
      :show-arrow="false"
      :virtual-ref="messageIcon"
      trigger="click"
      virtual-triggering
    >
      <div class="message-popover-content">
        <div class="title">
          <!-- <span class="unread-count">{{ unReadMessages?.newCount || 0 }}</span>
          <span>条消息</span> -->
          最近消息
        </div>
        <div class="message-list">
          <div
            v-for="message in unReadMessages?.messages?.slice(0, 2)"
            :key="message.sendUserId"
            class="message-row"
            @click="onReceiveMessage(message)"
          >
            <!-- <div class="message-send-user">
              <div class="user-name" :title="message.sendUserName">{{ message.sendUserName }}</div>
              <div class="message-time">{{ dayjs(message.sendTime).format('HH:mm') }}</div>
            </div>
            <pre class="flex-1 message-content" v-html="message.content"></pre> -->
            <div class="send-user truncate">{{ message.sendUserName }}</div>
            <!-- <div class="send-content truncate">{{ message.content }}</div> -->
            <div class="send-content truncate">{{ transContent(message.content) }}</div>
          </div>
        </div>
        <confirm-button
          size="small"
          between
          ok-text="收消息"
          cancel-text="发消息"
          @confirm="onReceiveMessage"
          @cancel="onSendMessage"
        ></confirm-button>
      </div>
    </el-popover>
    <message-window
      v-model="visibleMessageWindow"
      v-model:type="messageWindowType"
      v-model:replyUserId="replyUserId"
      :paper-path="props.paperPath"
    ></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'

const props = withDefaults(
  defineProps<{
    type?: 'view' | 'send'
    replyUserId?: number | null
    messageVisible?: boolean | null
    paperPath?: string | null
  }>(),
  { type: 'view', replyUserId: null, paperPath: null, messageVisible: false }
)
const transContent = (content: any) => {
  return content.replaceAll(/<[^>]+>/gim, ' ')
  // return content.replaceAll('<div>', ' ').replaceAll('<br>', ' ').replaceAll('<\/div>', '').replaceAll('<\/br>', '')
}
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() - 6000
      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)

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
}
</script>

<style scoped lang="scss">
.message-icon {
  display: grid;
  place-items: center;
  font-size: $LargeFont;
  position: relative;
  .bell {
    cursor: pointer;
  }
  .un-read-num {
    position: absolute;
    width: 24px;
    height: 24px;
    line-height: 24px;
    right: -15px;
    top: -15px;
    text-align: center;
    color: $color--white;
    font-size: 10px;
    border-radius: 50%;
    background-color: $DangerColor;
  }
}
.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>
