<template>
  <div class="user-library">
    <van-tabs
      :title-active-color="tabConf.titleActiveColor"
      :title-inactive-color="tabConf.titleInactiveColor"
      :line-width="tabConf.lineWidth"
      :color="tabConf.color"
      :before-change="beforeTabChange"
      v-model="tabActive"
      class="j-container"
    >
      <van-tab title="我的文库" name="0">
        <van-list
          v-model="myLibListState.loading"
          :finished="myLibListState.finished"
          :offset="myLibListState.offset"
          @load="onLoad"
          class="more-list"
          ref="vanList"
        >
          <div>
            <Card
              v-for="(item, index) in myLibListState.list"
              :key="index"
              :title="item.DocName"
              :docType="item.DocFileType"
              :subInfo="calcSubInfoForLib(item)"
              @onClick="toDocDetail(item)"
            />
          </div>
        </van-list>
        <Empty v-if="myLibListState.list.length === 0 && myLibListState.loaded">暂无数据</Empty>
      </van-tab>

      <van-tab title="文库收藏" name="1">
        <van-list
          v-model="myCollectionListState.loading"
          :finished="myCollectionListState.finished"
          :offset="myCollectionListState.offset"
          @load="onLoad"
          class="more-list"
          ref="vanList"
        >
          <div>
            <Card
              v-for="(item, index) in myCollectionListState.list"
              :key="index"
              :title="item.DocName"
              :desc="item.DocSummary"
              :docType="item.DocFileType"
              :price="item.Cost"
              :subInfo="calcSubInfoForColl(item)"
              @onClick="toDocDetail(item)"
            />
          </div>
        </van-list>
        <Empty v-if="myCollectionListState.list.length === 0 && myCollectionListState.loaded">暂无数据</Empty>
      </van-tab>
    </van-tabs>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { Tabs, Tab, List } from 'vant'
import { mapState, mapMutations, mapActions } from 'vuex'
import Card from '@/components/docs-card/Card.vue'
import Empty from '@/components/common/Empty.vue'
import { dateFormatter, formatSize } from '@/utils/globalFunctions'

@Component({
  name: 'user-library',
  components: {
    [Tabs.name]: Tabs,
    [Tab.name]: Tab,
    [List.name]: List,
    Card,
    Empty
  },
  computed: {
    ...mapState('main', {
      userLibInfo: (state: any) => state.userLib
    })
  },
  methods: {
    ...mapMutations({
      saveLibState: 'main/saveMyLibState',
      clearLibState: 'main/clearMyLibState'
    }),
    ...mapActions({
      getMyLibList: 'main/getMyLibList'
    })
  }
})

export default class UserLibrary extends Vue {
  protected userLibInfo: any
  protected saveLibState: any
  protected clearLibState: any

  protected getMyLibList: any

  tabActive = '0'

  tabConf = {
    titleActiveColor: '#2ABED1',
    titleInactiveColor: '#5F5E64',
    lineWidth: '24',
    color: '#2ABED1'
  }

  myLibListState = {
    loaded: false,
    loading: false,
    finished: false,
    pageNum: 1,
    pageSize: 10,
    offset: 80,
    scrollTop: 0,
    list: []
  }

  myCollectionListState = {
    loaded: false,
    loading: false,
    finished: false,
    pageNum: 1,
    pageSize: 10,
    offset: 80,
    scrollTop: 0,
    list: []
  }

  get keyForList () {
    const map: any = {
      0: 'myLibListState',
      1: 'myCollectionListState'
    }
    return map[this.tabActive] || map[0]
  }

  @Watch('tabActive')
  onTabChange () {
    const i: any = this.$data[this.keyForList]
    this.setScrollTop(i.scrollTop)
  }

  created () {
    this.tabActive = this.$route.query.tab as string
    this.reStoreState()
  }

  beforeTabChange () {
    this.saveScrollTop()
    return true
  }

  toDocDetail (item: any) {
    const { DocId: id } = item
    this.saveState()
    this.$router.push({
      name: 'details',
      params: { id }
    })
  }

  calcSubInfoForLib (item: any) {
    const { UpdateAt, DocFileSize } = item
    return [`${dateFormatter(UpdateAt * 1000, 'yyyy/MM/dd')}下载`, formatSize(DocFileSize)]
  }

  calcSubInfoForColl (item: any) {
    const { DocPageSize, DocFileSize } = item
    return [`共${DocPageSize}页`, formatSize(DocFileSize)]
  }

  async onLoad () {
    const t: any = this.$data[this.keyForList]
    const query = {
      num: t.pageNum,
      size: t.pageSize,
      sign: this.tabActive
    }
    console.log('搜索参数：', query)
    t.loading = true
    const { data } = await this.getMyLibList(query)
    t.loading = false
    t.loaded = true

    if (data && Array.isArray(data.list)) {
      t.pageNum += 1
      t.total = data.total
      t.list = t.list.concat(data.list)
    } else {
      t.finished = true
    }

    // 数据请求完成(根据页码计算，当前页是否是最后一页)
    // 请求完成后，页码就变为了下一页的页面，所以这里要-1
    const isLastPage = (t.pageNum - 1) * t.pageSize >= t.total
    if (isLastPage) {
      t.finished = true
    }
  }

  reStoreState () {
    const listInfo = this.userLibInfo
    if (!listInfo || Object.keys(listInfo).length === 0) {
      return false
    } else {
      for (const key in listInfo) {
        this.$data[key] = listInfo[key]
      }
      this.setScrollTop(this.$data[this.keyForList].scrollTop)
      setTimeout(() => {
        this.clearLibState()
      }, 20)
      return true
    }
  }

  setScrollTop (scrollTop: number) {
    this.$nextTick(() => {
      const wrapper: any = document.querySelector('.van-tabs__content')
      wrapper.scrollTop = scrollTop
    })
  }

  saveScrollTop () {
    const wrapper: any = document.querySelector('.van-tabs__content')
    this.$data[this.keyForList].scrollTop = wrapper.scrollTop
  }

  saveState () {
    this.saveScrollTop()
    const d = {
      tabActive: this.tabActive,
      myLibListState: this.myLibListState,
      myCollectionListState: this.myCollectionListState
    }
    this.saveLibState(d)
  }
}
</script>

<style lang="scss" scoped>
.user-library {
  ::v-deep {
    .van-tabs__wrap {
      height: 48px;
    }
    .van-tabs__line {
      bottom: 18px;
    }
    .van-tab__pane {
      height: 100%;
    }
    .van-tabs__content {
      flex: 1;
      overflow-y: scroll;
      overflow-x: hidden;
    }
    .van-tabs {
      width: 100%;
    }
    .van-tab {
      font-size: 16px;
      line-height: 20px;
    }
  }
}
</style>
