<template>
    <div class="details-p">
        <div class="tops">
          <div class="word">
            <van-icon class="word01" :name="'diy-' + fileType(detailData.docFileType)" />
          </div>
          <div class="title">{{detailData.docName}}</div>
        </div>
        <div class="middles">
            <h3>摘要</h3>
            <p>{{detailData.docSummary}}</p>
            <div class="continue" v-show="buyed == 0">全文共{{detailData.docPageSize}}页，<span @click="continued">继续阅读<van-icon name="arrow-down" size="18" /></span></div>
        </div>
        <div class="head-tip" id="fixedTop" :class="{'is-fixed':fixed}" v-show="buyed == 1">
            <h3 v-show="fixed">
              <van-icon class="word01" :name="'diy-' + fileType(detailData.docFileType)" />
              <span>{{detailData.docName}}</span>
            </h3>
            <span class="pages"><i id="page_num"></i> / <i id="page_count"></i></span>
        </div>
        <div class="botts" v-show="buyed == 1">
            <div class="cont-page" id="pdfPage"></div>
        </div>
        <van-goods-action>
            <van-goods-action-icon class="no-icon">
                <template #default>
                    <p class="p1">剑鱼币</p>
                    <p class="p2">{{detailData.price}}</p>
                </template>
            </van-goods-action-icon>
            <van-goods-action-icon icon="diy-jubao" text="投诉举报" @click="jubaod" />
            <van-goods-action-icon :icon="collectd==1?'diy-guanzhu':'diy-weiguanzhu'" :text="collectd==1?'已收藏':'收藏'" @click="canged" />
            <van-goods-action-button text="下载文档" @click="uploaded" />
        </van-goods-action>
        <!-- 充值 -->
        <recharge ref="charge" :detailData="detailData" :coins="coins"></recharge>
        <!-- 分享 -->
        <share-pop ref="shares" :detailData="detailData" :links="links"></share-pop>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { mapActions } from 'vuex'
import { Icon, Toast, GoodsAction, GoodsActionIcon, GoodsActionButton } from 'vant'
import Recharge from '@/components/Recharge.vue'
import sharePop from '@/components/SharePopup.vue'
import { MixinTop } from '@/utils/mixin-top'
import { weChatShare } from '@/utils/wxShare'
const pdfjsLib = require('pdfjs-dist/build/pdf.js')
const pdfjsViewer = require('pdfjs-dist/web/pdf_viewer.js')

@Component({
  name: 'details-p',
  mixins: [MixinTop],
  components: {
    [Icon.name]: Icon,
    [GoodsAction.name]: GoodsAction,
    [GoodsActionIcon.name]: GoodsActionIcon,
    [GoodsActionButton.name]: GoodsActionButton,
    Recharge,
    sharePop
  },
  methods: {
    ...mapActions({
      getDetails: 'main/getDetails',
      getShow: 'main/getShow',
      getCoin: 'main/getCoin',
      getDown: 'main/getDown',
      getShare: 'main/getShare',
      getAdd: 'main/getAdd',
      getRemove: 'main/getRemove'
    })
  }
})
export default class extends Vue {
  getDetails: any
  getCoin: any
  getDown: any
  getShow: any
  getShare: any
  links: any = []
  docIds = ''
  fixed = false
  coins: any = []
  conts: any = []
  offsets: any = 0
  getAdd: any
  getRemove: any
  detailData: any = []
  collectd = 0
  buyed = 0
  pdfh5 = null
  pdfDocument: any
  config: any = {
    PAGE_TO_VIEW: 0,
    SCALE: 0,
    CMAP_URL: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.6.347/cmaps/',
    CMAP_PACKED: true,
    workerSrc: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.6.347/es5/build/pdf.worker.min.js'
  }

  pData: any = {
    heightList: []
  }

  TopConfig: any = {
    actionRightText: '<div style="display:flex;flex-direction: column;align-items: center;"><i class="j-icon icon-iconJianYu"></i><p style="color: #171826;font-size: 10px;line-height: 12px;margin-top:3px;">分享赚剑鱼币</p></div>',
    actionRightCallback: this.shared,
    actionRightStyle: {
      color: '#5F5E64',
      fontSize: '20px',
      paddingLeft: '10px'
    }
  }

  created () {
    this.docIds = this.$route.params.id
    this.onList()
    this.setTop()
    console.log(window.screen.width)
  }

  mounted () {
    // 监听滚轮
    window.addEventListener('scroll', this.initHeight)
  }

  destroyed () { // 移除监听
    window.removeEventListener('scroll', this.initHeight)
  }

  setTop () {
    this.$nextTick(() => {
      // 获取到达页面顶端的值
      const heights = document.getElementById('fixedTop')
      this.offsets = heights?.offsetTop
      // this.offsets = heights.getBoundingClientRect().top
      console.log(this.offsets)
    })
  }

  initHeight () {
    // 获取页面滚动距离
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    this.fixed = !!(scrollTop > this.offsets && this.buyed)
    const top = window.scrollY
    let base = 0
    for (let i = 0; i < this.pData.heightList.length; i++) {
      base += this.pData.heightList[i]
      if (top <= base) {
        this.updateText({ type: 'num', value: i + 1 })
        break
      }
    }
  }

  async getShareUrl () {
    const { data } = await this.getShare({ docId: this.docIds })
    this.links = data.url || location.href
    // 注册微信sdk
    weChatShare({
      config: {
        title: this.detailData.docName,
        desc: this.detailData.docSummary,
        link: this.links
      }
    })
  }

  shared () {
    ;(this.$refs.shares as any).show = true
  }

  updateText (data: any) {
    console.log(data)
    switch (data.type) {
      case 'count': {
        ;(document.getElementById('page_count') as HTMLDivElement).textContent = data.value
        break
      }
      case 'num': {
        ;(document.getElementById('page_count') as HTMLDivElement).textContent = data.value
        break
      }
    }
  }

  renders () {
    const container = document.getElementById('pdfPage')
    // let notes = document.getElementById('pdfPage')
    // document.getElementById('pdfPage').style.width = '100vw'
    return this.pdfDocument.getPage(this.config.PAGE_TO_VIEW).then((pdfPage: any) => {
      const pdfPageView = new pdfjsViewer.PDFPageView({
        container: container,
        id: this.config.PAGE_TO_VIEW,
        scale: this.config.SCALE,
        defaultViewport: pdfPage.getViewport({ scale: this.config.SCALE }),
        eventBus: new pdfjsViewer.EventBus(),
        annotationLayerFactory: new pdfjsViewer.DefaultAnnotationLayerFactory()
      })
      pdfPageView.setPdfPage(pdfPage)
      this.pData.heightList.push(pdfPageView.viewport.height)
      return pdfPageView.draw()
    })
  }

  init () {
    console.log(this.conts)
    pdfjsLib.GlobalWorkerOptions.workerSrc = this.config.workerSrc
    const loadingTask = pdfjsLib.getDocument({
      url: this.conts,
      cMapUrl: this.config.CMAP_URL,
      cMapPacked: this.config.CMAP_PACKED
    })
    loadingTask.promise.then((pdfDocument: any) => {
      this.pdfDocument = pdfDocument
      console.log(this.pdfDocument.numPages)
      this.updateText({ type: 'count', value: this.pdfDocument.numPages })
      this.updateText({ type: 'num', value: 1 })
      for (let i = 0; i < this.pdfDocument.numPages; i++) {
        this.config.PAGE_TO_VIEW++
        this.renders()
      }
    })
  }

  watchPage () {
    const top = window.scrollY
    let base = 0
    for (let i = 0; i < this.pData.heightList.length; i++) {
      base += this.pData.heightList[i]
      if (top <= base) {
        this.updateText({ type: 'num', value: i + 1 })
        break
      }
    }
  }

  buyShow () {
    this.getShow({ docId: this.docIds }).then((res: any) => {
      console.log(res.data)
      this.conts = res.data
      this.init()
    })
  }

  onList () {
    this.getDetails({ docId: this.docIds, from: this.$route.query.from }).then((res: any) => {
      console.log(res.data)
      this.detailData = res.data.detail
      this.detailData.docSummary = res.data.detail.docSummary.split('').length >= 500 ? res.data.detail.docSummary + '...' : res.data.detail.docSummary
      this.buyed = res.data.status
      if (res.data.status === 1) {
        this.buyShow()
      }
      this.collectd = res.data.collect
      this.getShareUrl()
    })
    this.getCoin({ B: true }).then((res: any) => {
      console.log(res.data.data)
      this.coins = res.data.points
    })
  }

  jubaod () {
    Toast({
      duration: 3500,
      message: '如果您发现此内容有侵权行为，请联系客服400-108-6670进行投诉'
    })
  }

  canged () {
    if (this.collectd === 0) {
      this.getAdd({ docId: this.docIds }).then((res: any) => {
        console.log(res)
        if (res.error_code === 0) {
          this.collectd = 1
          Toast('收藏成功')
        }
      })
    } else {
      this.getRemove({ docId: this.docIds }).then((res: any) => {
        console.log(res)
        if (res.error_code === 0) {
          this.collectd = 0
          Toast('取消收藏')
        }
      })
    }
  }

  continued () {
    this.uploaded()
  }

  uploaded () {
    if (this.buyed === 1) {
      this.getDown({ docId: this.docIds }).then((res: any) => {
        if (res.error_code === 0) {
          window.location.href = res.data
        }
      })
    } else {
      if (this.coins.balance < this.detailData.price) {
        ;(this.$refs.charge as any).show = true
      } else {
        this.$router.replace('/purchase/' + this.detailData.docId)
      }
    }
  }

  fileType (val: any) {
    if (val === 1) {
      return 'word'
    } else if (val === 2) {
      return 'pdf'
    } else if (val === 3) {
      return 'excel'
    } else if (val === 4) {
      return 'ppt'
    } else if (val === 5) {
      return 'txt'
    } else {
      return ''
    }
  }
}
</script>

<style lang="scss" scoped>
@include diy-icon('pdf', 24, 24);
@include diy-icon('word', 24, 24);
@include diy-icon('excel', 24, 24);
@include diy-icon('ppt', 24, 24);
@include diy-icon('jubao', 20, 20);
@include diy-icon('weiguanzhu', 20, 20);
@include diy-icon('guanzhu', 20, 20);
@include diy-icon('iconJianYu', 24, 24);
.details-p {
    display: flex;
    flex-direction: column;
    padding-bottom: 80px;
    .tops {
        display: flex;
        flex-direction: initial;
        background: #fff;
        padding: 24px 16px;
        .word {
          display: flex;
        }
        .word01 {
            display: flex;
            width: 24px;
            height: 24px;
            margin-right: 8px;
        }
        .title {
          color: #171826;
          font-weight: 500;
          font-size: 20px;
          line-height: 30px;
        }
    }
    .middles {
        padding: 16px;
        background: #fff;
        margin: 8px 0;
        h3 {
            font-size: 16px;
            line-height: 24px;
            font-weight: 500;
            color: #171826;
        }
        p {
            color: #5F5E64;
            font-size: 14px;
            line-height: 20px;
            margin-top: 8px;
        }
        .continue {
            color: #5F5E64;
            font-size: 14px;
            line-height: 20px;
            text-align: center;
            margin-top: 32px;
            span {
                display: inline-flex;
                align-items: center;
                color: #2ABED1;
                cursor: pointer;
                i {
                    margin-left: 4px;
                }
            }
        }
    }
    .head-tip {
        width: auto;
        height: 60px;
        background: #fcfcfc;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding: 0 16px;
        border-bottom: 1px solid #F2F2F4;
        h3 {
            display: flex;
            align-items: center;
            span {
                width: 260px;
                color: #686868;
                font-weight: 500;
                font-size: 14px;
                line-height: 24px;
                overflow: hidden;
                text-overflow:ellipsis;
                white-space: nowrap;
            }
            i {
                margin-right: 8px;
            }
        }
        .pages {
            color: #686868;
            font-size: 14px;
            i:first-child {
                display: inline-block;
                font-style: normal;
                width: 16px;
                height: 16px;
                line-height: 18px;
                text-align: center;
                border-radius: 2px;
                background: #FFFFFF;
                border: 1px solid #ECECEC;
            }
        }
    }
    .is-fixed {
        position: fixed;
        top: 0;
        justify-content: space-between;
    }
    .botts {
        // padding: 16px 24px;
        // width: 375px;
        background: #fff;
        .cont-page {
          // width: 375px;
          overflow-y: scroll;
          background: #fff;
        }
    }
    .van-goods-action {
        // height: 56px;
        padding: 8px 16px;
        box-shadow: 0px -2px 8px 0px #eee;
        display: flex;
        justify-content: space-between;
        .no-icon {
            .p1 {
                font-size: 12px;
                line-height: 18px;
                color: #5F5E64;
            }
            .p2 {
                font-size: 18px;
                line-height: 26px;
                color: #FB483D;
            }
            .van-icon {
                display: none!important;
            }
        }
        .van-goods-action-icon:not(.no-icon) {
            font-size: 10px;
            color: #5F5E64;
        }
        .van-goods-action-button--first {
            margin-left: 0;
        }
        .van-goods-action-button--last {
            margin-right: 0;
        }
        .van-goods-action-button {
            flex: none;
        }
        .van-button--large {
            width: 165px;
            height: 40px;
        }
        ::v-deep .van-button--default {
            background-color: #2ABED1;
            .van-button__content {
                .van-button__text {
                    color: #fff;
                    font-size: 16px;
                }
            }
        }
    }
}
</style>
