<template>
  <div class="flex flex-col">
    <div class=" h-260px bg-squareBanner bg-center bg-cover bg-transparent  bg-opacity-10 relative" ref="topBox">
      <div class="flex flex-col justify-center items-center py-12 pointer-events-none" ref="textBox">
        <img src="@/assets/squareBanner-text.png" alt="">
      </div>
      <div class='w-full  absolute bottom-3 '>
        <div class=' w-11/12 mx-auto h-10 py-3  text-white'>
          <app-search @search="search"></app-search>
        </div>
      </div>
    </div>
    <div class="list-contianer w-11/12 mx-auto"  >
      <div class="sub-title flex items-center justify-between py-5">
        <div>投票列表</div>
        <div @click="doFilter"><app-icon type="icon-shaixuan" customize color=' text-white' ></app-icon></div>
      </div>
      <div class="list w-full" @scroll="scrollStart" ref="botBox">
        <div class="wrap" v-if="lists.length > 0">
          <div v-for="(item, index) in lists" :key="index" @click="goPage(item)">
            <app-card v-if="item.type === 1" class="mb-2" :cardContent="item" :blockTime="blockTime" :blockHeight="blockHeight"  />
          </div>
          <div class='h-1'></div>
        </div>
        <div v-else class="w-full h-40 flex items-center justify-center">
          <img class="w-32 h-32" src="@/assets/home/empty.png" alt="">
        </div>
      </div>
    </div>
    <app-filter ref="filter" :show="showfilter" @filterList="filterList" @cancel="showhidden" />
  </div>
</template>

<script lang="ts">

import Vue from "vue";
import { service } from '@/service/index'
import {TimelineLite, Power2, CSSPlugin, gsap} from 'gsap'
import BScroll from 'better-scroll'
gsap.registerPlugin(CSSPlugin)
/// <reference path="tween.d.ts"/>

export default Vue.extend({
  name: "Square",
  data() {
    return {
      anima:null as any,
      scrollArr:[] as any[],
      showfilter: false,
      lists: [] as any[],
      copyList: [] as any[],
      blockHeight: '',
      blockTime: 0,
      bscroll: null as any,
      page: 1
    };
  },
  mounted(){
    this.getBlockHeight()
    this.getVoteList()
    this.initAnima()
  },
  components:{
    'app-icon':()=>import('@/components/common/Icon.vue'),
    'app-card':()=>import('@/components/Card.vue'),
    'app-filter':()=>import('@/components/square/Filter.vue'),
    'app-search':()=>import('@/components/common/Search.vue')
  },
  methods:{
    getVoteList() {
      service.voteList({
        execer: 'user.p.szhtest.rankvote',
        funcName: 'GetRankVoteList',
        payload: { addr: '', count: -1, direction: 0, height: 0, index: 0 }
      }).then(res => {
        let lists = res.data.result && res.data.result.list || []
        lists = lists.filter((item: any) => item.type === 1)
        this.lists = lists
        this.copyList = lists
        // this.initScroll()
      })
    },
    getBlockHeight() {
      service.getHeight().then(res => {
        this.blockHeight = res.data.result.mainHeight
        this.blockTime = +res.data.result.mainBlockTime
      })
    },
    initScroll() {
      this.$nextTick(() => {
        if (!this.bscroll) {
          this.bscroll = new BScroll(this.$refs.botBox, {
            click: true,
            scrollY: true,
            observeDOM: true,
            pullUpLoad: {
              threshold: 80 // 当上拉到超过底部 70px 时
            },
            pullDownRefresh: {
              threshold: 70,
              stop: 40,
            },
          });
          this.bscroll.on("scroll", (obj: any) => {
            this.scrollStart(obj)
          });
          this.bscroll.on("pullingUp", () => {
            console.log("pullingUp")
            this.page++
            this.getVoteList()
            // this.bscroll.finishPullUp();
          });
          this.bscroll.on("pullingDown", () => {
            console.log("pullingDown");
            this.getVoteList()
          })
        } else {
          this.complete();
        }
      });
    },
    complete() {
      if(this.bscroll){
        this.bscroll.finishPullUp();
        this.bscroll.refresh();
        this.bscroll.finishPullDown();
      }
    },
    initAnima() {
      if (this.anima) this.anima = null
      const {topBox,botBox,textBox} = this.$refs
      this.anima = new TimelineLite()
      this.anima.to(botBox,0.1,{css:{height:"calc(100vh - 190px)"},ease:Power2.easeInOut})
      this.anima.to(textBox,0.1,{opacity:0,ease:Power2.easeInOut})
      this.anima.to(topBox,0.6,{css:{height:"50px"},ease:Power2.easeInOut,delay:0.1},'>-0.3')
      this.anima.pause()
    },
    scrollStart(e:any){
      // let poisition = e.y
      // this.scrollArr.push(poisition)
      // let l = this.scrollArr.slice(-2)
      // if(Math.abs(e.y) > 320 && l[0]>l[1]){
      // // 设置高度检测，当小于回滚高度时跳出
      // // if (e.target.scrollHeight - 320 < window.innerHeight) return
      //   this.anima.play()
      // }else if(Math.abs(e.y) <= 320 && l[0]<l[1]){
      //   this.anima.reverse()
      // }
      let poisition = e.target.scrollTop
      this.scrollArr.push(poisition)
      let l = this.scrollArr.slice(-2)
      if(e.target.scrollTop > 320 && l[0]<l[1]){
      // 设置高度检测，当小于回滚高度时跳出
      if (e.target.scrollHeight - 320 < window.innerHeight) return
        this.anima.play()
      }else if(e.target.scrollTop <= 320 && l[0]>l[1]){
        this.anima.reverse()
      }
    },
    search(v: string) {
      const str = v ? v : ''
      if (str) {
        this.filterList(str)
      } else {
        this.getVoteList()
      }
    },
    doFilter(){
      this.showfilter = true
    },
    showhidden(v: boolean) {
      this.showfilter = !v
    },
    filterList(v: object|string) {
      this.showfilter = false
      let lists = JSON.parse(JSON.stringify(this.copyList))
      this.lists = []
      if (typeof v === 'string') {
        const l1 = lists.filter((item: any) => item.name.indexOf(v) > -1)
        const l2 = lists.filter((item: any) => item.ID === v)
        const l = [...l1, ...l2]
        this.$nextTick(() => {
          this.lists = l
        })
      } else {
        const o = v as any
        if (o.type === 2) {
          lists = lists.filter((item: any) => item.creator === this.$store.state.app.address)
        } else if (o.type === 3) {
          lists = lists.filter((item: any) => item.creator !== this.$store.state.app.address)
        }
        if (o.status !== 0) {
          lists = lists.filter((item: any) => item.status === o.status)
        }
        this.$nextTick(() => {
          this.lists = lists
        })
      }
    },
    goPage(o: any) {
      const type = o.status
      if (type <= 2) {
        this.goVote(o.ID)
      } else {
        this.goDetails(o.ID)
      }
    },
    goVote(id: string) {
      this.$router.push({path: '/Square/SquareVote', query: {voteID: id}})
    },
    goDetails(id: string) {
      this.$router.push({path: '/Square/SquareDetails', query: {voteID: id}})
    },
  },
  // activated() {
  //   this.getBlockHeight()
  //   this.getVoteList()
  //   this.initAnima()
  // },
  watch: {
    $route: {
      immediate: true,
      handler(n) {
        if (n.path !== '/Square') return
        this.lists = []
        this.getBlockHeight()
        this.getVoteList();
        if (this.$refs.filter) {
          (this.$refs.filter as any).clear()
        }
      }
    }
  }
});
</script>

<style scoped>
  .wrap {
    min-height: calc(100vh - 392px);
  }
</style>

