<template>
  <div :class="['message-drawer']">
    <el-drawer
      :visible.sync="isShow"
      :modal-append-to-body="false"
      :show-close="false"
      :withHeader="false"
      size="19%"
      @close="close"
      @open="close"
    >
      <div
        class="message-drawer-container"
        v-loading="loading"

        element-loading-background="rgba(10 ,38 ,61, 0.9)"
      >
        <div class="message-drawer-header">
          <div :class="['header-left', leavingTop ? 'header-left-leaving-top' : '']"
               :title="leavingTop ? '返回顶部': '消息中心'"
               @click="leavingTop && titleClick()"
          >
            消息中心 {{ newMsgNum ? `(${newMsgNum})` : '' }}
          </div>
          <div class="header-right">
            <span @click="moreMsg" title="更多消息">更多消息</span>
          </div>
        </div>
        <div class="message-drawer-content">
          <el-empty
            description="无新消息通知，点击“更多消息”查看历史消息"
            v-if="!msgData.length"
          />
          <ul v-else
              class="message-list"
              v-infinite-scroll="scrollLoad"
              :infinite-scroll-immediate="false"
              :infinite-scroll-disabled="isFinished"
              :infinite-scroll-distance="10"
              ref="messageList"
              @scroll="e => leavingTop = !!e.target.scrollTop"
          >
            <li v-for="(item,index) in msgData"
                :key="index"
                :class="[
                            'message-box',
                             item.type  ? 'old-message-box' : 'new-message-box',
                             rowInfo.id === item.id ? 'message-box-active' : ''
                           ]"
                ref="messageBox"
            >
              <div class="message-left">
                <span>{{ index + 1 }}.</span>
              </div>
              <div class="message-content"
                   title="查看详情"
                   @click="showDialog('isShowDetail',item)"
              >
                <div :class="['message-type']">
                  <img
                    :src="require(`@/assets/img/publicLayout/${item.iconPath}.png`)"
                    alt=""
                  />
                  <span>最新消息</span>
                </div>
                <div class="message-title" :title="item.subject">{{ item.subject || '-' }}</div>
                <div class="message-source-time" :title="item.createTime">
                  {{ item.owner }}&nbsp; · &nbsp;{{ item.time }}
                </div>
              </div>
            </li>
            <li class="no-more-data" v-if="isFinished">没有更多新消息了..</li>
          </ul>
        </div>
      </div>
    </el-drawer>

    <!--  详情弹层  -->
    <detail-dialog
      :isShowDetail.sync="isShowDetail"
      width="40%"
      title="消息通知"
      :rowInfo="rowInfo"
      @close-dialog="closeDetail"
    />
  </div>
</template>
<script>

import {messageReceiver} from '@/api/MessageReminder'
import DetailDialog from '@/views/MessageReminder/components/DetailDialog.vue'
import moment from 'moment'

export default {
  name: 'MessageDrawer',
  components: {DetailDialog},
  props: {
    showMsgDrawer: {
      default: false,
      type: Boolean
    },
    newMsgNum: {
      default: 0,
      type: Number
    }
  },
  data() {
    return {
      queryParams: {
        page: 1,
        pageSize: 20,
        total: 0,
        receiveTime: '1'
      },
      msgData: [],
      loading: false, // 加载中
      isFinished: false, // 是否加载完成
      leavingTop: false, // 离开顶部
      rowInfo: {}, // 消息点击行信息
      isShowDetail: false // 展示详情弹层
    }
  },
  computed: {
    isShow: {
      get() {
        return this.showMsgDrawer
      },
      set(val) {
        this.$emit('update:showMsgDrawer', val)
      }
    },
    // 加工为后端需要的请求格式
    computedQuery() {
      const querys = [
        {operation: 'EQUAL', property: 'receiveTime', relation: 'AND', group: 'filterTime'},
        {operation: 'LIKE', property: 'subject', relation: 'OR', group: 'quick'}
      ]
      const {pageSize, page, ...item} = this.queryParams
      return {
        pageBean: {pageSize, page},
        querys: querys.flatMap(i => {
          const value = item[i.property]
          if (Array.isArray(value) && !value.length) return []
          if (value === '') return []
          return {group: 'main', ...i, value}
        })
        // sorter: this.sorter.filter(i => i.direction !== '')
      }
    }
  },
  created() {
    this.getMsgData()
  },
  methods: {
    // 获取消息
    async getMsgData(callback) {
      this.loading = true
      const {data: {rows, total}} = await messageReceiver(this.computedQuery)
      this.$emit('update:newMsgNum', total) // 更新消息数量
      this.queryParams.total = total
      const {pageSize, page} = this.queryParams
      if (total <= pageSize * page) this.isFinished = true // 数据加载完成

      // 新数据合并旧数据
      this.msgData = this.msgData.concat(rows.map(i => {
        let time = i.createTime
        const dayDiff = moment().diff(moment(time, 'YYYY-MM-DD'), 'days')

        /**
         * @param {String} formatStr 格式化字符串
         * @return {String} 格式化后的时间
         * */
        const timeMoment = formatStr => moment(time).format(formatStr)

        /*
        * 时间格式化逻辑，判断条件从上到下依次为：
        *   是否为当天 => 时分秒
        *   是否为昨天 => 昨天 时分秒
        *   是否为本周 => 星期 时分秒
        *   是否为本年 => 月日 时分秒
        *   未进入以上条件分支语句中(非本年时间) => 年月日 时分秒
        * */
        if (dayDiff === 0) {
          time = timeMoment('HH:mm:ss')
        } else if (dayDiff === 1) {
          time = `昨天 ${timeMoment('HH:mm:ss')}`
        } else if (moment().weekday(0).isBefore(moment(time))) {
          time = `${timeMoment('dddd HH:mm:ss')}`
        } else if (!moment().diff(moment(time, 'YYYY'), 'years')) {
          time = `${timeMoment('MM-DD HH:mm:ss')}`
        }

        return {
          ...i,
          iconPath: `${i.receiveTime ? 'historical-' : ''}msg-icon`,
          type: !!i.receiveTime,
          time
        }
      }))
      this.loading = false
      callback && callback()
    },

    // 标题点击
    titleClick() {
      if (
        this.$refs.messageBox
        && Array.isArray(this.$refs.messageBox)
        && this.$refs.messageBox.length
      ) {
        const [firstDom] = this.$refs.messageBox
        firstDom.scrollIntoView({behavior: 'smooth', block: 'center'})
      }
    },

    // 更多信息
    moreMsg() {
      this.$router.push('/platLayout/messageReminder')
      this.isShow = false
    },

    // 触底触发
    scrollLoad() {
      if (this.loading) return
      this.queryParams.page += 1
      this.getMsgData()
    },

    // 关闭抽屉后触发
    close() {
      Object.assign(this.$data, this.$options.data())
      this.getMsgData(_ => {
        this.$refs.messageList && this.$refs.messageList.scrollTo(0, 0)
      })
    },

    // 展示弹层
    showDialog(dialog, rowInfo = {}) {
      this[dialog] = true
      this.rowInfo = rowInfo // 保存点击行信息
    },

    //  关闭详情弹层
    closeDetail() {
      if (!this.rowInfo.type) {
        this.rowInfo.type = true
        this.$emit('update:newMsgNum', this.newMsgNum - 1)
      }
      this.rowInfo = {}
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/css/element-variables";

.message-drawer {

  ::v-deep .el-drawer__wrapper {


    .el-drawer__container {

      .el-drawer {
        height: calc(100% - 60px);
        top: 60px;

        .el-drawer__body {
          overflow: hidden;
          height: 100%;

          .message-drawer-container {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;

            .message-drawer-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              height: 60px;
              padding: 0 20px;
              box-sizing: border-box;
              user-select: none;
              flex-shrink: 0;
              background: $--system-module-color1;


              .header-left {
                font-size: 18px;
                font-family: Microsoft YaHei, Microsoft YaHei, serif;
                color: $--color-white;
                font-weight: 600;

                &.header-left-leaving-top {
                  cursor: pointer;
                }
              }

              .header-right {
                span {
                  font-size: 14px;
                  font-family: Microsoft YaHei, Microsoft YaHei, serif;
                  color: $--color-primary;
                  cursor: pointer;
                }
              }
            }

            .message-drawer-content {
              width: 100%;
              display: flex;
              height: calc(100% - 60px);
              flex: 1;
              padding: 1px;

              .message-list {
                width: 100%;
                height: 100%;
                overflow-x: hidden;
                overflow-y: auto;

                &::-webkit-scrollbar {
                  /*滚动条整体样式*/
                  width: 7px !important; /*高宽分别对应横竖滚动条的尺寸*/
                  height: 1px;
                  border-radius: 7px !important;
                  background-color: #ededed !important;
                }

                &::-webkit-scrollbar-thumb {
                  /*滚动条里面小方块*/
                  border-radius: 7px !important;
                  background-color: rgba(17, 80, 160, 0.7);
                  background-image: -webkit-linear-gradient(
                          45deg,
                          rgba(255, 255, 255, 0.3) 25%,
                          transparent 25%,
                          transparent 50%,
                          rgba(255, 255, 255, 0.3) 50%,
                          rgba(255, 255, 255, 0.3) 75%,
                          transparent 75%,
                          transparent
                  );
                }

                &::-webkit-scrollbar-track {
                  /*滚动条里面轨道*/
                  //box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
                  border-radius: 7px;
                  background-color: #fff !important;
                }

                .message-box {
                  display: flex;
                  width: 100%;
                  box-sizing: border-box;
                  padding: 15px 20px 12px;
                  border-bottom: 1px solid $--system-disabled-bgColor;
                  transition: all 0.1s;
                  $title-color: var(--title-color);

                  @mixin hover-active {
                    background-color: $--system-box-color5;
                    box-shadow: rgba($--system-box-color4, 0.15) 0 3px 3px 0;
                    transition: all 0.2s;
                    border-bottom: 1px solid transparent;

                    .message-content {

                      .message-source-time {
                        text-decoration: underline;
                      }
                    }
                  }

                  &:hover {
                    @include hover-active;
                  }

                  &:last-child {
                    border: 0;
                  }

                  &.new-message-box {
                    --title-color: #{$--color-error};
                  }

                  &.old-message-box {
                    --title-color: #{$--system-table-text-color};
                  }

                  &.message-box-active {
                    @include hover-active;
                  }


                  .message-left {
                    min-width: 40px;
                    user-select: none;

                    span {
                      font-size: 16px;
                      color: $--system-table-text-color;
                      height: 16px;
                      line-height: 16px;
                    }

                  }

                  .message-content {
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    row-gap: 5px;
                    font-size: 14px;
                    cursor: pointer;

                    .message-type {
                      display: flex;
                      column-gap: 8px;
                      align-items: center;
                      margin-bottom: 8px;

                      img {
                        width: 12px;
                        height: 14px;
                        vertical-align: bottom;
                      }

                      span {
                        font-size: 14px;
                        color: $title-color;
                        display: inline-block;
                        height: 16px;
                        line-height: 16px;
                        transition: all 0.2s;
                      }
                    }

                    .message-title {
                      font-size: 13.5px;
                      color: $--system-table-text-color;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      -webkit-line-clamp: 2;
                      display: -webkit-box;
                      -webkit-box-orient: vertical;
                      line-height: 20px;
                    }

                    .message-source-time {
                      font-size: 13.5px;
                      color: $--system-table-text-color;
                      transition: all 0.2s;
                    }
                  }
                }

                .no-more-data {
                  width: 100%;
                  height: 80px;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  font-size: 14px;
                  pointer-events: none;
                  user-select: none;
                  color: $--color-text-placeholder;
                }
              }
            }
          }
        }
      }
    }
  }

  ::v-deep .v-modal {
    height: calc(100% - 60px);
    top: 60px;
    opacity: 0.5;
  }

  ::v-deep .el-empty {
    width: 100%;
    padding: 0 0 40% 0;

    .el-empty__description {
      margin-top: 30px;

      p {
        font-size: 14px;
        font-family: Microsoft YaHei, Microsoft YaHei, serif;
        user-select: none;
      }
    }
  }
}
</style>
