<template>
  <div class="bi-notice">
    <el-popover
      placement="top-end"
      trigger="hover"
      popper-class="notice-popper"
      :popper-options="{ padding: '0px' }"
      @show="handleShow"
      @hide="handleHide"
    >
      <div class="bi-notice-box">
        <el-card
          class="box-card"
          shadow="never"
          :body-style="bodyStyle"
        >
          <div
            slot="header"
            class="notice-header"
          >
            <span>系统通知</span>
            <el-button
              type="text"
              :disabled="badgeNum === 0 && !currentUnreadNum"
              @click="noticeAllRead"
            >{{ badgeNum === 0 && !currentUnreadNum ? '全部已读' : '全部标为已读' }}</el-button>
          </div>
          <ul
            v-infinite-scroll="load"
            class="notice-list"
            :infinite-scroll-immediate="false"
            :infinite-scroll-disabled="noticeListDisabled"
            :infinite-scroll-delay="300"
            style="overflow: auto"
          >
            <li
              v-for="item in noticeList"
              :key="item._id.oid"
              class="notice-item"
              :class="{ unread: !item.is_read }"
              @click="detail(item)"
            >
              <div class="header">
                <p class="title">{{ item.title }}</p>
                <p class="time">{{ item.send_time }}</p>
              </div>
              <div class="notice-content-box">
                <div class="content">{{ item.describe }}</div>
                <div class="username">产品负责人: {{ item.user_name||'-' }}</div>
              </div>
            </li>
            <p
              v-if="noticeListLoading"
              style="font-size: 14px; color: #5e6d82; text-align: center"
            >加载中...</p>
            <p
              v-if="noMore"
              style="font-size: 14px; color: #5e6d82; text-align: center"
            >没有更多了</p>
          </ul>
        </el-card>
      </div>
      <el-badge
        slot="reference"
        class="notice-badge"
        :value="badgeNum"
        :hidden="badgeNum === 0"
      >
        <el-button
          class="notice-button"
          type="text"
        >
          <svg class="iconpark-icon">
            <use href="#el-icon-warn1" />
          </svg>
        </el-button>
      </el-badge>
      <!-- <el-badge
        slot="reference"
        class="notice-badge"
        :value="badgeNum"
        :hidden="badgeNum === 0"
      >
        <el-button
          class="notice-button"
          type="text"
        >
          <i class="el-icon-warn1"></i>
        </el-button>
      </el-badge> -->
    </el-popover>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="680px"
      top="-38px"
      :before-close="handleClose"
      append-to-body
      :show-close="false"
      :custom-class="`notice-open-dialog ${theme}`"
    >
      <div class="notice-open-container">
        <div class="notice-bg">
          <img :src="`https://frontend-oss.zzwwiidd.com/bi-element-ui/NoticeCenter/notice-${theme}.png`">
        </div>
        <div class="notice-open-box">
          <!-- <el-scrollbar> -->
          <p class="notice-open-tile">{{ openNotice.title }}</p>
          <div class="notice-open-box-scrollbar">
            <div class="notice-open-content">
              <div class="notice-open-content-info">
                <div>产品负责人: <span>{{ openNotice.user_name || '-' }}</span></div>
                <div>发送时间: <span>{{ openNotice.send_time }}</span></div>
              </div>
              <div v-html="openNotice.content"></div>
            </div>
          </div>
          <!-- </el-scrollbar> -->
          <div class="notice-open-button">
            <el-button
              type="primary"
              @click="noticeClose(openNotice.extra_id)"
            >知道了</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
    <el-drawer
      custom-class="bi-notice-drawer"
      title="消息详情"
      :visible.sync="detailVisible"
      direction="rtl"
      size="538px"
      destroy-on-close
      append-to-body
      :modal="true"
      :style="{ '--headHegiht': headerHeight }"
      @open="handleDetailOpen"
      @close="handleDetailClose"
    >
      <el-scrollbar>
        <div class="notice-detail-box">
          <div class="notice-detail">
            <div class="detail-header">
              <p class="detail-title">{{ detailData.title }}</p>
              <p class="detail-time">{{ detailData.send_time }}</p>
            </div>
            <div
              class="detail-content"
              v-html="detailData.content"
            />
          </div>
        </div>
      </el-scrollbar>
    </el-drawer>
  </div>
</template>

<script>
// import WebSocketClass from '../../WebSocket'
import { diffTime } from '../../utils/time/index'
import request from '../../utils/request/index.js'
import { registerNoticeDialogHost, unregisterNoticeDialogHost } from '../noticeDialogApi'
export default {
  name: 'BiNoticeCenter',
  props: {
    headerHeight: {
      type: String,
      default: '58'
    },
    system: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // dialogImg: 'https://wanxiaomeng-1255977238.file.myqcloud.com/bi-element-ui/NoticeCenter/notice.png',
      openNotice: {
        id: '',
        title: '',
        content: ``,
        username: '',
        send_time: ''
      },
      page: 1,
      last_id: '',
      last_send_time: '',
      dialogVisible: false,
      noticeTimer: null,
      badgeNum: 0,
      is_open_page: 1,
      bodyStyle: {
        padding: '0'
      },
      detailVisible: false,
      noticeListDisabled: false,
      noticeListLoading: false,
      noMore: false,
      detailData: {},
      noticeList: [],
      /** true：知道了仅关弹窗，不调 noticeRead（openNoticeDialog 打开） */
      dialogCloseSkipsNoticeRead: false
    }
  },
  inject: ['theme'],
  computed: {
    currentUnreadNum() {
      return this.noticeList.some((item) => item.is_read === 0)
    }
    // dialogImg() {
    //   return this.theme === 'dark' ? 'https://frontend-oss.zzwwiidd.com/bi-element-ui/NoticeCenter/notice-dark.png' : 'https://frontend-oss.zzwwiidd.com/bi-element-ui/NoticeCenter/notice-light.png'
    // }
  },
  mounted() {
    this.noticeList = []
    this.last_id = ''
    this.last_send_time = ''
    this.initUnreadNum()
    registerNoticeDialogHost(this)
  },
  beforeDestroy() {
    unregisterNoticeDialogHost(this)
  },
  methods: {
    handleClose() {},
    async handleShow() {
      this.noticeList = []
      this.last_id = ''
      this.last_send_time = ''
      this.getNoticeList()
    },
    handleHide() {
      this.page = 1
      this.noticeListDisabled = false
    },
    setUnreadNum(unread_num) {
      this.badgeNum = unread_num
    },
    popupNotice(data, onlyread = false) {
      this.dialogCloseSkipsNoticeRead = false
      console.log('🚀 ~ data:', data)
      console.log('🚀 ~ data:', data.id)
      this.openNotice.title = data.title
      this.openNotice.user_name = data.user_name
      this.openNotice.send_time = data.send_time
      this.openNotice.id = data._id.oid || ''
      this.openNotice.extra_id = data.extra_id
      this.openNotice.content = data.content
      this.dialogVisible = true
      onlyread !== true && this.noticePoped(this.openNotice.id)
    },
    /** 供宿主 openNoticeDialog 使用：不调 noticePoped，关闭时不调 noticeRead */
    openExternalNoticeDialog({ title, user_name, send_time, content }) {
      this.dialogCloseSkipsNoticeRead = true
      this.openNotice.title = title || ''
      this.openNotice.user_name = user_name
      this.openNotice.send_time = send_time || ''
      this.openNotice.id = ''
      this.openNotice.extra_id = undefined
      this.openNotice.content = content || ''
      this.dialogVisible = true
    },
    async noticeClose(id) {
      this.dialogVisible = false
      if (this.dialogCloseSkipsNoticeRead) {
        this.dialogCloseSkipsNoticeRead = false
        return
      }
      this.noticeRead(id)
    },
    async noticeRead(id) {
      await request({
        env: this.$BI.env,
        system: 'zq',
        api: '/api/system_notice/close',
        data: {
          id
        }
      })
    },
    async noticePoped(msg_id) {
      await request({
        env: this.$BI.env,
        system: 'service_center',
        api: '/api/admin/message/setPopup',
        data: {
          system: this.system,
          msg_id
        }
      })
    },
    async initUnreadNum() {
      const res = await request({
        env: this.$BI.env,
        system: 'service_center',
        api: '/api/admin/message/getUnreadNum',
        data: {
          system: this.system
        }
      })
      if (res.status_code === 1) {
        this.setUnreadNum(res.data || 0)
      } else {
        this.setUnreadNum(0)
      }
    },
    detail(item) {
      // this.$set(this, 'detailData', item)
      item.is_read = 1
      this.popupNotice(item, true)
      // this.detailVisible = true
      this.handleNoticeRead(item._id.oid)
    },
    async getNoticeList() {
      this.noticeListLoading = true
      try {
        const res = await request({
          env: this.$BI.env,
          system: 'service_center',
          api: '/api/admin/message/getSystemMessage',
          data: {
            system: this.system,
            last_id: this.last_id,
            last_send_time: this.last_send_time
          }
        })
        if (res.status_code === 1) {
          if (res.data.length) {
            const arr = [...this.noticeList, ...res.data]
            const map = new Map()
            for (const item of arr) {
              map.set(item._id.oid, item)
            }
            const noticeList = [...map.values()]
            noticeList.sort((a, b) => diffTime(a, b))
            this.noticeList = noticeList

            this.noMore = false
            this.noticeListDisabled = false
          } else {
            this.noMore = true
            this.noticeListDisabled = true
          }
          if (this.noticeList.length && this.noticeList[this.noticeList.length - 1]) {
            this.last_id = this.noticeList[this.noticeList.length - 1]._id.oid
            this.last_send_time = this.noticeList[this.noticeList.length - 1].send_time
          }
        }
        this.noticeListLoading = false
      } catch (error) {
        this.noticeListLoading = false
      }
    },
    async handleNoticeRead(msg_id) {
      const res = await request({
        env: this.$BI.env,
        system: 'service_center',
        api: '/api/admin/message/read',
        data: {
          system: this.system,
          msg_id
        }
      })
      if (res.status_code === 1) {
        this.setUnreadNum(res.data.unread_num)
      }
    },
    load() {
      this.getNoticeList()
    },
    async noticeAllRead() {
      await request({
        env: this.$BI.env,
        system: 'service_center',
        api: '/api/admin/message/isReadAll',
        data: {
          system: this.system,
          type: 'system'
        }
      })
      this.badgeNum = 0
      this.noticeList.map((item) => {
        item.is_read = true
      })
    },
    handleDetailOpen() {},
    handleDetailClose() {}
  }
}
</script>
<style lang="scss" scoped>
.bi-notice {
  display: flex;
  align-items: center;

  ::v-deep > span {
    display: flex;
    align-items: center;
  }
}
.notice-button {
  padding: 5px;
  width: 32px;
  height: 32px;
  display: block;
  overflow: hidden;
  border-radius: 4px;
  .iconpark-icon,
  .iconpark-icon:hover {
    font-size: 20px;
    color: #8893aa;
  }
  &:hover {
    background-color: #f2f3f5;
  }
  ::v-deep {
    span {
      display: block;
      height: 100%;
      width: 100%;
    }
  }
}
.notice-badge {
  display: flex;
  height: 32px;
  padding: 0;
  ::v-deep .el-badge__content.is-fixed {
    top: 2px;
    right: 15px;
  }
}
.bi-notice-box {
  width: 600px;
  .el-card {
    border: none !important;
    padding: 0 !important;
    width: initial !important;
    min-width: initial !important;
    margin: initial !important;

    ::v-deep.el-card__header {
      padding: 15px;
    }
  }
  .notice-header {
    font-size: 14px;
    font-weight: 500;
    line-height: 28px;
    display: flex;
    justify-content: space-between;
    padding: 0 6px;
    .el-button {
      font-size: 14px;
      width: initial !important;
      line-height: 28px;
      padding: 0;
    }
  }
  .notice-list,
  .notice-item {
    list-style: none;
    margin: 0;
    padding: 0;
  }
  .notice-list {
    height: 300px;
    .notice-item {
      padding-left: 28px;
      padding-right: 17px;
      padding-bottom: 10px;
      padding-top: 10px;
      margin: 0;
      border-bottom: 1px solid #e5e6eb;
      position: relative;
      cursor: pointer;

      &.unread::before {
        content: ' ';
        position: absolute;
        width: 8px;
        height: 8px;
        background: #f53f3f;
        border: 1px solid #ffffff;
        border-radius: 10px;
        left: 14px;
        top: 17px;
      }
      .header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 4px;
        line-height: 22px;
        .title {
          font-size: 14px;
          font-weight: 500;
          color: #323335;
          margin: 0;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          flex: 1;
        }
        .time {
          font-size: 14px;
          font-weight: 400;
          color: #86909c;
          margin: 0;
          flex: 0 0 auto;
        }
      }
      .notice-content-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 10px;
        .content {
          //  flex: 0 0 auto;
        }
        .username {
          font-size: 12px;
          font-weight: 400;
          color: #86909c;
          margin: 0;
          flex: 0;
          white-space: nowrap;
        }
      }
      .content {
        font-size: 12px;
        font-weight: 400;
        color: #86909c;
        line-height: 22px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
}
</style>
<style lang="scss">
.notice-popper {
  padding: 0 !important;
}
.notice-open-dialog {
  background: none !important;
  box-shadow: none !important;

  .el-dialog__header {
    display: none;
  }
  .el-dialog__body {
    padding: 0;
  }
  .notice-bg {
    img {
      width: 100%;
      display: block;
      height: 180px;
    }
  }
  .notice-open-box {
    // margin-top: -36px;
    // height: calc(calc(100vh - 3vh - 281px) - 60px);
    position: relative;
    background: #ffffff;
    border-radius: 0 0 4px 4px;
    // padding-bottom: 40px;
    .notice-open-box-scrollbar {
      height: calc(calc(100vh - 3vh - 351px) * 0.95 - 50px);
      padding: 10px 0;
    }
    .notice-open-tile {
      margin: 0;
      text-align: center;
      font-size: 18px;
      font-weight: 600;
      color: #323335;
      line-height: 30px;
    }
    .notice-open-content {
      font-size: 14px;
      font-weight: 400;
      color: #333333;
      line-height: 20px;
      height: 100%;
      overflow-y: auto;
      padding: 0 20px;
      * {
        max-width: 100%;
      }
      a {
        color: #24d87b;
        text-decoration: underline;
      }
      ul,
      li {
        list-style: inherit;
      }
      .notice-open-content-info {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 10px;
        color: #86909c;
        gap: 30px;
        margin-bottom: 20px;
        span {
          font-weight: 400;
          color: #323335;
        }
      }
    }
    .notice-open-button {
      // position: absolute;
      box-shadow: 0px -1px 0px 0px #f2f3f5;
      box-sizing: border-box;
      bottom: 10px;
      left: 0;
      width: 100%;
      text-align: center;
      padding: 14px 20px;
    }
  }
  &.dark {
    .notice-open-box {
      background: rgba(31, 31, 31, 1);
      .notice-open-tile,
      .notice-open-content,
      .notice-open-content-info span {
        color: rgba(255, 255, 255, 0.85);
      }
      .notice-open-content-info {
        color: rgba(255, 255, 255, 0.45);
      }
    }
    .notice-open-button {
      box-shadow: 0px -1px 0px 0px rgba(48, 48, 48, 1);
    }
  }
}
.bi-notice-drawer {
  .notice-open-container {
    overflow: hidden;
  }
  .el-drawer__body,
  .notice-detail-box {
    .notice-detail {
      padding: 20px;
      .detail-title {
        font-size: 16px;
        font-weight: 500;
        color: #333333;
        margin-top: 0;
        margin-bottom: 10px;
      }
      .detail-time {
        font-size: 12px;
        font-weight: 400;
        color: #999999;
        margin-bottom: 20px;
      }
      .detail-content {
        font-size: 14px;
        font-weight: 400;
        color: #333333;
        line-height: 20px;
        a {
          color: #24d87b;
          text-decoration: underline;
        }
        * {
          max-width: 100% !important;
        }
      }
    }
  }
}
</style>
