<template>
  <div class="message-must-read-box">
    <el-dialog
      :visible.sync="visible"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :modal-append-to-body="false"
      class="msg-dialog-container"
      width="1000px"
    >
      <div slot="title" class="dialog-title">
        <span v-if="idList" class="content">消息管理中心<i class="el-icon-arrow-right"/>重要消息必读（{{ currentMsgNum }}/{{ idList.length }}）</span>
        <div class="dialog-btns">
          <el-button v-if="prevId" type="primary" class="msg-btn" @click="setCurrentId(prevId, 'prev')">
            上一条
          </el-button>
          <el-button v-if="nextId" :loading="isBtnLoading" :disabled="isUnRead" type="primary" class="msg-btn" @click="setCurrentId(nextId, 'next')">
            下一条
            <span v-if="isUnRead">({{ downCount }}s)</span>
          </el-button>
          <el-button v-else :loading="isBtnLoading" :disabled="isUnRead" type="primary" class="msg-btn" @click="onClose">
            关闭
            <span v-if="isUnRead">({{ downCount }}s)</span>
          </el-button>
        </div>
      </div>

      <div v-loading="isLoading" class="msg-detail-box">
        <div v-if="details" class="msgd-main">
          <div class="msgd-top">
            <div class="msg-title" v-text="details.title"/>
            <div class="msg-details-main" v-html="details.content"/>
          </div>

          <div v-if="details.attachments" class="msgd-bottom">
            <div v-if="details.attachments.length" class="msgd-file-num">
              <!-- 附件{{ details.attachments.length }}个 -->
              <i class="el-icon el-icon-share"/>
              <div class="msgdf-list-wrap">
                <div v-for="(item,index) in details.attachments " :key="index" class="file-item">
                  <div class="download-file file-item-title">
                    <a :href="getDownloadUrl(item.fileUrl)" class="file-item-title" download @click="toDownload(item)" v-text="item.fileName"/>
                  </div>
                  <div class="file-item-desc">{{ getFileSize(item.size) }}</div>
                </div>
              </div>
            </div>
          </div>

        </div>
        <div class="msg-desc">
          <span>管理员发送于 {{ details.pushTime|moment('YYYY-MM-DD HH:mm') }}</span>
          <span>您可前往消息中心继续查看该信息！</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { hideMessageMustRead, isShowMessageMustRead } from '../../functions/messageMustReadFn'
export default {
  name: 'MessageMustRead',
  props: {
    httpMethods: {
      type: Function,
      default: null
    },
    refreshUnreadCount: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      idList: null,
      currentMsgNum: 0, // 当前重要消息
      visible: false, // 用于判断内容是否展示
      isShow: isShowMessageMustRead(), // 控制该组件是否展示（目前为登录和清除cookie时显示组件）
      currentId: null,
      prevId: null,
      nextId: null,

      details: {},
      isLoading: false,
      isBtnLoading: false,
      interval: null,
      defaultDownCount: 5, // 云控返回计数
      downCount: 5, // 倒数
      isUnRead: true
    }
  },
  watch: {
    'currentId': {
      deep: true,
      handler() {
        this.downCount = this.defaultDownCount
        this.setPrevNextId()
        if (this.visible) {
          this._getMsgDetail()
        }
      }
    }
  },
  mounted() {
    if (this.isShow) {
      this._getSeconds()
      this._getRequireMsg()
    }
  },
  methods: {
    // 获取云控读秒数
    _getSeconds() {
      const params = {
        url: '/admin/v1/operation/message/getSeconds',
        method: 'post',
        data: {}
      }
      this.isBtnLoading = true
      this.httpMethods(params).then(res => {
        const { data } = res || {}
        this.downCount = data
        this.defaultDownCount = data
      }).finally(() => {
        this.isBtnLoading = false
      })
    },
    // 获取必读消息id列表
    _getRequireMsg() {
      const params = {
        url: '/admin/v1/operation/message/findRequiredIds',
        method: 'post',
        data: { pushChannel: '30' }
      }
      this.isLoading = true
      this.httpMethods(params).then(res => {
        const { data } = res || {}
        this.idList = data
        this.currentMsgNum = (data && data.length) || 0
        this.currentId = data && data[0]
        this.visible = Array.isArray(data) && data.length > 0
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 获取信息详情
    _getMsgDetail() {
      if (!this.currentId) return
      this.isLoading = true
      const params = {
        url: '/admin/v1/operation/message/findSubjectById',
        method: 'post',
        data: { id: this.currentId }
      }
      this.httpMethods(params).then(res => {
        const { data } = res || {}
        this.details = data

        clearInterval(this.interval)
        this.interval = setInterval(() => { // 倒计时关闭弹窗
          if (!this.isBtnLoading) {
            this.downCount--
            if (this.downCount < 0) {
              this.isUnRead = false
              clearInterval(this.interval)
            }
          }
        }, 1000)
        this.refreshUnreadCount()
      }).finally(() => {
        this.isLoading = false
      })
    },
    onClose() {
      this.visible = false
      hideMessageMustRead() // 设置cookie关闭
    },
    // 设置当前数据id
    setCurrentId(id, type) {
      if (!id) return
      this.currentId = id

      // 点击上一条、下一条时，更新当前页数
      if (type === 'next') {
        this.currentMsgNum = this.currentMsgNum - 1
      } else if (type === 'prev') {
        this.currentMsgNum = this.currentMsgNum + 1
      }

      // 上一条、下一条时返回该条数据是否已读（已读则不倒数）
      const params = {
        url: '/admin/v1/operation/message/findRequiredIds',
        method: 'post',
        data: { pushChannel: '30' }
      }
      this.isBtnLoading = true
      this.httpMethods(params).then(res => {
        const { data } = res || {}
        const result = (data || []).find(ele => `${ele}` === `${this.currentId}`)
        this.isUnRead = !!result
      }).finally(() => {
        this.isBtnLoading = false
      })
    },
    // 设置上一条、下一条数据id
    setPrevNextId() {
      if (!this.currentId) return
      const ids = this.idList || []
      const index = ids.indexOf(this.currentId) + 1
      if (index === 0) {
        this.nextId = null
      } else {
        this.nextId = ids[index]
      }

      const i = ids.indexOf(this.currentId) - 1
      this.prevId = ids[i]
    },
    // 文件单位展示
    getFileSize(size) {
      size = size || 0
      size = Number(size)
      const canEsp = 1000
      const kbSize = size / canEsp
      const mSize = kbSize / canEsp
      const gSize = mSize / canEsp
      const a = 1
      let value = 0
      let dw = 'B'
      if (kbSize < a) {
        value = size
        dw = 'B'
      } else if (mSize < a) {
        value = kbSize
        dw = 'KB'
      } else if (gSize < a) {
        value = mSize
        dw = 'M'
      } else {
        value = gSize
        dw = 'G'
      }
      const retuVList = (Number(value).toFixed(2) + '').split('.')
      let returnV = retuVList[0]
      // KB和B都是没有小数点展示的
      if (retuVList[1][1] >= 5 && !(dw === 'KB' || dw === 'B')) {
        let point = Number(retuVList[1][0]) + 1
        point = point === 0 || dw === 'KB' || dw === 'B' ? '' : '.' + point
        returnV = returnV + '.' + point
      } else {
        let point = Number(retuVList[1][0])
        if (dw === 'KB' || dw === 'B') {
          returnV = Number(value).toFixed(0)
        } else {
          point = point === 0 || dw === 'KB' || dw === 'B' ? '' : '.' + point
          returnV = returnV + point
        }
      }
      // 小数点后一位四舍五入
      return returnV + dw
    },
    // 下载地址转换
    getDownloadUrl(url) {
      return (url || '').replace('/oss?', '/oss/download?')
    },
    // 附件下载
    toDownload(file) {
      const { id: attachmentId } = file
      const params = {
        url: '/admin/v1/operation/message/attachmentBury',
        method: 'post',
        data: { id: this.currentId, attachmentId }
      }
      this.httpMethods(params)
    }
  }
}
</script>

<style lang="scss" scoped>
$border_color:#dbdcde;
.message-must-read-box {
  .msg-dialog-container {
    line-height: normal;
    /** 必读重要消息展示在最上面 */
    z-index: 999999999 !important;

    /deep/ .el-dialog {
      background-color: #f1f3f7;

    }
    /deep/ .el-dialog__body {
      padding: 0 0 30px;
      color: #606266;
      font-size: 14px;
    }
    .dialog-title {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      border-bottom: solid 1px $border_color;
      padding: 0 0 5px;
      .content {
        font-size: 16px;
      }
    }

  }

  .msg-detail-box{
    font-size: 14px;
    display: flex;
    flex-direction: column;
    margin: 0 20px;
    background: #fff;
    padding: 0 20px;
    max-height: 85vh;

    .msg-dh-options{
      margin-bottom: 15px;
      z-index: 1;
      .msg-btn{
        padding: 9px 20px;
      }
    }
    .msgd-main{
      width: 100%;
      color:#606266;
      display: flex;
      flex-direction: column;
      padding-right:3px;
      flex-grow: 1;
      overflow: auto;

      .msgd-top{
        flex:1;
        .msg-title {
          font-weight: bolder;
          position: relative;
          border-bottom: 1px solid $border_color;
          padding: 0 0 0 15px;
          font-size: 16px;
          line-height: 60px;

          &::before {
            position: absolute;
            content: "";
            width: 8px;
            height: 8px;
            border-radius: 100%;
            background: #cc0000;
            left: 0;
            top: 50%;
            margin-top: -4px;
          }
        }
        .msg-details-main{
          line-height: 25px;
          min-height: 250px;
          /deep/ a {
            color: #1890ff;
            text-decoration: underline;
          }
        }
      }
      .msgd-bottom{
        padding:20px 0px;
        display: block;
        border-bottom: 1px solid $border_color;
        .msgd-file-num {
          display: flex;
          flex-direction: row;
          .el-icon {
            margin-right: 12px;
            font-size: 20px;
            padding: 12px;
          }

          .msgdf-list-wrap{
            flex-grow: 1;
            .file-item{
              display: inline-block;
              background: #eeeeee;
              padding: 10px 30px;
              margin-right:20px;
              margin-bottom:20px;
              min-width:200px;
              max-width: 100%;
              cursor: default;
              .file-item-title{
                text-align: left;
                word-break: break-all;
              }
              .file-item-desc{
                padding-top:10px;
                font-size: 12px;
                color:#9fa0a7;
              }
            }
          }
        }

      }
    }
    .msg-desc{
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      line-height: 60px;
    }
  }

  /deep/ .v-modal {
    /** 必读重要消息展示在最上面 */
    z-index: 999999998 !important;
  }
}
</style>
