<template>
  <div class="detail-main">
    <div class="c-details">
      <div class="d-left"  v-loading="loading">
        <div class="tops">
          <h1>
            <div>
              <i :class="'el-icon-jy-' + fileType(datas.docFileType)"></i>
            </div>
            {{ datas.docName }}
          </h1>
          <div class="cd-tips">
            <ul>
              <li class="li-tags" v-for="item in getContentTags" :key="item">{{ item }}</li>
              <li class="type-tag" :class="datas.productType === 2 ? 'boutique' : 'free'">{{ datas.productType === 2 ? '付费精品' : '会员免费' }}</li>
              <li>{{ datas.viewTimes || 0 }}次浏览<el-divider direction="vertical"></el-divider></li>
              <li>{{ datas.downTimes || 0 }}次下载<el-divider direction="vertical"></el-divider></li>
              <li>共{{ datas.docPageSize }}页<el-divider direction="vertical"></el-divider></li>
              <li>{{ datas.docFileSize }}<el-divider direction="vertical"></el-divider></li>
              <li class="no-line">{{ datas.uploadDate }}上传</li>
            </ul>
            <!-- <div class="coin"><i class="el-icon-jy-iconJianYu"></i><span>{{ datas.price }}</span></div> -->
          </div>
          <el-divider class="heng-line" v-if="lineShow"></el-divider>
        </div>
        <div class="middles middles-summary" :class="{ 'actives': buyed == 0}" v-if=" buyed == 0 && datas.source === 1 && !islogin">
          <h3>摘要</h3>
          <p>{{ datas.docSummary }}</p>
          <div class="continue" v-if="buyed == 0">全文共{{ datas.docPageSize }}页，<span @click="continued">阅读全文<i
              class="el-icon-arrow-down"></i></span></div>
        </div>
        <div class="middles preview-page" v-if="buyed === 0 && (islogin || (!islogin && datas.source === 2))">
          <div class="preview-content">
            <!--剑鱼文档全为PDF-->
            <div v-if="datas.source === 1 ">
              <div class="cont-p"  id="previewPdfPage"></div>
            </div>
            <div class="file-content file-word-docx" v-else>
              <img v-for="(iUrl, ind) in previewConfig.docinImg" :key="'iUrl_' + ind" :src="iUrl" alt="预览">
            </div>
          </div>
          <div class="continue" v-if="unreadPage > 0 && datas.docPageSize > 1 && guideText">
            剩余{{ unreadPage }}页未读，<span @click="continued">{{ guideText }}
            <i class="el-icon-arrow-down"></i></span>
          </div>
        </div>
        <div class="head-tip" id="fixedTop" :class="{ 'is-fixed': fixed }">
          <h3 v-show="fixed">
            <i :class="'el-icon-jy-' + fileType(datas.docFileType)"></i>
            <span>{{ datas.docName }}</span>
          </h3>
          <span v-if="page_count" class="pages"><i>{{ page_num }}</i> / <i>{{ page_count }}</i></span>
        </div>
<!--        豆丁的文档渲染错误后，需要处理成最多预览5页图片-->
        <div class="bottoms-preview" v-if="docLoadError && buyed === 1">
          <div class="preview-content">
            <!--剑鱼文档全为PDF-->
            <div class="file-content">
              <img v-for="(iUrl, ind) in previewConfig.docinImg" :key="'iUrl_' + ind" :src="iUrl" alt="预览">
            </div>
            <div class="continue" v-if="unreadPage > 0 && datas.docPageSize > 1 && guideText">
              剩余{{ unreadPage }}页未读，<span @click="continued">{{ guideText }}
            <i class="el-icon-arrow-down"></i></span>
            </div>
          </div>
        </div>
        <div class="bottoms" id="colWidth">
          <div class="page" v-show="!docLoadError">
            <div class="cont-p" v-show="fileTypeThis !== 'docx' && fileTypeThis !== 'xlsx'" id="pdfPage"></div>
            <div class="file-content file-word-docx" id="docxPage" v-if="fileTypeThis === 'docx'">
              <vue-office-docx
                  :src="fileSrc.docSrc"
                  style="margin-bottom: 24px; height: 100vh;"
                  @rendered="rendered"
                  @error="errorHandler()"
              />
            </div>
            <div class="file-content file-word-docx" id="xlsxPage" v-if="fileTypeThis === 'xlsx' || fileTypeThis === 'xls'">
              <vue-office-excel
                  :src="fileSrc.excelSrc"
                  :options="excelOptions"
                  style="margin-bottom: 24px; height: 100vh"
                  @rendered="rendered"
                  @error="errorHandler"
              />
            </div>
          </div>
          <div class="foot-tip tops" id="footp">
            <div class="member-time-tip" v-if="redShow && islogin">
              <span class="warn-icon">i</span>
              <span>您的文库会员将于{{ surplusDay }}到期，续费即享下载特权！</span>
              <span @click="goRenew" style="color: #2ABED1;cursor: pointer;">请点击前往续费＞</span>
              <span @click="redShow = false" class="time-tip-close el-icon-close"></span>
            </div>
            <div class="doc-detail-ad" v-else-if="!redShow && jyPcDocmemberDetail && jyPcDocmemberDetail.length">
              <div class="doc-detail-ad-img">
                <a :href="jyPcDocmemberDetail[0].s_link || 'javascript:;'">
                  <img :src="jyPcDocmemberDetail[0].s_pic" :alt="jyPcDocmemberDetail[0].s_remark" />
                </a>
              </div>
              <span @click="jyPcDocmemberDetail = []" class="time-tip-close el-icon-close"></span>
            </div>
            <div class="load-doc">
              <div class="icons">
                <el-tooltip placement="bottom" effect="light" popper-class="f-share">
                  <span class="spa1"><i class="el-icon-jy-share"></i>分享</span>
                  <div slot="content">
                    <img :src="locaHref + '/jydocs/share/img?docId=' + docIds" width="110" height="108">
                    <p style="color: #686868;font-size: 14px;text-align:center;">微信扫码分享</p>
                  </div>
                </el-tooltip>
                <span class="spa1 spa2" @click="shoucang"><i
                    :class="collectd == 1 ? 'el-icon-jy-guanzhu' : 'el-icon-jy-weiguanzhu'"></i>{{ collectd == 1 ? '已收藏' :
                      '收藏' }}</span>
                <el-tooltip content="如果您发现此内容有侵权行为，请联系客服400-108-6670进行投诉" placement="top" effect="dark">
                  <span class="spa1"><i class="el-icon-jy-jubao"></i>投诉举报</span>
                </el-tooltip>
              </div>
              <div class="file-action">
                <!-- 会员免费文档 -->
                <div class="file-action-content member-free" v-if="datas.productType === 1">
                  <div class="coin before-coin" v-if="buyed !== 1 && docsInfo.freeDownload !== 1">原价：<i class="el-icon-jy-iconJianYu"></i><span style="text-decoration: line-through;">{{ datas.price }}</span></div>
                  <div class="member-mark" v-if="buyed !== 1 && docsInfo.docStatus > 0">会员免费</div>
                  <el-button class="prime-cost origin-cost" type="primary" @click="primeLoadFile" v-if="showCostBtn">
                    <i class="el-icon-jy-iconJianYu"></i>
                    <span>{{ datas.price }}</span>
                    <span>原价下载</span>
                  </el-button>
                  <el-button class="prime-cost" @click="downLoadFreeEvent" v-if="islogin && buyed !== 1 && !docsInfo.docStatus && docsInfo.freeDownload !== 1">
                    <span>使用免费下载特权</span>
                    <span>（1次机会）</span>
                  </el-button>
                  <div class="file-download" v-if="buyed === 1">
                    您已下载过该文档，可再次下载
                  </div>
                  <el-button type="primary" @click="loadFile">{{ btnName }}</el-button>
                </div>
                <!-- 精品文档 -->
                <div class="file-action-content member-pay" v-else>
                  <el-button class="prime-cost origin-cost" type="primary" @click="primeLoadFile" v-if="!docsInfo.docStatus && buyed === 0">
                    <i class="el-icon-jy-iconJianYu"></i>
                    <span>{{ datas.price }}</span>
                    <span>原价下载</span>
                  </el-button>
                  <div class="coin before-coin" v-if="docsInfo.docStatus > 0 && buyed === 0">
                    原价：<i class="el-icon-jy-iconJianYu"></i>
                    <span style="text-decoration: line-through;">{{ datas.price }}</span>
                  </div>
                  <div class="coin after-coin" v-if="docsInfo.docStatus > 0 && buyed === 0">
                    会员价：<i class="el-icon-jy-iconJianYu"></i>
                    <span style="color: #FF3A20;font-size: 24px;">{{ datas.docMemberPrice }}</span>
                  </div>
                  <div class="file-download" v-if="buyed === 1">
                    您已下载过该文档，可再次下载
                  </div>
                  <el-button type="primary" @click="loadFile">{{ btnName }}</el-button>
                </div>
              </div>
            </div>
          </div>
          <div class="transition-dom" ref="transitionDom"></div>
        </div>
      </div>
      <collect-info ref="collectRef"></collect-info>
      <common-dialog
        width="386px"
        @confirm="dialogConfirm"
        @cancel="dialogCancel"
        :confirm-text="dialogInfo.confirmText"
        :show-footer="true"
        :cancel-text="dialogInfo.cancelText"
        :title="dialogInfo.title"
        :show-cancel="dialogInfo.showCancel"
        :visible="dialogInfo.visible">
        <div class="dialog-content" style="text-align: center" v-html="dialogInfo.content"></div>
        <span slot="footText">{{ dialogInfo.footText }}</span>
      </common-dialog>
      <div class="d-right">
        <div class="r-tops">
          <a :href="item.s_link ? item.s_link : 'javascript:;'" v-for="item in adsUrl" :key="item.s_pic">
            <img :src="item.s_pic">
          </a>
        </div>
        <v-recommend :recomes="recomes"></v-recommend>
      </div>
    </div>
  </div>
</template>
<script>
import { Button, Tooltip, Divider, Message } from 'element-ui'
import { getDetails, getShow, getRecommend, getDown, getCoin, getAdd, getRemove, getSimpleData } from '../api/modules/detail'
import { formatSize, dateFormatter, recoveryPageData } from '@/utils/'
import vRecommend from '@/components/recommend'
import CollectInfo from '@/components/collect-info/CollectInfo'
import commonDialog from '@/components/dialog/Dialog'
import { getSearchTag } from '../api/modules/home'
import { getDocPays } from '../api/modules/purchase'
import { getJyAdListApi } from '../api/modules/publicapply'
import { mapState } from 'vuex'
// 引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from '@vue-office/excel'
// 引入相关样式
import '@vue-office/docx/lib/index.css'
import '@vue-office/excel/lib/index.css'
export default {
  components: {
    [Button.name]: Button,
    [Tooltip.name]: Tooltip,
    [Divider.name]: Divider,
    [Message.name]: Message,
    vRecommend,
    commonDialog,
    CollectInfo,
    VueOfficeDocx,
    VueOfficeExcel
  },
  data () {
    return {
      loading: false,
      docIds: '',
      locaHref: '',
      datas: [],
      conts: [],
      adsUrl: [],
      recomes: [],
      coinNum: 0,
      btnName: '',
      buyed: 0,
      downloadStatus: 0,
      collectd: 0,
      offsetTop: 0,
      offsetWidth: 0,
      colWidth: 0,
      page_num: 0,
      page_count: 0,
      redShow: false,
      lineShow: false,
      fixed: false,
      pdfh5: null,
      pdfDocument: null,
      config: {
        PAGE_TO_VIEW: 0,
        SCALE: 1.0,
        CMAP_URL: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.1.266/cmaps/',
        CMAP_PACKED: true,
        workerSrc: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.1.266/build/pdf.worker.min.js'
      },
      pData: {
        heightList: []
      },
      tabs: [],
      islogin: false,
      // userMemberInfo: {},
      dialogInfo: {
        visible: false,
        title: '文档下载成功',
        content: `已添加到您的文库中，您可前往<span class="high-light">【工作台-服务-我的文库】</span>查看。`,
        footText: '会员免费文档下载特权：消耗1篇 | 今日还剩余99篇',
        showCancel: false,
        confirmText: '我知道了'
      },
      jyPcDocmemberDetail: [],
      docsInfo: {
        docStatus: 0,
        endDate: 0,
        freeDownload: 0,
        startDate: 0
      },
      surplusDay: 0, // 剩余多少天到期
      fileSrc: {
        docSrc: '',
        excelSrc: ''
      },
      fileTypeThis: '', // 当前文件类型
      excelOptions: {
        xls: false
      },
      previewConfig: {
        pageNums: 1,
        docinImg: []
      },
      // 文档加载失败
      docLoadError: false,
    }
  },
  created () {
    window.loginCallback = this.loginCallback
    this.docIds = this.$route.params.id
    this.locaHref = window.location.origin
    this.getSimpleData_()
    this.setTop()
    this.adverse()
  },
  beforeCreate () {
    $('.docs-app').addClass('page-content')
  },
  mounted () {
    this.details()
    window.addEventListener('scroll', this.initHeight)
  },
  beforeMount () {
    this.tabs = recoveryPageData('jy-docs-search-tags-pc')
    this.getTags()
  },
  destroyed () { // 移除监听
    window.removeEventListener('scroll', this.initHeight)
  },
  computed: {
    ...mapState('user', ['userMemberInfo']),
    getContentTags () {
      const a = new Set(this.datas.tags)
      const b = new Set(this.tabs.map(v => v.type))
      const arr = Array.from(new Set([...b].filter(x => a.has(x))))

      const oldArr = Array.from(a)
      arr.forEach(v => {
        oldArr.splice(oldArr.indexOf(v), 1)
      })
      const nArr = arr.concat(oldArr)
      return nArr.splice(0, 3)
    },
    showCostBtn () {
      return (this.buyed !== 1 && !this.docsInfo.docStatus && this.docsInfo.freeDownload === 1 && this.downloadStatus !== 1) || !this.islogin
    },
    // 未购买预览时，未读页码; 或者豆丁渲染错误，
    unreadPage () {
      return this.datas.docPageSize - this.previewConfig.pageNums
    },
    // P620需求：1、未购买预览时，引流文案
    // 或者，购买豆丁文件加载时错误后，最多预览5页，最后的引流文案
    guideText () {
      let btnText = '下载文档阅读全文'
      if (!this.islogin) {
        return '开通文库会员免费阅读全文'
      }
      if(this.docLoadError) {
        return '下载文档阅读全文'
      }
      // 会员
      if (this.docsInfo?.docStatus > 0 || (this.buyed === 1 && this.datas.source === 2 && this.datas.docFileType !== 2)) {
        btnText = '下载文档阅读全文'
      } else if (this.docsInfo?.docStatus <= 0 && this.buyed === 0) {
        if (this.datas.productType === 2) {
          btnText = `开通文库会员${this.datas.docMemberDiscount}折下载文档阅读全文`
        } else {
          btnText = '开通文库会员免费阅读全文'
        }
      }
      // 会员免费文档+未下载+不是会员+未使用1次免费下载特权
      if (this.islogin && this.datas.productType === 1 && this.buyed === 0 && !this.docsInfo.docStatus && this.docsInfo.freeDownload !== 1) {
        btnText = '使用免费下载特权阅读全文'
      }
      if (this.buyed === 1 && this.datas.docFileType === 2) {
        btnText = ''
      }
      return btnText
    }
  },
  watch: {
    userMemberInfo: {
      handler (val) {
        if (val && val.docsInfo) {
          this.docsInfo = val.docsInfo
          const date = parseInt(new Date().getTime() / 1000)
          const sevenDay = 60 * 60 * 24 * 7
          const oneDay = 60 * 60 * 24
          const surplus = parseInt(val.docsInfo?.endDate - date)
          if (surplus <= sevenDay && val.docsInfo.docStatus === 1) {
            this.redShow = true
            this.surplusDay = (surplus / oneDay)
            // 如果剩余天数不到1天，则显示今天到期
            if (this.surplusDay < 1) {
              this.surplusDay = '今天'
            } else {
              this.surplusDay = this.surplusDay.toFixed(0) + '天后'
            }
          }
        }
      },
      immediate: true
    }
  },
  methods: {
    rendered () {
      console.log('渲染完成')
    },
    errorHandler () {
      this.ddErrorPreview()
      console.log('渲染失败')
    },
    // 使用免费下载特权
    downLoadFreeEvent () {
      if (this.docsInfo?.freeDownload === 0) {
        // 未留资，去留资
        try {
          this.$refs.collectRef.noCallApiFn('pc_library_details_free', true)
        } catch (error) {
          console.log(error)
        }
      } else if (this.docsInfo?.freeDownload === 2) {
        // 已留资，未使用特权，可以下载
        getDocPays({ docId: this.datas.docId, payType: 2 }).then((res) => {
          if (res.data.error_code === 0) {
            const params = {
              visible: true,
              title: '文档下载成功',
              content: `已添加到您的文库中，您可前往<span class="high-light">【工作台-服务-我的文库】</span>查看。`,
              footText: '',
              showCancel: false,
              confirmText: '我知道了'
            }
            this.dialogInfo = params
            this.buyed = 1
            this.getDocInfo()
          }
        })
      }
    },
    dialogConfirm () {
      const text = this.dialogInfo.confirmText
      if (text === '立即充值') {
        window.location.href = '/swordfish/integral/index/recharge?id=' + this.datas.docId
      } else if (text === '明日再来' || text === '我知道了') {
        if (this.dialogInfo.title === '文档下载成功') {
          // 加载文档内容，刷新页面
          location.reload()
        } else {
          this.dialogInfo.visible = false
        }
      }
    },
    dialogCancel () {
      const text = this.dialogInfo.cancelText
      if (text === '原价下载') {
        this.dialogInfo.visible = false
        this.primeLoadFile()
      } else {
        this.dialogInfo.visible = false
      }
    },
    async getDocInfo () {
      if (this.docsInfo?.docStatus > 0 || this.buyed === 1) {
        this.btnName = '下载文档'
      } else {
        if (this.datas.productType === 2) {
          this.btnName = `开通文库会员，享${this.datas.docMemberDiscount}折下载`
        } else {
          this.btnName = '开通文库会员免费下载'
        }
      }
    },
    loginCallback () {
      this.islogin = true
      this.adverse()
      this.tabs = recoveryPageData('jy-docs-search-tags-pc')
      this.getTags()
    },
    getSimpleData_ () {
      getSimpleData({ t: new Date().getTime() }).then((res) => {
        if (!res.data.error) {
          this.islogin = true
        }
      })
    },
    // 前往续费
    goRenew () {
      window.location.href = '/swordfish/page_big_pc/order/doc-member'
    },
    setTop () {
      this.$nextTick(() => {
        // 获取到达页面顶端的值
        const heights = document.getElementById('fixedTop')
        this.offsetTop = heights.getBoundingClientRect().top
        const headerNav = document.getElementById('public-nav')
        if (headerNav) {
          const headerTop = headerNav.offsetHeight
          heights.style.top = headerTop + 'px'
        }
      })
    },
    initHeight () {
      // 获取页面滚动距离
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      this.fixed = !!(scrollTop > this.offsetTop && this.buyed)
      this.watchPage()
      let t = document.getElementById('pdfPage')
      if (this.fileTypeThis === 'docx') {
        t = document.getElementById('docxPage')
      } else if (this.fileTypeThis === 'xlsx' || this.fileTypeThis === 'xls') {
        t = document.getElementById('xlsxPage')
      }
      const targetElement = this.$refs.transitionDom
      const rect = targetElement.getBoundingClientRect()
      const innerHeight = window.innerHeight
      const b = t.getBoundingClientRect().bottom
      const dom = document.getElementById('footp')
      if (b < 500 || rect.top < innerHeight) {
        dom.style.position = 'unset'
      } else {
        dom.style.position = 'fixed'
        dom.style.bottom = '0px'
        dom.style.zIndex = '99'
      }
    },
    updateText ({ type, value = '' }) {
      switch (type) {
        case 'count': {
          this.page_count = value
          break
        }
        case 'num': {
          this.page_num = value
          break
        }
      }
    },
    renders (type) {
      let container = document.getElementById('pdfPage')
      if (type === 'preview') {
        container = document.getElementById('previewPdfPage')
      }
      return this.pdfDocument.getPage(this.config.PAGE_TO_VIEW).then((pdfPage) => {
        var 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 (type) {
      pdfjsLib.GlobalWorkerOptions.workerSrc = this.config.workerSrc
      const loadingTask = pdfjsLib.getDocument({
        url: this.conts.data,
        cMapUrl: this.config.CMAP_URL,
        cMapPacked: this.config.CMAP_PACKED
      })
      loadingTask.promise.then((pdfDocument) => {
        this.pdfDocument = pdfDocument
        this.updateText({ type: 'count', value: this.pdfDocument.numPages })
        this.updateText({ type: 'num', value: 1 })
        const numPages = type === 'preview' ? this.previewConfig.pageNums : this.pdfDocument.numPages
        for (let i = 0; i < numPages; i++) {
          this.config.PAGE_TO_VIEW++
          this.renders(type)
        }
        this.loading = false
      }).catch((e) => {
        console.log('-------加载错误了------')
        console.warn(e)
        this.loading = false
        // 文档加载失败
        if (this.datas.source === 2) {
          this.ddErrorPreview()
        }
      })
    },
    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 (type) {
      this.loading = true
      getShow({ docId: this.docIds }).then(res => {
        if (res.data.error_code === 0) {
          this.conts = res.data
          let FileIndex = 0
          const fileExtensions = ['doc', 'docx', 'pdf', 'xls', 'xlsx', 'ppt', 'txt']
          fileExtensions.forEach((v, index) => {
            if (this.conts.data.indexOf(v) > -1){
              FileIndex = index
            }
          })

          this.fileTypeThis = fileExtensions[FileIndex]
          if (fileExtensions[FileIndex] === 'docx' || fileExtensions[FileIndex] === 'xlsx' || fileExtensions[FileIndex] === 'xls') {
            this.loading = false
          }
          switch (fileExtensions[FileIndex]) {
            case 'docx':
              // this.fileSrc.docSrc = res.data.data
              this.ddErrorPreview()
              break
            case 'xlsx':
              this.excelOptions.xls = false
              this.fileSrc.excelSrc = res.data.data
              break
            case 'xls':
              this.excelOptions.xls = true
              this.fileSrc.excelSrc = res.data.data
            default:
              this.init(type)
              break
          }
        } else {
          this.loading = false
          Message({
            message: res.data.error_msg,
            type: 'warning'
          })
        }
      }).catch(() => {
        this.loading = false
      })
    },
    coined () {
      getCoin({ B: true }).then(res => {
        if (res.data.error_code === 0) {
          this.coinNum = res.data.data.points.balance
          // if (this.buyed === 1) {
          //   this.btnName = '下载文档'
          //   this.lineShow = false
          // } else {
          //   if (this.coinNum < this.datas.price) {
          //     this.btnName = '立即充值'
          //     this.redShow = true
          //   } else {
          //     this.btnName = '下载文档'
          //     this.redShow = false
          //     this.lineShow = true
          //   }
          // }
        }
      })
    },
    recommend (str) {
      this.recomes = []
      getRecommend({ docTag: str, docId: this.docIds, num: 3 }).then(res => {
        res.data.data.forEach(v => {
          v.docFileSize = formatSize(v.docFileSize)
          this.recomes.push(v)
        })
      })
    },
    getTags () {
      getSearchTag().then(res => {
        if (!res.data.error_msg.length) {
          this.tabs = res.data.data.map(v => {
            return {
              type: v,
              label: v
            }
          })
          sessionStorage.setItem('jy-docs-search-tags-pc', JSON.stringify(this.tabs))
        }
      })
    },
    details () {
      getDetails({ docId: this.docIds, from: this.$route.query.from }).then(data => {
        const res = data.data
        if (res.error_code === 0) {
          this.recommend(res.data.detail.tags)
          this.datas = res.data.detail
          this.datas.docFileSize = formatSize(this.datas.docFileSize)
          this.datas.uploadDate = dateFormatter(this.datas.uploadDate.replace(/-/g, '/'), 'yyyy/MM/dd')
          if (this.datas.docSummary) {
            this.datas.docSummary = this.datas.docSummary.split('').length >= 500 ? this.datas.docSummary + '...' : this.datas.docSummary
          } else {
            this.datas.docSummary = ''
          }
          this.datas.tags = this.datas.tags.split(',')
          this.buyed = res.data.status
          this.downloadStatus = res.data.downloadStatus
          if (this.buyed === 1) {
            document.getElementById('fixedTop').style.display = 'block'
            document.getElementById('footp').style.position = 'fixed'
            document.getElementById('footp').style.bottom = '0'
          } else {
            document.getElementById('fixedTop').style.display = 'none'
            // 处理预览展示
            this.disposePreviewContent(this.datas)
          }
          this.getDocInfo()
          this.coined()
          // 已经下载过，显示文档内容
          if (res.data.status === 1) {
            this.buyShow()
          }
          this.collectd = res.data.collect
          // 监听滚轮
          setTimeout(() => {
            this.initHeight()
          }, 500)
        } else {
          Message({
            message: res.error_msg,
            type: 'warning'
          })
        }
      })
    },
    // 处理预览展示
    disposePreviewContent (details) {
      this.previewConfig.docinImg = []
      // P620需求 总页数≥3页：最多预览2页；总页数≤2页：最多预览1页。
      // 预览页数
      this.previewConfig.pageNums = details.docPageSize >= 3 ? 2 : 1
      // 豆丁预览图片
      // source 2豆丁 1 剑鱼
      if (details.source === 2) {
        for (let i = 1; i <= this.previewConfig.pageNums; i++) {
          const ddUrl = `https://docimg1.docin.com/docinviewpic.jsp?file=${details.imgId}&width=920&pageno=${i}&sview=1&clogo=1`
          this.previewConfig.docinImg.push(ddUrl)
        }
      } else {
        // 剑鱼文档，返回的格式全部为pdf
        if (this.islogin) {
          this.buyShow('preview')
        }
      }
    },
    // 豆丁预览(如果购买后的全文加载失败，则走预览逻辑,PDF)
    ddErrorPreview () {
      this.docLoadError = true
      this.fixed = true
      this.previewConfig.docinImg = []
      this.previewConfig.pageNums = this.datas.docPageSize >= 5 ? 5 : this.datas.docPageSize
      for (let i = 1; i <= this.previewConfig.pageNums; i++) {
        const ddUrl = `https://docimg1.docin.com/docinviewpic.jsp?file=${this.datas.imgId}&width=920&pageno=${i}&sview=1&clogo=1`
        this.previewConfig.docinImg.push(ddUrl)
      }
    },
    adverse () {
      // 获取广告信息
      getJyAdListApi({ codes: ['jydoc-content-right', 'jy-pc-docmember-detail'] }).then(res => {
        const resData = res.data
        if (resData && resData.error_code === 0) {
          this.jyPcDocmemberDetail = resData.data['jy-pc-docmember-detail']
          this.adsUrl = resData.data['jydoc-content-right']
        }
      })
    },
    shoucang () {
      if (!this.islogin) {
        try {
          window.openLoginDig(false, 'reload')
        } catch (e) {
          console.log(e)
        }
        return
      }
      if (this.collectd === 0) {
        getAdd({ docId: this.docIds }).then(res => {
          if (res.data.error_code === 0) {
            this.collectd = 1
            Message({
              message: '收藏成功',
              type: 'success'
            })
          }
        })
      } else {
        getRemove({ docId: this.docIds }).then(res => {
          if (res.data.error_code === 0) {
            this.collectd = 0
            Message({
              message: '取消收藏',
              type: 'warning'
            })
          }
        })
      }
    },
    continued () {
      if (!this.islogin) {
        try {
          window.openLoginDig(false, 'reload')
        } catch (e) {
          console.log(e)
        }
        return
      }
      if (this.buyed !== 1 && !this.docsInfo.docStatus && this.docsInfo.freeDownload !== 1 && this.datas.productType === 1) {
        this.downLoadFreeEvent()
      } else {
        this.loadFile()
      }
    },
    loadFile () {
      if (!this.islogin) {
        try {
          window.openLoginDig(false, 'reload')
        } catch (e) {
          console.log(e)
        }
        return
      }
      // 已下载，点击“下载文档”，调起浏览器进行文档下载。
      if (this.buyed === 1) {
        getDown({ docId: this.datas.docId }).then(res => {
          if (res.data.error_code === 0) {
            window.location.href = res.data.data
          }
        })
        return
      }
      // 判断是否是会员：不是会员进入开通剑鱼文库会员页面
      if (!this.docsInfo.docStatus > 0) {
        window.location.href = '/swordfish/page_big_pc/order/doc-member'
      } else {
        // 判断文档类型：1：会员免费文档，2：精品文档
        if (this.datas.productType === 1) {
          getDocPays({ docId: this.datas.docId, payType: 0 }).then((res) => {
            if (res.data.error_code === 0) {
              let params = {}
              // 下载特权已用尽
              if (res.data.data.status === 1) {
                params = {
                  visible: true,
                  title: '今日会员免费文档下载特权已用尽',
                  content: '建议您明日享受会员特权进行免费下载。',
                  footText: '',
                  showCancel: false,
                  confirmText: '我知道了'
                }
              } else if (res.data.data.status === 0) {
                // 下载成功，显示下载成功弹窗
                params = {
                  visible: true,
                  title: '文档下载成功',
                  content: `已添加到您的文库中，您可前往<span class="high-light">【工作台-服务-我的文库】</span>查看。`,
                  footText: `会员免费文档下载特权：消耗1篇 | 今日还剩余${res.data.data.surplus}篇`,
                  showCancel: false,
                  confirmText: '我知道了'
                }
                this.buyed = 1
                this.buyShow()
              }
              this.dialogInfo = params
            } else {
              Message({
                message: res.data.error_msg,
                type: 'warning'
              })
            }
          })
        } else {
          // 点击“下载文档”，剑鱼币余额不足，弹窗提示：
          if (this.coinNum < this.datas.price) {
            // 剑鱼币余额不足
            const params = {
              visible: true,
              title: '剑鱼币余额不足',
              content: `现有 ${this.coinNum} 剑鱼币，还需 ${this.datas.docMemberPrice - this.coinNum} 剑鱼币，请先充值`,
              footText: '',
              showCancel: true,
              confirmText: '立即充值',
              cancelText: '我再想想'
            }
            this.dialogInfo = params
          } else {
            // 点击“下载文档”，剑鱼币余额充足，进入“剑鱼币文档兑换”页，“价值剑鱼币”按照会员价进行展示兑换。
            this.$router.push('/purchase/' + this.datas.docId)
          }
        }
      }
    },
    // 原价下载
    primeLoadFile () {
      if (!this.islogin) {
        try {
          window.openLoginDig(false, 'reload')
        } catch (e) {
          console.log(e)
        }
        return
      }
      if (this.coinNum < this.datas.price) {
        // 剑鱼币余额不足
        const params = {
          visible: true,
          title: '剑鱼币余额不足',
          content: `现有 <span class="high-light">${this.coinNum}</span> 剑鱼币，还需 <span class="high-light">${this.datas.price - this.coinNum}</span> 剑鱼币，请先充值`,
          footText: '',
          showCancel: true,
          confirmText: '立即充值',
          cancelText: '我再想想'
        }
        this.dialogInfo = params
      } else {
        // 进入剑鱼币文档兑换页
        this.$router.push(`/purchase/${this.datas.docId}?payType=1`)
      }
    },
    fileType (val) {
      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">
.high-light{
  color: #2ABED1;
}
.cont-p {
  .page, .canvasWrapper, canvas {
    width: 100%!important;
    height: auto;
  }
}

</style>
<style lang="scss" scoped>
@include diy-icon('pdf', 24);
@include diy-icon('word', 24);
@include diy-icon('excel', 24);
@include diy-icon('ppt', 24);
@include diy-icon('txt', 24);
@include diy-icon('share', 18);
@include diy-icon('jubao', 18);
@include diy-icon('weiguanzhu', 18);
@include diy-icon('guanzhu', 18);
@include diy-icon('iconJianYu', 24);
.detail-main{
  width: 100%;
  background: #F2F2F4;
}
.c-details {
  position: relative;
  width: 1200px;
  display: flex;
  flex-direction: initial;
  margin: 32px auto;
  padding-bottom: 60px;
  color: #1D1D1D;

  .d-left {
    width: 920px;

    .tops {
      background: #fff;
      padding: 32px 40px;
      border-radius: 4px;

      h1 {
        display: flex;
        flex-direction: initial;
        color: #1d1d1d;
        font-weight: 500;
        font-size: 24px;
        line-height: 36px;
        margin: 0;

        i {
          display: inline-flex;
          margin-right: 8px;
          margin-top: 5px;
        }
      }

      .cd-tips {
        display: flex;
        justify-content: space-between;
        padding: 12px 0;
        margin-top: 8px;

        ul {
          display: flex;
          flex-direction: initial;
          align-items: center;
          margin: 0;
          padding: 0;

          li {
            display: flex;
            list-style-type: none;
            align-items: center;
            color: #686868;
            font-size: 14px;
            line-height: 24px;
          }

          .li-tags {
            padding: 2px 8px;
            border-radius: 4px;
            background: rgba(44, 167, 227, 0.08);
            color: #2cb7ca;
            font-size: 12px;
            line-height: 20px;
            text-align: center;
            margin-right: 8px;
          }

          .no-line {
            border-right: none !important;
          }
        }
        .type-tag {
          padding: 1px 8px 1px 8px;
          font-size: 12px;
          line-height: 18px;
          text-align: center;
          margin-right: 8px;
          border-radius: 4px;
          &.free {
            background: linear-gradient(98deg, #FFA674 0%, #F01212 100%);
            color: #fff;
          }
          &.boutique{
            background: linear-gradient(270deg, #F1D090 0%, #FAE7CA 100%);
            color: #B1700E;
          }
        }
        .coin {
          display: flex;
          align-items: center;

          span {
            font-size: 20px;
            color: #FF3A20;
          }
        }
      }

      .buyed {
        height: 24px;
        color: #2CB7CA;
        background: rgba(44, 183, 202, 0.05);
        font-size: 12px;
        line-height: 24px;
        text-align: center;
        border-radius: 4px;
        margin: 10px 0 8px 0;
      }

      .no-buyed {
        background: rgba(255, 58, 32, 0.05) !important;
        color: rgb(255, 58, 32) !important;
      }

      .heng-line {
        margin: 8px 0;
        background-color: #ECECEC;
      }

      .load-doc {
        height: 69px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        ::v-deep .el-button {
          min-width: 180px;
          height: 46px;
          // padding: 7px 34px 8px 34px;
          border-radius: 8px;
          background-color: #2CB7CA;
          border-color: #2CB7CA;
          &.prime-cost{
            padding: 0;
            background-color: #fff;
            &>span{
              display: flex;
              flex-direction: column;
              font-size: 16px;
              &>span{
                line-height: 24px;
                color: #2ABED1;
              }
              &>span:last-child {
                font-size: 14px;
                line-height: 18px;
              }
            }
            &.origin-cost{
              &>span{
                flex-direction: row;
                justify-content: center;
                align-items: center;
                &>span{
                  font-size: 18px;
                  color: #FF3A20;
                }
                &>span:last-child {
                  margin-left: 12px;
                  font-size: 16px;
                  color: #2ABED1;
                }
              }

            }
          }
          span {
            color: #fff;
            font-size: 16px;
          }
        }
        .file-action{
          &-content{
            display: flex;
            align-items: center;
            .file-download{
              font-size: 16px;
              color: #2ABED1;
            }
            .coin{
              display: flex;
              align-items: center;
              color: #999999;
              font-size: 14px;
              &.after-coin {
                margin-left: 16px;
                font-size: 14px;
                color: #1D1D1D;
                .el-icon-jy-iconJianYu{
                  width: 26px;
                  height: 26px;
                }
              }
            }
            .member-mark{
              margin-left: 16px;
              font-size: 24px;
              color: #FF3A20;
            }
          }
        }

        .icons {
          color: rgba(104, 104, 104, 1);
          font-size: 14px;

          span {
            display: inline-flex;
            align-items: center;
          }

          .spa2 {
            margin-left: 16px;
            margin-right: 16px;
            cursor: pointer;
          }

          .spa1 {
            i {
              height: 18px;
              margin-right: 5px;
            }
          }
        }
      }
    }

    .middles, .bottoms-preview {
      padding: 24px 0;
      background: #fff;
      border-radius: 4px;
      margin: 16px 0;
      position: relative;

      h3 {
        font-size: 18px;
        line-height: 28px;
        font-weight: 500;
      }

      p {
        color: #686868;
        font-size: 14px;
        line-height: 22px;
        margin-top: 16px;
        text-align: justify;
      }

      .continue {
        position: absolute;
        width: 100%;
        height: 400px;
        color: #686868;
        font-size: 16px;
        line-height: 24px;
        display: flex;
        align-items: flex-end;
        justify-content: center;
        padding-bottom: 27px;
        background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, #fff 75%);
        bottom: 24px;
        left:0;

        span {
          color: #2CB7CA;
          cursor: pointer;

          i {
            margin-left: 7px;
          }
        }
      }
    }
    .middles.middles-summary{
      padding: 24px 40px;
      .continue {
        position: unset;
        height: unset;
        color: #686868;
        margin-top: 36px;
      }
    }
    .actives {
      // height: 656px;
      padding: 24px 40px 48px;
    }

    .actives1 {
      height: 680px;
    }

    .head-tip {
      width: auto;
      height: 42px;
      line-height: 42px;
      background: #fcfcfc;
      padding: 0 40px;
      border-bottom: 1px solid #F2F2F4;

      h3 {
        float: left;
        line-height: 42px;

        span {
          width: 700px;
          color: #686868;
          font-weight: 500;
          font-size: 16px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        i {
          margin-right: 8px;
          vertical-align: middle;
        }
      }

      .pages {
        float: right;
        color: #686868;
        font-size: 14px;

        i:first-child {
          display: inline-block;
          font-style: normal;
          width: 22px;
          height: 22px;
          line-height: 24px;
          text-align: center;
          border-radius: 2px;
          background: #FFFFFF;
          border: 1px solid #ECECEC;
        }
      }
    }

    .is-fixed {
      position: fixed;
      top: 0;
      width: 920px;
    }
    .bottoms-preview{
      padding: 24px 0;
      background: #fff;
      border-radius: 4px;
      margin: 16px 0;
    }
    .bottoms {
      // position: fixed;
      // bottom: 0;
      display: flex;
      flex-direction: column;

      .page {
        .cont-p {
          display: flex;
          flex-direction: column;
          align-items: center;
          background: #fff;
          // padding: 24px 40px 32px;
        }
        ::v-deep {
          .docx-wrapper {
            padding: 0;
            background: #fff;
          }
          .vue-office-docx .docx-wrapper>section.docx{
            width: 100%!important;
          }
        }
      }

      .foot-tip {
        width: 920px;
        height: auto;
        background: #FFFFFF;
        box-shadow: 0px 0px 28px 0px rgba(0, 0, 0, 0.08);
        padding: 0;
        border-radius: 0;
        z-index: 99;
        .member-time-tip{
          position: relative;
          display: flex;
          align-items: center;
          padding: 9px 0 9px 24px;
          font-size: 14px;
          color: #FF3A20;
          line-height: 22px;
          background-color: #FFECE9;
          .warn-icon{
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 8px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            font-size: 14px;
            color: #fff;
            background: #F56500;
          }
        }
        .time-tip-close{
          position: absolute;
          right: 24px;
          top: 11px;
          cursor: pointer;
          font-size: 18px;
          color: #AAAAAA;
        }
        .doc-detail-ad{
          position: relative;
          width: 920px;
          height: 64px;
          .doc-detail-ad-img{
            height: 100%;
          }
          img{
            width: 100%;
            height: 100%;
          }
          .time-tip-close{
            color: #fff;
          }
        }
        .load-doc {
          height: 68px;
          padding: 0 40px;
          // justify-content: flex-end;

          .spa2 {
            cursor: pointer;
          }

          button {
            margin-left: 24px;
          }
        }
      }
    }
  }

  .d-right {
    width: 264px;
    height: 904px;
    margin-left: 16px;

    // position: fixed;
    .r-tops {
      overflow: hidden;
      min-height: 456px;
      border-radius: 4px;

      img {
        width: 100%;
        cursor: pointer;
      }

      img:not(:last-child) {
        margin-bottom: 5px;
      }
    }
  }
}

::v-deep {
  .page:not(:first-of-type) {
    border-top: 6px solid #f2f2f2;
  }
}
.preview-content {
  img:not(:first-of-type) {
    border-top: 6px solid #f2f2f2;
  }
}

</style>
