<template>
  <div class="bst-notice-container">
    <el-popover
      placement="bottom"
      width="500"
      trigger="click"
      popper-class="bst-notice-popover"
      @show="handleAfterEnter"
    >
      <div slot="reference">
        <el-badge :hidden="unreadCount <= 0" :value="unreadCount" :max="99" class="notice-badge">
          <i class="el-icon-bell"></i>
        </el-badge>
      </div>

      <el-row type="flex" justify="space-between" style="padding:10px;">
        <div class="filter-section">
          <el-radio-group v-model="queryParams.isRead" size="mini" @change="handleQuery">
            <el-radio-button :label="null">全部</el-radio-button>
            <el-radio-button :label="false">未读</el-radio-button>
            <el-radio-button :label="true">已读</el-radio-button>
          </el-radio-group>
        </div>
        <el-button type="text" size="mini" @click="handleRead(null)">全部已读</el-button>
      </el-row> 
      
      <div class="notice-list" @scroll="handleScroll">
        <el-collapse accordion v-if="messgeList.length" @change="handleChangeCollapse">
          <el-collapse-item v-for="message in messgeList" :name="message.id">
            <div slot="title" class="notice-title-box">
              <div class="notice-title">
                <dict-tag :options="dict.type.message_bst_type" :value="message.bstType" size="mini"/>
                [{{message.title}}]
                {{message.content}}
              </div>
              <el-badge is-dot :hidden="message.isRead">
                <div class="notice-time">{{message.createTime}}</div>
              </el-badge>
            </div>
            <div class="notice-content" @click="handleClickMessage(message)">{{message.content}}</div>
          </el-collapse-item>
        </el-collapse>
        <el-empty v-if="messgeList.length == 0 && finished" description="暂无消息"></el-empty>
        <div v-if="!finished && !loading" class="loading-more">下拉加载更多</div>
        <div v-if="finished && messgeList.length > 0" class="loading-more">没有更多了</div>
        <div v-if="loading" class="loading-more"><i class="el-icon-loading"></i>加载中...</div>
      </div>
    </el-popover>

    <task-view-dialog :show.sync="showTaskDialog" :id="bstId" />

  </div>
</template>

<script>
import { appGetReceiveList, appReadMessage, appGetUnreadCount } from '@/api/app/message'
import { getToken } from '@/utils/auth'
import { MessageBstType } from '@/utils/enums'
import TaskViewDialog from '@/views/bst/task/components/TaskViewDialog.vue'  

export default {
  name: 'NoticeTip',
  components: {
    TaskViewDialog
  },
  dicts: ['message_bst_type'],
  data() {
    return {
      messgeList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        isRead: null
      },
      unreadCount: 0,
      selectedNotice: null,
      detailVisible: false,
      ws: null,
      loading: false,
      total: 0,
      row: null,
      finished: false,
      showTaskDialog: false,
      bstId: null
    }
  },
  created() {
    this.getUnReadCount();
    this.initWebSocket();
  },
  mounted() {
    this.tryGetPermission();
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.close()
    }
  },
  methods: {
    // 点击消息
    handleClickMessage(message) {
      if (message == null) {
        return;
      }
      this.bstId = message.bstId;

      if (message.bstType == MessageBstType.TASK) {
        this.showTaskDialog = true;
      }


    },
    // 进入后获取未读消息数量和列表
    handleAfterEnter() {
      this.getUnReadCount();
      this.getList();
    },
    // 获取未读消息数量
    async getUnReadCount() {
      const res = await appGetUnreadCount();
      this.unreadCount = res.data;
    },
    // 获取通知列表
    async getList() {
      this.total = 0;
      this.messgeList = [];
      this.queryParams.pageNum = 0;
      await this.lodList();
    },
    async lodList() {
      this.queryParams.pageNum ++;
      this.loading = true;
      try {
        const res = await appGetReceiveList(this.queryParams);
        this.messgeList.push(...res.rows);
        this.total = res.total;
        this.finished = this.messgeList.length >= this.total;
      } catch (error) {
        console.error('获取消息列表失败:', error)
      } finally {
        this.loading = false;
      }
    },
    initWebSocket() {
      const token = getToken(); // 获取token
      this.ws = new WebSocket(`${process.env.VUE_APP_WS_HOST}/ws/message?token=${token}`);
      
      this.ws.onopen = () => {
        console.log('WebSocket连接成功');
      };
      
      this.ws.onmessage = (event) => {
          // 处理消息
          let message = JSON.parse(event.data);
          this.showDesktopNotification(message);
          if (message.id != null) {
            this.unreadCount ++;
          }
      };
      
      this.ws.onclose = (event) => {
        console.log('WebSocket连接关闭，尝试重连...');
        setTimeout(this.initWebSocket, 5000); // 5秒后重连
      };
      
      this.ws.onerror = (error) => {
          console.error('WebSocket错误:', error);
      };
    },
    // 桌面通知
    showDesktopNotification(message) {
      this.tryGetPermission();
      if (Notification.permission === 'granted') {
        new Notification(`${message.title}`, {
          body: message.content,
          icon: '/favicon.ico'
        })
      }
    },
    // 获取通知权限
    tryGetPermission() {
      if (Notification.permission !== 'granted') {
        Notification.requestPermission();
      }
    },
    // 处理折叠
    handleChangeCollapse(name) {
      let row = this.messgeList.find(item => item.id == name);
      if (row != null && !row.isRead) {
        this.handleRead(row.id);
      }
    },
    // 处理消息已读
    async handleRead(id) {
      // 调用接口
      let res = await appReadMessage(id);
      if (res.code === 200 && res.data > 0) {
        this.getUnReadCount();
        if (id != null) {
          this.messgeList.forEach(item => {
            if (item.id == id) {
              item.isRead = true;
            }
          });
        } else {
          this.getList();
        }
      }
    },
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleScroll(e) {
      const { scrollHeight, scrollTop, clientHeight } = e.target;
      // 距离底部20px时触发加载
      if (scrollHeight - scrollTop - clientHeight < 20 && !this.loading && !this.finished) {
        this.lodList();
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.bst-notice-container {
  position: relative;
  display: inline-block;

  .notice-badge {
    cursor: pointer;
    
    ::v-deep .el-badge__content {
      top: 12px;
      right: 12px;
    }
    
    .el-icon-bell {
      font-size: 20px;
      color: #606266;
      
      &:hover {
        color: #409EFF;
      }
    }
  }
}

.notice-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
  
  .loading-more {
    text-align: center;
    color: #909399;
    font-size: 12px;
    padding: 10px 0;
  }

  .notice-title-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: row;
    width: calc(100% - 1em);

    .notice-title {
      padding-left: 10px;
      position: relative;
      font-size: 12px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .notice-time {
      position: relative;
      font-size: 12px;
      color: #999;
      align-items: center;
      height: 1.5em;
      line-height: 1.5em;
      min-width: 120px;
      margin-left: 6px;
    }
  }
  .notice-content {
    cursor: pointer;
    padding-left: 10px;
    padding-right: 10px;
    font-size: 12px;
    color: #606266;
    transition: color 0.3s;
    &:hover {
      color: #409EFF;
    }
  }
}
</style>

<style lang="scss">
.bst-notice-popover {
  padding: 0 !important;
}
</style>


