<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"
        @keydown="handlerKeydown($event)"
        @keypress="handlerKeypress($event)"
      >
        <li v-for="(item, index) in items" class="message-item"
        :key="index" @click="openMessageContent(item,$event)">
          <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>
require('@/lib/iscroll/iscroll')
const IScroll = window.iScroll
let pullDownEl, pullDownOffset, pullUpEl, pullUpOffset
export default {
  name: 'message',
  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.loaded()
    })
  },
  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.myScroll.refresh()
    },
    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 = ''
    },
    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()
    },

    openMessageContent (item) {
      if (this.eventType === 'click') {
        this.$alert(`${item.content}`, '', {
          dangerouslyUseHTMLString: true,
          customClass: 'message-panel'
        })
      }

      // this.$alert(`${item.content}`, '', {
      //   dangerouslyUseHTMLString: true,
      //   customClass: 'message-panel'
      // })
    }
  }
}
</script>

<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>
