<script setup lang="ts">
import type { MessageType } from '@/types'
import { getMessages, readMessages } from '@/api/base'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
const router = useRouter()

let list = $ref<MessageType[]>([])
const currentList = $computed(() => {
  return list.map(item => {
    try {
      item.payload = JSON.parse(item.payload)
    } catch (error) {
      console.log(error)
    }
    return item
  })
})
function fetchList() {
  getMessages({ source: 'RESOURCE_MARKETING', is_read: 0, is_platform: 0, limit: 100 }).then(res => {
    list = res.data.data
  })
}
onMounted(fetchList)

function handleClick(data: MessageType) {
  readMessages({ message_id: data.id }).then(() => {
    fetchList()
  })
  const payload = data.payload || {}
  if (userStore.role?.id === 5) {
    // 指导老师
    // 实验评分
    if (payload?.channel === 1) {
      router.push({ path: '/admin/lab/score', query: payload })
    }
  } else if (userStore.role?.id === 6) {
    // 专家
    // 大赛评分
    if (payload?.channel === 3) {
      router.push({ path: '/admin/contest/check', query: payload })
    }
  } else {
    // 学生
    // 实验成绩
    if (payload?.channel === 2) {
      router.push({ path: '/student/lab', query: payload })
    }
  }
}
</script>

<template>
  <el-popover trigger="click" placement="top-start" :width="380">
    <template #reference>
      <div class="app-message">
        <div class="icon"></div>
        <p>我的待办</p>
        <span v-if="currentList.length">{{ currentList.length }}</span>
      </div>
    </template>
    <ul class="app-message-list" v-if="currentList.length">
      <li v-for="item in currentList" :key="item.id" @click="handleClick(item)">{{ item.payload.message }}</li>
    </ul>
    <el-empty description="暂无数据" v-else />
  </el-popover>
</template>

<style lang="scss" scoped>
.app-message {
  position: fixed;
  right: 40px;
  bottom: 40px;
  padding: 1px;
  display: flex;
  align-items: center;
  min-width: 130px;
  height: 40px;
  background-color: #fff;
  border-radius: 20px;
  box-sizing: border-box;
  cursor: pointer;
  .icon {
    width: 38px;
    height: 38px;
    background: var(--main-color) url(@/assets/images/icon_message.png) no-repeat center center;
    background-size: 22px;
    border-radius: 50%;
    overflow: hidden;
  }
  p {
    margin: 0 5px;
    font-size: 14px;
    font-family: Source Han Sans CN;
    line-height: 24px;
    color: #666666;
  }
  span {
    margin-top: -10px;
    width: 16px;
    height: 16px;
    font-size: 12px;
    line-height: 16px;
    color: #ffffff;
    background-color: var(--main-color);
    text-align: center;
    border-radius: 50%;
    overflow: hidden;
  }
}
.app-message-list {
  li {
    padding: 8px;
    border-radius: 6px;
    &:hover {
      background-color: #f8f9fb;
    }
  }
}
</style>
