<template>
  <div class="page">
    <Loading :loading="loading" />
    <div v-show="!loading">
      <van-image-preview v-model="vshowList" :images="detailData.imageFiles" :start-position='0' @change="onChange"
                         @scale='onScale' @close='onClose' ref='imagePreview'>
        <template v-slot:index>
          <div>
            第{{curPage}}页
          </div>
        </template>
        <template v-slot:cover v-if="showBottom">
          <div class="pdf-cover-bottom">
            <input class="pdf-barinputL" ref='pdfInput' type="number" id="spinner_amount" :value="curPage"
                   @input="pdfInput" />
            <!-- oninput="" -->
            <div class="pdf-barinputR">/{{ detailData.imageFiles.length}}</div>
          </div>
        </template>
      </van-image-preview>
      <div v-show="!vshowList" class="jurisdiction">
        <van-image :src="require('../../../static/images/icon_jurisdiction.png')" />
        <div>{{nomessage}}</div>
      </div>
    </div>
  </div>
</template>

<script>
import * as dd from 'dingtalk-jsapi';
import Loading from '@/components/Loading';
import {
  ImagePreview
} from 'vant';
export default {
  name: 'page',
  data() {
    return {
      nomessage: '',
      vshowList: false,
      pdfFile: null,
      loading: true,
      curPage: 1,
      curPage2: 1,
      totals: 0,
      scale: 2,
      show: true,
      detailData: null,
      showBottom: false,
      timeCountId: null,
    }
  },
  watch: {
    vshowList(nval, oval) {
      if (oval && !nval) {
        this.vshowList = true;
      }
    }
  },
  created() {
    if (this.$route.query.path) {
      this.loadPdfHandler(this.$route.query.path);
    }

    if (this.$route.query.title) {
      this.ChangePageTitle(this.$route.query.title)
    }
    if (this.$route.query.id) {
      this.loading = true;
      this.getDetail();
    } else {
      // this.loadPdfHandler('http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf');
      this.loading = false;
    }

    if (dd.env.platform != 'notInDingTalk') {
      dd.biz.navigation.setRight({
        show: false, //控制按钮显示， true 显示， false 隐藏， 默认true
        control: false, //是否控制点击事件，true 控制，false 不控制， 默认false
        showIcon: false, //是否显示icon，true 显示， false 不显示，默认true； 注：具体UI以客户端为准
        onSuccess: () => {},
        onFail: function (err) {
          alert('dd error: ' + JSON.stringify(err));
        }
      });

    }
  },
  destroyed() {
    this.clearTimeCount();
  },
  components: {
    Loading,
    [ImagePreview.Component.name]: ImagePreview.Component,
  },
  methods: {
    // pdf加载时
    loadPdfHandler(path) {
      this.$nextTick(() => {
        this.$refs.canvas.src = path
        this.$refs.canvas.start();
      });
    },
    // 获取详情
    getDetail() {
      let self = this;

      this.$api.user.getDetail(this.$route.query.id, localStorage.userId || '').then((response) => {
        const res = response.data.data;
        this.loading = false;
        if (res.code == 0 && res.data) {
          this.detailData = res.data;
          this.vshowList = true;
          this.$nextTick(() => {
            this.showBottom = true
          })
          // let path = res.data.path || ''
          // self.loadPdfHandler(path);
          // self.loadPdfHandler("http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf");
          self.ChangePageTitle(res.data.fileName);
        } else if (res.code == 1000) { //没有查看权限
          this.vshowList = false;
          this.nomessage = res.message
        }
      }).catch(err => {
        console.log(err)
        self.loading = false;
      });
    },
    // 修改页面标题
    ChangePageTitle(title) {
      if (dd.env.platform != 'notInDingTalk') {
        dd.ready(function () {
          dd.biz.navigation.setTitle({
            title: title, //控制标题文本，空字符串表示显示默认文本
            onSuccess: function (result) {
              console.log(result);
            },
            onFail: function (err) {
              console.log(err);
            }
          });
        });
      } else {
        document.title = title
      }
    },
    // 缩放
    onScale() {
      document.getElementById("spinner_amount").blur();
    },
    // 关闭
    onClose() {
      document.getElementById("spinner_amount").blur();
    },
    // 页面切换
    onChange(val) {
      this.curPage = val + 1;
      document.getElementById("spinner_amount").blur();
    },
    // 开始输入计时
    startTimeCount(f) {
      this.clearTimeCount();
      this.timeCountId = setTimeout(() => {
        f();
      }, 700)
    },
    // 清除输入计时
    clearTimeCount() {
      if (this.timeCountId) {
        clearTimeout(this.timeCountId);
        this.timeCountId = null;
      }
    },
    // 页码输入
    pdfInput(e) {
      let value = e.target.value;
      if (value) {
        value = value.replace(/[^\d]/g, '')
      }
      this.curPage = value;
      this.startTimeCount(() => {
        if (!value) {
          this.jumpPage(0);
        } else if (parseInt(value) > parseInt(this.detailData.imageFiles.length)) {
          this.jumpPage(this.detailData.imageFiles.length);
        } else {
          this.jumpPage(value)
        }
      })
    },
    // 输入框失去焦点
    pdfInputBlur() {
      let spinner = document.getElementById('spinner_amount');
      let val = spinner.valueAsNumber
      if (val) {
        if (this.detailData.imageFiles.length < val) {
          val = this.detailData.imageFiles.length;
          spinner.valueAsNumber = this.detailData.imageFiles.length;
        }
        this.jumpPage(val);
      } else {
        spinner.valueAsNumber = this.curPage
      }
    },
    // 切换页面
    jumpPage(val) {
      console.log(val)
      if (0 < val && val <= this.detailData.imageFiles.length) {
        this.curPage = val;
        this.$refs.imagePreview.swipeTo(val - 1);
      }
    },
  }
}
</script>

<style scoped>
.jurisdiction {
  margin: 10px;
  margin-top: 10vh;
  text-align: center;
  font-size: 17px;
  color: #17a8ff;
  opacity: 1;
}

.pdf-cover-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  padding: 20px 10px;
}

.pdf-barinputL {
  width: 40px;
  height: 20px;
  text-align: center;
}

.pdf-barinputR {
  margin-left: 5px;
  text-align: center;
}

.pdf-jump-button {
  position: absolute;
  top: 50%;
  right: 30px;
  transform: translateY(-50%);
  border-radius: 5px;
  background: #17a8ff;
  color: #fff;
}
</style>