<template>
  <div class="all" style="margin-top: 10px;margin-right: 10px;margin-left: 10px;overflow: auto">
    <Row style="height: 820px;" type="flex">
      <Col :span="5" order="1">
        <Card style="width: 95%;" v-if="getFileWay==='scanning'">
          <p slot="title">
            <Icon type="ios-film-outline"></Icon>
            文件列表
          </p>
          <Collapse simple>
            <Panel v-for="(directory, index) in catalogList" :name="index+''" :key="`directory_${index}`">
              {{directory.name}}
              <ul slot="content">
                <li v-for="(file, index1) in directory.children" @click.prevent="loadPdf(file)" :key="`file_${index1}`">
                  {{file.name}}
                </li>
              </ul>
            </Panel>
          </Collapse>
        </Card>
      </Col>
      <Col :span="14" order="2">
        <Row style="text-align: center;margin-bottom: 5px;">
          纸张类型:
          <Select v-model="MyPageSizeType" style="width: 100px;margin-right: 5px;">
            <Option :value="9">A4</Option>
            <Option :value="10">A4小</Option>
            <Option :value="8">A3</Option>
            <!--<Option :value="11">A5</Option>-->
            <Option :value="12">B4</Option>
            <Option :value="13">B5</Option>
            <Option :value="29">信封纸C3</Option>
            <Option :value="30">信封纸C4</Option>
            <Option :value="28">信封纸C5</Option>
          </Select>
          打印方向:
          <Select v-model="MyPageOrientationType" style="width: 80px;margin-right: 5px;">
            <Option :value="1">纵向</Option>
            <Option :value="0">横向</Option>
          </Select>
          <Tooltip content="开启后将无视纸张类型与打印方向,自动进行尺寸调整!" max-width="200" transfer>
            <Checkbox v-model="onePagePerSheet" border>自适应大小</Checkbox>
          </Tooltip>
          <Button type="primary" size="small" @click="loadPdf()" ghost style="margin-right: 5px">转换</Button>
          <Button type="primary" size="small" @click="scaleD" ghost style="margin-right: 5px">放大</Button>
          <Button type="primary" size="small" @click="scaleX" ghost style="margin-right: 5px">缩小</Button>
          <Button type="primary" size="small" @click="changePdfPage(0)" ghost style="margin-right: 5px">上一页</Button>
          {{currentPage}} / {{pageCount}}
          <Button type="primary" size="small" @click="changePdfPage(1)" ghost style="margin-right: 5px">下一页</Button>
          <Button type="primary" @click="$refs.wrapper.print()" style="margin-right: 5px">打印</Button>
          <Dropdown @on-click="downClick" style="margin: 0px 10px;">
            <Button type="success" @click="" style="margin-right: 5px">下载<Icon type="md-arrow-dropdown"/></Button>
            <DropdownMenu slot="list">
              <DropdownItem  name="downPdf">PDF格式</DropdownItem>
              <DropdownItem  name="downOriginal">原文件格式</DropdownItem>
            </DropdownMenu>
          </Dropdown>

        </Row>
        <div class="main" @contextmenu.prevent="preventContextmenu" id="pdf-div" :style="pdfDivStyle">
          <pdf :src="pdfFileUrl" :page="currentPage"
               progress="loadedRatio = $event" @num-pages="pageCount=$event" @page-loaded="currentPage=$event"
               @loaded="loadPdfHandler" ref="wrapper" class="pdf"></pdf>
          <!-- 在没使用trigger = 'custom'时, 组件会响应document的菜单事件 -->
          <Contextmenu
            :containerId="'pdf-div'"
            :menu-data="menuData"
            @on-select="handleSelect"
            @on-cancel="handleCancel"
            @on-position="handlePosition"
          ></Contextmenu>
        </div>
      </Col>
      <Col :span="5" order="3">
        <Tabs ref="tabs_sign" v-model="tabName" type="card" style="width: 95%;float: right;">
          <TabPane v-if="operationType === 'sign'" label="文件签署" name="1">
            <Card>
              <p style="background-color: #519cf1;color: #ebebeb">我的电子印章</p>
              <Row style="margin-top: 20px;">
                <Col :span="11" v-for="(seal, index) in sealList" :key="`seal_${index}`"
                     style="margin-left: 5px;margin-bottom: 5px;">
                  <Card :padding="5"
                        :style="selectedSeal.id===seal.id?'border-color: red;cursor: pointer;':'cursor: pointer;'">
                    <img :src="seal.srcFileStr" width="120" height="120" @click="selectSeal(seal)"/>
                  </Card>
                </Col>
              </Row>
            </Card>
            <Card>
              <p style="background-color: #519cf1;color: #ebebeb">签署日期</p>
              <Row style="margin-top: 20px;">
                <Col span="12">
                  <DatePicker type="date" :options="options3" format="yyyy年MM月dd日" style="width: 200px"
                              :value="signDate"></DatePicker>
                </Col>
              </Row>
            </Card>
          </TabPane>
          <TabPane label="签署状态" name="2">
            <Timeline style="margin-top: 30px;margin-left: 30px;">
              <TimelineItem v-for="signRecord in signList" :key="signRecord.id">
                <p class="version">{{signRecord.companyName}}</p>
                <p class="time">{{signRecord.recordUserName}}--{{signRecord.useTime}}</p>
                <p class="content">
                  <Button v-if="signRecord.state === 1" type="success" size="small">已签署</Button>
                  <Button v-if="signRecord.state === 2" type="success" size="small">签署异常</Button>
                </p>
              </TimelineItem>
              <TimelineItem>
                <p class="version">{{this.$store.state.user.userName}}</p>
                <p class="time">当前</p>
                <p class="content">
                  <Button type="error" size="small">签署中</Button>
                </p>
              </TimelineItem>
              <!--<TimelineItem>
                <p class="version">长沙博矗软件技术</p>
                <p class="time">&#45;&#45;</p>
                <p class="content"><Button type="primary" size="small"  disabled>未签署</Button></p>
              </TimelineItem>-->
            </Timeline>
          </TabPane>
        </Tabs>
      </Col>
    </Row>
  </div>
</template>

<script>
  /*import pdfjsLib from 'pdfjs-dist'*/
  import pdf from 'vue-pdf'
  import {getCatalog, getSeal, doSign, getSignRecord, transferFile} from './pdf-api.js'
  import Contextmenu from './right-click-menu/Contextmenu.vue'
  import Cookies from 'js-cookie'
  import {getToken}from '../../bc-libs/token-util.js'

  let moment = require("moment");
  let $this;
  const pdfDivWidth = 1098, pdfDivHeight = 1552
  export default {
    name: 'pdfView',
    components: {
      pdf,
      Contextmenu,
    },
    props: {
      getFileWay: {//获取文件的途径  assignation-指定路径  scanning-目录下扫描
        type: String,
        default: Cookies.get('getFileWay') ? Cookies.get('getFileWay') : 'assignation'
      },
      workflowId: {//流程的id
        type: String,
        default: Cookies.get('workflowId') ? Cookies.get('workflowId') : ''
      },
      businessCode: {//业务类型的code
        type: String,
        default: Cookies.get('businessCode') ? Cookies.get('businessCode') : ''
      },
      rootPath: {//主目录,默认是 /usr/local/data/ 如果需要自己指定根目录,就传入此参数
        type: String,
        default: Cookies.get('rootPath') ? Cookies.get('rootPath') : ''
      },
      //↑↑↑↑↑以上是不指定文件的情况下需要传入的参数,需要扫描目录进行展示,需要有左边的目录栏↑↑↑↑↑↑↑
      fileName: {//文件名称
        type: String,
        default: Cookies.get('fileName') ? Cookies.get('fileName') : ''
      },
      filePath: {//文件路径,如果指定了文件路径传入的参数
        type: String,
        default: Cookies.get('filePath') ? Cookies.get('filePath') : ''
      },
      //↑↑↑↑↑以上是指定文件的情况下需要传入的参数,不会去扫描目录.而是直接展示指定的文件,不会有左边的目录栏↑↑↑↑↑↑↑
      fdfsId: {//文件类型过滤.如果想只展示某些类型的文件,就可以传入此参数,参数值是文件后缀.
        type: String,
        default: () => {
          return Cookies.get('fdfsId') ? Cookies.get('fdfsId') : ''
        }
      },
      //↑↑↑↑↑以上是采用分布式文件存储情况下需要传入的参数,不会去扫描目录.而是通过fdfs远程获取原文件,直接转换并展示,不会有左边的目录栏↑↑↑↑↑↑↑
      fileTypeFilter: {//文件类型过滤.如果想只展示某些类型的文件,就可以传入此参数,参数值是文件后缀.
        type: Array,
        default: () => {
          return Cookies.get('fileTypeFilter') ? Cookies.get('fileTypeFilter') : []
        }
      },
      operationType: {//操作类型,默认是  签章-sign  预览打印-previewAndPrint
        type: String,
        default: Cookies.get('operationType') ? Cookies.get('operationType') : 'sign'
      },
      pageOrientationType: {//纸张打印方向,默认纵向  PORTRAIT-纵向 LANDSCAPE-横向
        type: Number,
        default: Cookies.get('pageOrientationType') ? Cookies.get('pageOrientationType') : 1
      },
      pageSizeType: {//pdf纸张的大小类型  A4 A5 A6 等等,直接传到后台,去匹配常量
        type: Number,
        default: Cookies.get('pageSizeType') ? Cookies.get('pageSizeType') : 9
      },
    },
    data() {
      return {
        onePagePerSheet: true,
        MyPageOrientationType: null,
        MyPageSizeType: null,
        pdfDivStyle: 'width: ' + pdfDivWidth + 'px;height: ' + pdfDivHeight + 'px;',
        uuid: (new Date()).valueOf(),//标识符,用来刷新pdf预览地址, 否则参数一样是不会重新访问的
        pageSizes: {9: [595, 842]}, //具体每个纸张类型的长和宽集合 [宽,长]
        signLoading: false,//签章进行时的加载状态
        selectedSeal: {},//当前选择的印章
        //businessCode: 'gwbd-zg',//当前所属的业务类型编码
        //type: 'sign',//当前页面操作类型 签章与浏览
        tabName: '2',//标签页的标识
        pageCount: 0,//pdf页面数量
        currentPage: 0,//当前所在页
        scale: 100, //放大系数
        idx: -1,
        clauseTitle: "",
        loadedRatio: 0,
        pdfFileUrl: '',//当前pdf文件完整请求地址
        nowFileName: '',//当前pdf文件名称
        nowFilePath: '',//当前pdf文件路径
        catalogList: [],//左侧栏的目录
        sealList: [],//右侧印章列表
        signList: [],//签章记录列表
        options3: {
          disabledDate(date) {
            return date && date.valueOf() < Date.now() - 86400000;
          }
        },
        signDate: moment(new Date()).format('YYYY-MM-DD'),//签章日期
        menuData: [
          {
            title: '定位签章',
            name: 'do_sign',
            shortcut: ''
          },
          {
            title: '撤销签章',
            name: 'undo_sign',
            shortcut: ''
          },
          {
            title: '批量签章',
            name: 'batch_sign',
            divided: true,
            disabled: true
          }
        ],//右键菜单内容
        nowOffsetX: 0,//当前鼠标距离pdf左边界的距离
        nowOffsetY: 0,//当前鼠标距离pdf上边界的距离
      }
    },
    methods: {
      // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
      changePdfPage(val) {
        if (val === 0 && this.currentPage > 1) {
          this.currentPage--;
        }
        if (val === 1 && this.currentPage < this.pageCount) {
          this.currentPage++;
        }
      },
      goBack() {
        this.$router.go(-1);
      },
      // pdf加载时
      loadPdfHandler(e) {
        this.currentPage = 1; // 加载的时候先加载第一页
      },
      //放大
      scaleD() {
        this.scale += 5;
        // this.$refs.wrapper.$el.style.transform = "scale(" + this.scale + ")";
        this.$refs.wrapper.$el.style.width = parseInt(this.scale) + "%";
      },
      //缩小
      scaleX() {
        if (this.scale == 50) {//原来是100
          return;
        }
        this.scale += -5;
        this.$refs.wrapper.$el.style.width = parseInt(this.scale) + "%";
        // this.$refs.wrapper.$el.style.transform = "scale(" + this.scale + ")";
      },
      //获取指定流程的文档目录
      loadCatalog() {
        let params = {};
        getCatalog(params).then(res => {
          this.catalogList = res.data.result;
        }).catch(err => {
          this.catalogList = [];
          this.$Message.error('查询失败！')
          console.log(err)
        })
      },
      //点击目录触发加载pdf
      loadPdf(file) {
        //刷新uuid,重新访问pdf
        this.uuid = (new Date()).valueOf();
        if (file) {
          this.nowFilePath = encodeURI(file.path);
        }
        this.pdfFileUrl = '/api/v1/base/pdf/excel/byLoginUser'
          + '?access_token=' + getToken()
          + '&name=' + this.nowFileName + '&path=' + this.nowFilePath
          + '&pageOrientationType=' + this.MyPageOrientationType + '&pageSizeType=' + this.MyPageSizeType
          + '&onePagePerSheet=' + this.onePagePerSheet
          + '#' + this.uuid
        //pdf文件加载完成后,就加载签章记录
        //this.loadSignRecord(file)//展示隐藏
      },
      //点击目录触发加载pdf
      downPdf(type) {
        //刷新uuid,重新访问pdf
        this.uuid = (new Date()).valueOf();
        window.location.href = '/api/v1/base/pdf/down/byFilePath'
          + '?access_token=' + getToken()
          + '&path=' + this.nowFilePath + '&type=' + type
          + '&pageOrientationType=' + this.MyPageOrientationType + '&pageSizeType=' + this.MyPageSizeType
          + '&onePagePerSheet=' + this.onePagePerSheet
          + '#' + this.uuid
      },
      //加载签章记录
      loadSignRecord() {
        let params = {fileName: this.nowFileName};
        getSignRecord(params).then(res => {
          this.signList = res.data.result;
        }).catch(err => {
          this.signList = [];
          this.$Message.error('查询失败！')
          console.log(err)
        })
      },
      //选择操作的印章触发
      selectSeal(seal) {
        this.selectedSeal = seal
      },
      //----------------------------------------------------------右键菜单回调----------------------------------------------//
      //----------------------------------------------------------右键菜单回调----------------------------------------------//
      //----------------------------------------------------------右键菜单回调----------------------------------------------//
      handleSelect(name) {
        //console.log(`选择了菜单: ${name}`)
        //根据选择的不同,进行不同的操作
        let opType
        if (name === 'do_sign') {//选择了签章
          opType = 'sign'
        } else if (name === 'undo_sign') {//选择了撤章
          opType = 'unSign'
        }
        //判断是否选择了印章
        if ((!this.selectedSeal.id) && opType === 'sign') {
          this.$Message.warning("请先选择需要签署的印章!")
          return false;
        }
        //显示签章状态
        this.signLoading = true
        //根据选择的纸张大写来换算签章位置
        let width = this.pageSizes[this.MyPageSizeType][0]//所选纸张的宽
        let height = this.pageSizes[this.MyPageSizeType][1]//所选纸张的长
        let offsetX = this.nowOffsetX * width / pdfDivWidth //实际上偏移的宽度
        let offsetY = height - (this.nowOffsetY * height / pdfDivHeight) //实际上偏移的高度,距离底部的位置
        let params = {
          fileName: this.nowFileName, filePath: this.nowFilePath,
          offsetX: offsetX, offsetY: offsetY, sealId: this.selectedSeal.id, opType: opType
        }
        doSign(params).then(data => {
          this.signLoading = false
          if (!data.status) {
            this.$Message.error(data.error.message)
            console.log(data)
            return false
          }
          this.$Message.success('操作成功！')
          this.loadPdf();
        }).catch(err => {
          this.$Message.error('操作失败！')
          this.signLoading = false
          console.log(err)
        })

      },
      handleCancel() {
        console.log('取消了右键菜单')
      },
      preventContextmenu() {
        return false
      },
      handlePosition(e) {
        //console.log(e.clientX +'---client---'+e.clientY)
        //console.log(e.layerX +'---layer---'+e.layerY)
        //console.log(e.movementX +'---movement---'+e.movementY)
        console.log(e.offsetX + '---offset---' + e.offsetY)
        //console.log(e.screenX +'---screen---'+e.screenY)
        //console.log(e.pageX +'---page---'+e.pageY)
        //console.log(e.x +'---xy---'+e.y)
        this.nowOffsetX = e.offsetX
        this.nowOffsetY = e.offsetY
      },
      //下载文件触发事件
      downClick(name) {
        if (!this.nowFilePath){
          this.$Message.warning('请先选择要下载的文件！')
          return false
        }
        switch (name) {
          case 'downPdf':
            this.downPdf('pdf')
            break
          case 'downOriginal':
            this.downPdf('original')
            break
        }
      },
    },
    mounted() {
      $this = this;
      //如果获取文件的途径是扫描,就走扫描初始化的方法,否则就走指定路径的方法
      if (this.getFileWay === 'scanning') {
        this.loadCatalog();
      }
      //如果是分布式存储,那就要获取转移到签章服务后的地址
      else if (this.fdfsId && this.fdfsId !== '') {
        transferFile({fdfsId: this.fdfsId}).then(res => {
          this.fileName = res.fileName;
          this.filePath = res.filePath;
          this.loadPdf({name: this.fileName, path: this.filePath})
        }).catch(err => {
          this.$Message.error('查询失败！')
          console.log(err)
        })
      }
      //如果是指定路径,那就直接按照指定的路径访问就可以
      else if (this.filePath && this.filePath !== '') {
        this.loadPdf({name: this.fileName, path: this.filePath})
      }
      //如果是签署操作,就取查询此人拥有的电子印章
      if (this.operationType === 'sign') {
        getSeal({businessCode: this.businessCode}).then(res => {
          this.sealList = res.data.result;
        }).catch(err => {
          this.sealList = [];
          this.$Message.error('查询失败！')
          console.log(err)
        })
      }
      //初始化方向与纸张大小参数
      this.MyPageOrientationType = this.pageOrientationType
      this.MyPageSizeType = this.pageSizeType
    },
    created() {

    }
  }
</script>

<style lang="less" scoped>
  .version {
    font-size: 20px;
    font-weight: bold;
  }

  .time {
    color: #fa795e;
    font-weight: bold;
  }

  .content {
    padding-left: 5px;
  }
</style>
