<template>
  <div id="wrapper">
    <div id="scroller">
      <div id="pullDown">
        <span class="pullDownIcon" style="display: none"></span><span class="pullDownLabel">释放刷新</span>
      </div>
      <ul id="thelist">
        <li v-for="(item, index) in items" :data-index="index" class="message-item"
        :key="index">
          <div class="message-item-title">{{item.title}}</div>
          <div class="message-desc">{{item.content_text}}</div>
          <div class="message-desc">{{item.push_time | fomatDate}}</div>
        </li>
      </ul>
      <div id="pullUp">
        <span class="pullUpIcon" style="display: none"></span><span class="pullUpLabel">上拉加载更多</span>
      </div>
    </div>
  </div>
</template>

<script>
import {Observable} from 'rxjs'
import {throttleTime, switchMap, filter} from 'rxjs/operators'
require('@/lib/iscroll/iscroll')
const IScroll = window.iScroll
let pullDownEl, pullDownOffset, pullUpEl, pullUpOffset
export default {
  name: 'message',
  subscriptions () {},
  data () {
    return {
      items: [],
      myScroll: null,
      pageNo: 0,
      isLastPage: false,
      eventType: '',
      eventMouseStarEl: null,
      eventMouseEndEl: null
    }
  },
  components: {},
  created () {
    this.getListDataFromNet(1, 10)
  },

  watch: {},
  computed: {},
  mounted () {
    this.$nextTick(() => {
      this.bindMessageTapEvent()
      setTimeout(() => {
        this.initSlimscroll()
      },100)
    })
  },
  methods: {
    async getListDataFromNet () {
      if (this.isLastPage) {
        this.myScroll.refresh()
        return false
      }
      this.pageNo++
      // 延时一秒,模拟联网
      const res = await this.axios.get(
        'http://rap2api.taobao.org/app/mock/115626/store/notice!getStoreNoticeListByPageAction.do',
        {
          params: {
            pageNo: this.pageNo,
            pageSize: 20,
            push_state: 2
          }
        }
      )
      if (res.data.code === 0) {
        const resData = res.data.data
        const length = this.items.length
        if (length <= resData.totalCount) {
          this.items = this.items.concat(resData.dataList)
        } else {
          this.isLastPage = true
        }
      }
      this.loaded()
    },
    loaded () {
      pullDownEl = document.getElementById('pullDown')
      pullDownOffset = pullDownEl.offsetHeight
      pullUpEl = document.getElementById('pullUp')
      pullUpOffset = pullUpEl.offsetHeight
      this.myScroll = new IScroll('wrapper', {
        probeType: 2, // probeType：1对性能没有影响。在滚动事件被触发时，滚动轴是不是忙着做它的东西。probeType：2总执行滚动，除了势头，反弹过程中的事件。这类似于原生的onscroll事件。probeType：3发出的滚动事件与到的像素精度。注意，滚动被迫requestAnimationFrame（即：useTransition：假）。
        scrollbars: true, // 有滚动条
        mouseWheel: true, // 允许滑轮滚动
        fadeScrollbars: true, // 滚动时显示滚动条，默认影藏，并且是淡出淡入效果
        bounce: true, // 边界反弹
        interactiveScrollbars: true, // 滚动条可以拖动
        shrinkScrollbars: 'scale', // 当滚动边界之外的滚动条是由少量的收缩。'clip' or 'scale'.
        click: true, // 允许点击事件
        tap: true, // 允许tap事件
        keyBindings: true, // 允许使用按键控制
        momentum: true, // 允许有惯性滑动,
        scrollbarClass: 'myScrollbar' /* 重要样式 */,
        useTransition: true /* 此属性不知用意，本人从true改为false */,
        topOffset: pullDownOffset,
        onRefresh: () => {
          this.$nextTick(() => {
            if (pullDownEl.className.match('loading')) {
              pullDownEl.className = ''
              pullDownEl.querySelector('.pullDownLabel').innerHTML = '释放刷新'
            } else if (pullUpEl.className.match('loading')) {
              pullUpEl.className = ''
              pullUpEl.querySelector('.pullUpLabel').innerHTML = this.isLastPage
                ? '没有更多数据'
                : '释放加载'
            }

          })
        },
        onScrollMove: function () {
          if (this.y > 5 && !pullDownEl.className.match('flip')) {
            pullDownEl.className = 'flip'
            pullDownEl.querySelector('.pullDownLabel').innerHTML = '释放加载'
            this.minScrollY = 0
          } else if (this.y < 5 && pullDownEl.className.match('flip')) {
            pullDownEl.className = ''
            pullDownEl.querySelector('.pullDownLabel').innerHTML = '释放刷新'
            this.minScrollY = -pullDownOffset
          } else if (
            this.y < this.maxScrollY - 5 &&
            !pullUpEl.className.match('flip')
          ) {
            pullUpEl.className = 'flip'
            pullUpEl.querySelector('.pullUpLabel').innerHTML = '释放加载'
            this.maxScrollY = this.maxScrollY
          } else if (
            this.y > this.maxScrollY + 5 &&
            pullUpEl.className.match('flip')
          ) {
            pullUpEl.className = ''
            pullUpEl.querySelector('.pullUpLabel').innerHTML = '释放刷新'
            this.maxScrollY = pullUpOffset
          }
        },
        onScrollEnd: () => {
          this.$nextTick(() => {
            if (pullDownEl.className.match('flip')) {
              pullDownEl.className = 'loading'
              pullDownEl.querySelector('.pullDownLabel').innerHTML =
                '加载中...'
              this.pullDownAction()
            } else if (pullUpEl.className.match('flip')) {
              pullUpEl.className = 'loading'
              pullUpEl.querySelector('.pullUpLabel').innerHTML = '加载中...'
              this.pullUpAction()
            }
          })
        }
      })
      document.addEventListener(
        'touchmove',
        function (e) {
          e.preventDefault()
        },
        false
      )
    },
    handlerKeydown(event) {
      this.eventMouseStarEl = event.target
      this.eventType = ''
    },
    bindMessageTapEvent () {
      const clickEl$ = Observable.create(observer => {
        $('body').on('click','.message-item',(event) => {
          // const item = $(event.currentTarget)
          observer.next(event)
        })
      })
      const mousemoveEl$ = Observable.create(observer => {
        $('body').on('mousemove','.message-item',(event) => {
          // const item = $(event.currentTarget)
          observer.next(event)
        })
      })

      mousemoveEl$.pipe(
        switchMap(ev => clickEl$),
        throttleTime(300),
        filter(ev => ev.type === 'click')
      )
      .subscribe(event => {
        const index = $(event.currentTarget).data('index')
        const item = this.items[index]
        this.openMessageContent(item)
      },(ev) => {
        console.log(ev)
      })
    },
    handlerKeypress(event) {
      this.eventMouseEndEl = event.target
      console.log(event)
      if (this.eventMouseStarEl && this.eventMouseStarEl === this.eventMouseEndEl) {
        this.eventType = 'click'
      } else {
        this.eventType = 'mousemove'
      }
      // this.eventMouseStarEl = this.eventMouseEndEl = null
    },
    pullDownAction () {
      this.items = []
      this.pageNo = 0
      this.isLastPage = false
      this.getListDataFromNet()
    },

    pullUpAction () {
      this.getListDataFromNet()
    },

    initSlimscroll () {
      $('#wrapper').slimScroll({
        width: '100%', // 可滚动区域宽度
        height: '700px', // 可滚动区域高度
        size: '10px', // 滚动条宽度，即组件宽度
        color: '#000', // 滚动条颜色
        position: 'right', // 组件位置：left/right
        distance: '0px', // 组件与侧边之间的距离
        start: 'top', // 默认滚动位置：top/bottom
        opacity: 0.4, // 滚动条透明度
        alwaysVisible: true, // 是否 始终显示组件
        disableFadeOut: false, // 是否 鼠标经过可滚动区域时显示组件，离开时隐藏组件
        railVisible: true, // 是否 显示轨道
        railColor: '#333', // 轨道颜色
        railOpacity: 0.2, // 轨道透明度
        railDraggable: true, // 是否 滚动条可拖动
        railClass: 'slimScrollRail', // 轨道div类名
        barClass: 'slimScrollBar', // 滚动条div类名
        wrapperClass: 'slimScrollDiv', // 外包div类名
        allowPageScroll: true, // 是否 使用滚轮到达顶端/底端时，滚动窗口
        wheelStep: 20, // 滚轮滚动量
        touchScrollStep: 200, // 滚动量当用户使用手势
        borderRadius: '7px', // 滚动条圆角
        railBorderRadius: '7px' // 轨道圆角
      })
    },

    openMessageContent (item) {
      this.$alert(`<div><session class="model-body">${item.content}</session></div>`, '', {
        dangerouslyUseHTMLString: true,
        customClass: 'message-panel',
        confirmButtonText: '知道了',
        title:item.title,
        callback:(action) => {
          this.axios.post('http://testcenter.bigaka.net/b/store/notice!addNoticeUserRelationAction.do', {
            params:{
              "userId":"3956",
              "noticeId":"68"
            }
          })
        }
      })
      this.$nextTick(() => {
        $(".el-message-box__message")
          .slimscroll({
            height: '530px',
            distance: '10px',
            alwaysVisible: false,
            railVisible: true,
            railColor: '#e1e1e1',
            railOpacity: 1,
            size: '6px',
            color: '#77c2f7',
            opacity: 1
          })
      })
    }
  }
}
</script>
<style>
.message-panel .el-message-box__title {
  min-height: 16.428571429px;
  padding: 15px;
  border-bottom: 1px solid #e5e5e5;
}

.model-body {
  position: relative;
  overflow: hidden;
  width: auto;
  height: 500px;
}
</style>

<style scoped>
#wrapper {
  width: 100%;
  position: absolute;
  top: 18px;
  bottom: 0;
  overflow: hidden;
}
#pullDown,
#pullUp {
  border-bottom: none;
  text-align: center;
  height: 40px;
  box-sizing: border-box;
  line-height: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

#pullUp {
  border-top: solid 1px #d7d7d7;
  text-align: center;
}
</style>

<style lang="scss" scoped>
.message-item {
  border-top: 1px dashed #ddd;
  padding: 5px 20px;
  cursor: pointer;
  &:first-child {
    border-top: none;
  }
}

.message-item-title {
  font-size: 15px;
}

.message-desc {
  font-size: 13px;
}
</style>
