<template>
  <div class="works con">
    <div class="back-top" @click="onClickBackTop" v-show="isShowBackTopBtn">
      <i class="iconfont icon-top"></i>
    </div>
    <div class="tab">
      <span>我的作品 {{workTotalNum !== undefined ? `(${workTotalNum})`:''}}</span>
      <div class="tab-r">
         <div class="filter">
          <div :class="{active: isFilterFocus}" @focusin="onFilterFocus" @focusout="onFilterBlur">
            <i class="iconfont iconworks_search search"></i>
            <input
              type="text"
              placeholder="搜索作品"
              v-model="searchKey"
            >
            <i v-if="searchKey" @click="searchKey=''" class="iconfont icontoast_red del"></i>
          </div>
        </div>
      </div>
    </div>
    <div class="mask" v-show="isShowMask"></div>
    <ul
      class="w-list"
      v-if="!(list.length === 0 && !hasMoreData)"
      v-infinite-scroll="requestMoreData"
      :infinite-scroll-disabled="!hasMoreData || isRequestingMoreData"
      infinite-scroll-distance="315"
      ref="w-list-ref"
      @scroll.self="onWorkListScroll"
    >
      <li class="add-work" @click="add">
        <div class="add-con">
          <div>
            <i class="iconfont icon_plus"></i>
          </div>
          <span>创建作品</span>
        </div>
      </li>
      <li v-for="(item,i) in list" :key="i">
        <div class="li-hover">
          <span class="lipreview" @click="handlePreview(item)">预览</span>
          <ul class="oper">
            <li class="comfirmhover" @click="edit(item)"><i class="iconfont icon-works_editor"></i>编辑</li>
            <li class="comfirmhover" @click="openShare(item)"><i class="iconfont icon-works_share"></i>分享</li>
            <li class="cancelhover" @click="del(item, i)"><i class="iconfont icon-works_delete"></i>删除</li>
          </ul>
        </div>
        <div class="img" @click="handlePreview(item)">
          <img class="real" :src="item.icon||$thumb" alt="" />
        </div>
        <div class="li-info">
          <div>
            <span class="shenglve tttttt" :title="item.name||'无标题'">{{item.name||'无标题'}}</span>
          </div>
          <div>
            <span>{{item.createTime.split(' ')[0]}}</span>
            <div :title="item.visit">
              <i class="iconfont iconworks_look"></i>{{item.visit>10000?'1w+':item.visit}}
            </div>
          </div>
        </div>
      </li>
    </ul>
    <div class="nodata" v-if="list.length == 0 && !hasMoreData && lastestUsedSearchKey">
      <img :src="$noresult" alt="" />
      <span>未搜索到结果~</span>
    </div>
    <div class="nodata" v-if="list.length == 0 && !hasMoreData && !lastestUsedSearchKey">
      <img :src="config.empty" alt="" />
      <span>您还没有作品，请先创建作品~</span>
      <button @click="add" class="upload-btn-in-table">创建作品</button>
    </div>
    <share :show='showShare' :item="shareItem" @close="showShare=false"></share>
    <preview
      v-if="showItem"
      :name="showItem.name"
      :show="showPreview"
      :ifr="`./show.html?id=${showItem.id}`"
      @close="showPreview = false"
    />
  </div>
</template>

<script>
import share from '../popup/share'
import preview from "@/components/preview";
import config from "@/config";
import { debounce } from "@/utils/other.js"

import {
  addWorks,
  getWorksList,
  delWorks,
  getPanoInfo
} from "@/api";

export default {
  components:{
    share,
    preview
  },
  data(){
    return {
      config,
      
      list:[],
      workTotalNum: undefined,
      hasMoreData: true,
      isRequestingMoreData: false,
      
      searchKey:'',
      // 因为searchKey的变化经过debounce、异步请求的延时，才会反映到数据列表的变化上，所以是否显示、显示哪种无数据提示，也要等到数据列表变化后，根据数据列表是否为空，以及引发本次变化的那个searchKey瞬时值来决定。本变量就是用来保存那个瞬时值。
      lastestUsedSearchKey: '',
      isFilterFocus: false,
      
      showShare:false,
      showPreview:false,
      showItem:'',
      shareItem:'',

      isBackingTop: false,
      isShowBackTopBtn: false,

      isShowMask: false,
    }
  },
  mounted(){
  },
  watch:{
    searchKey: {
      handler: function () {
        console.log(111);
        this.refreshListDebounced()
      },
      immediate: false,
    },
  },
  methods:{
    onFilterFocus() {
      this.isFilterFocus = true
    },
    onFilterBlur() {
      this.isFilterFocus = false
    },
    refreshListDebounced: debounce(function() {
      this.list = []
      this.isRequestingMoreData = false
      this.hasMoreData = true
      this.requestMoreData()
    }, 700, false),
    openShare(data){
      getPanoInfo(data.id, (data) => {
        if (data.scenes.length<=0) {
          return this.$msg.message("链接未生成，请编辑作品添加素材");
        }
        this.showShare = true
        this.shareItem = data
      })
    },
    
    handlePreview(item){
      getPanoInfo(item.id, (data) => {
        if (data.scenes.length<=0) {
          return this.$msg.message("链接未生成，请编辑作品添加素材");
        }
        this.showItem = {
          ...item,
          ...data
        }
        this.showPreview=true
      })
    },
    add(){
      addWorks({},(data)=>{
        window.open(`./edit.html?id=${data.data.id}`)
      })
    },
    edit(item){
        window.open(`./edit.html?id=${item.id}`)
    },
    del(item, index){
      this.$confirm({
          title:'删除作品',
          content: "确定要删除作品吗？",
          ok: () => {
              delWorks(item.id,()=>{
                this.$msg.success("删除成功");
                this.isRequestingMoreData = true
                const lastestUsedSearchKey = this.searchKey
                getWorksList(
                  {
                    pageNum: this.list.length + 1,
                    pageSize: 1,
                    searchKey: this.searchKey
                  },
                  (data) => {
                    this.list.splice(index, 1)
                    this.list = this.list.concat(data.data.list)
                    if (this.list.length === data.data.total) {
                      this.hasMoreData = false
                    }
                    this.isRequestingMoreData = false
                    this.lastestUsedSearchKey = lastestUsedSearchKey
                    if (!lastestUsedSearchKey) {
                      this.workTotalNum = data.data.total
                    }
                    // TODO: 这是干啥呢？
                    this.$nextTick(()=>{
                      this.$bus.emit('refreshTips')
                    })
                  },
                  () => {
                    this.lastestUsedSearchKey = lastestUsedSearchKey
                    this.isRequestingMoreData = false
                  }
                )
              });
          },
      });
    },
    requestMoreData() {
      this.isRequestingMoreData = true
      const lastestUsedSearchKey = this.searchKey
      getWorksList(
        {
          pageNum: Math.floor(this.list.length / config.PAGE_SIZE) + 1,
          pageSize: config.PAGE_SIZE,
          searchKey: this.searchKey,
        },
        (data) => {
            this.list = this.list.concat(data.data.list)
          if (this.list.length === data.data.total) {
            this.hasMoreData = false
          }
          this.isRequestingMoreData = false
          this.lastestUsedSearchKey = lastestUsedSearchKey
          if (!lastestUsedSearchKey) {
            this.workTotalNum = data.data.total
          }
          // TODO: 这是干啥呢？
          this.$nextTick(()=>{
            this.$bus.emit('refreshTips')
          })
        },
        () => {
          this.isRequestingMoreData = false
          this.lastestUsedSearchKey = lastestUsedSearchKey
        }
      );
    },
    onClickBackTop() {
      if (this.isBackingTop) {
        return
      }
      this.isBackingTop = true

      const startTime = Date.now()
      const totalScroll = this.$refs['w-list-ref'].scrollTop
      const fn = () => {
        if (this.$refs['w-list-ref'].scrollTop === 0) {
          this.isBackingTop = false
          return
        } 

        const nowTime = Date.now()
        const assumeScrollTop = totalScroll - (nowTime - startTime) * totalScroll / 500
        this.$refs['w-list-ref'].scrollTop = assumeScrollTop > 0 ? assumeScrollTop : 0
        requestAnimationFrame(fn)
      }
      requestAnimationFrame(fn)
    },
    onWorkListScroll(e) {
      if (e.target.scrollTop >= 30) {
        !this.isShowMask && (this.isShowMask = true)
      } else {
        this.isShowMask && (this.isShowMask = false)
      }
      
      if (e.target.scrollTop >= 600) {
        this.isShowBackTopBtn = true
      } else {
        this.isShowBackTopBtn = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.works{
  width: 100%;
  flex-direction: column;
  position: relative;
  .back-top {
    position: absolute;
    right: -80px;
    bottom: 30px;
    width: 60px;
    height: 60px;
    border-radius: 8px;
    background-color: #fff;
    z-index: 1;
    color: #C8C9CC;
    &:hover {
      color: #323233;
    }
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    i {
      font-size: 20px;
    }
  }
  .tab{
    flex: 0 0 auto;
    width: 100%;
    display: flex;
    background: #fff;
    justify-content: space-between;
    align-items: center;
    padding: 20px 30px;
    >span{
      font-size: 18px;
      font-weight: bold;
    }
    .tab-r{
      align-items: center;
      display: flex;
      .ui-button{
        margin-right: 20px;
      }
    }
  }
  .mask {
    position: absolute;
    width: 100%;
    top: 210px;
    height: 30px;
    background: linear-gradient(rgb(239, 242, 244), rgba(255, 255, 255, 0));
    z-index: 1;
    pointer-events: none;
  }
  .w-list{
    flex: 1 1 auto;
    overflow: auto;
    width: 100%;
    margin-top: 30px;
    @gap:20px;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    >li{
      width: calc((100% - @gap * 4) / 5);
      margin-bottom: @gap;
      background: #fff;
      position: relative;
      margin-right: @gap;
      border-radius: 6px;
      overflow: hidden;
      &:nth-of-type(5n){
        margin-right: 0;
      }

      .li-hover{
        display: none;
        width: 100%;
        height: 240px;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 99;
        background: rgba(0, 0, 0, 0.6);
        .lipreview{
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%,-50%);
          color: #fff;
          display: inline-block;
          line-height: 40px;
          height: 40px;
          width: 100px;
          text-align: center;
          border-radius: 22px;
          cursor: pointer;
          background-color: transparent;
          border: 1px solid #fff;
          &:hover {
            border: none;
            background: #1983F6;
          }
        }
        .oper{
          display: flex;
          justify-content: space-around;
          align-items: center;
          position: absolute;
          bottom: 10px;
          left: 0;
          width: 100%;
          >li{
            color: #fff;
            font-size: 13px;
            display: flex;
            align-items: center;
            cursor: pointer;
            >i{
              font-size: 20px;
              margin-right: 4px;
            }
          }

        }
      }
      &:hover{
        box-shadow: 0px 2px 12px 0px rgba(50, 50, 51, 0.12);
        transform: translateY(-6px);
        .li-hover{
          display: block;
        }
        .img{
          .real{
            height: 108%;
          }  
        }
      }
    
      .img{
        width: 100%;
        height: 240px;
        position: relative;
        overflow: hidden;
        cursor: pointer;
        .real{
          height: 100%;
          position: absolute;
          top: 0;
          left: 50%;
          transform: translateX(-50%);
          z-index: 0;
          transition: all ease 0.3s;
        }   
      }
        
      .li-info{
        font-size: 14px;
        padding: 10px;
        >div{
          text-align: left;
          &:first-of-type{
            >span{
              font-weight: bold;
              margin-bottom: 10px;
              display: inline-block;
              text-overflow: ellipsis;
              overflow: hidden;
              white-space: nowrap;
              cursor: pointer;
              color: #323233;
              font-size: 16px;
            }
          }
          &:last-of-type{
            display: flex;
            justify-content: space-between;
            align-items: center;
            >span{
              font-size: 14px;
              color: #969799;
            }
            >div{
              color: #969799;
              i{
                margin-right: 6px;
              }
            }
          }
        }
      }
    }
    .add-work{
      .add-con{
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        text-align: center;
        div{
          width: 60px;
          height: 60px;
          border-radius: 50%;
          background: linear-gradient(144deg, #00AEFB 0%, #0076F6 100%);
          position: relative;
          cursor: pointer;
          >i{
            font-size: 32px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
            color: #fff
          }
        }
        span{
          color: #333333;
          display: inline-block;
          margin-top: 8px;
          font-size: 14px;
        }
      }
    }
  }
}
</style>

<style lang="less" scoped>
@import '../style.less';
</style>