/**
* @Author Sean
* @Date 2019/5/13
*/
<template>
  <transition name="slide-fade">
    <div ref="signModal" class="sign-modal" @click="hideModal">
      <div class="pane" @click.stop>
        <div class="layout">
          <div id="data" @click="confirmData()">确定</div>
          <div id="clear" @click="cleanData()">清除</div>
        </div>
        <div id="draw" class="draw">
          <div id="sig" class="sig">
            <canvas
              id="canvas"
              @mousedown="beginDraw"
              @mouseup="endDraw"
              @mousemove="drawing"
              @touchstart="beginDraw"
              @touchend="endDraw"
              @touchmove="drawing"
            />
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
  export default {
    props: {
      info: {
        type: Object,
        default: function () {
          return { }
        },
      },
    },
    data () {
      return {
        image_base64: '',
        canvas: {},
        context: {},
        height: '',
        hasSignature: false,
        last: null,
        config: {
          strokeStyle: '#ff0000',
          lineWidth: 3,
        },
        mousePress: false,
      }
    },
    created: function () {
      // console.log(this.timeInfo)
    },
    mounted: function () {
      this.canvas = document.getElementById('canvas')
      this.context = this.canvas.getContext('2d')
      if (window.innerHeight > window.innerWidth) {
        this.height = window.innerHeight / 2 + 50
        this.resizeCanvas(window.innerWidth, window.innerHeight / 2 - 50)
      } else {
        this.resizeCanvas(window.innerWidth, window.innerHeight - 50)
        this.height = window.innerHeight + 50
      }
    },
    methods: {
      hideModal () {
        this.$emit('closeModal')
      },
      cleanData () {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
        this.hasSignature = false
      },
      beginDraw (e) {
        this.mousePress = true
      },
      endDraw (e) {
        this.mousePress = false
        e.preventDefault()
        this.last = null
      },
      drawing (e) {
        e.preventDefault()
        if (!this.hasSignature) {
          this.hasSignature = true
        }
        if (!this.mousePress) {
          return
        }
        let xy = this.getCoordinate(e)
        if (this.last !== null) {
          this.context.beginPath()
          this.context.moveTo(this.last.x, this.last.y)
          this.context.lineTo(xy.x, xy.y)
          this.context.stroke()
        }
        // 开始移动，将坐标赋值给last。那么下次再移动就会通过上面的操作从上一个xy移动到当前的xy处
        this.last = xy
      },
      getCoordinate (e) {
        let x, y
        if (this.isTouch(e)) {
          x = e.touches[0].pageX // 修改
          y = e.touches[0].pageY - this.height
        } else {
          x = e.offsetX + e.target.offsetLeft
          y = e.offsetY + e.target.offsetTop + this.height
          // return false;
        }
        return {
          x: x,
          y: y,
        }
      },
      /**
       * 重置画布操作
       * @param {*} w 画布宽
       * @param {*} h 画布高
       */
      resizeCanvas (w, h) {
        let nc = this.canvas
        this.canvas.width = w
        this.canvas.height = h
        this.context.strokeStyle = this.config.strokeStyle
        this.context.lineWidth = this.config.lineWidth
        this.context.drawImage(nc, 0, 0, w, h, 0, 0, w, h)
      },
      isTouch (e) {
        let type = e.type
        if (type.indexOf('touch') >= 0) {
          return true
        } else {
          return false
        }
      },
      // 确认签名
      confirmData () {
        let vm = this
        if (!this.hasSignature) {
          vm.hlsPopup.showLongCenter('未创建签名!')
        } else {
          vm.hideModal()
          let canvas = document.getElementById('canvas')
          let canvasData = canvas.toDataURL('image/png')
          vm.image_base64 = canvasData.split(',')[1]
          vm.hlsPopup.showLoading('正在签名请稍等!')
          // 先创建账号
          let url = process.env.rootPath + '/app/sign/register'
          let param = {
            idNo: vm.info.id_number,
            name: vm.info.name,
          }
          vm.$post(url, param).then(function (res) {
            if (!res.success) {
              // 如果成功进行签名
              let fileName = '测试e签宝' + '-盖章.pdf'
              vm.getSignPdf(vm.info.name, vm.info.id_number, vm.image_base64, '', '', '', fileName, '', 'BOTH')
            } else {
              vm.hlsPopup.hideLoading()
              vm.hlsPopup.showPopup('', '签名失败请返回重试', function () {
                // window.history.go(-1)
              })
            }
          })
        }
      },
      getSignPdf (name, idNo, imgData, tableName, tablePkValue, attachmentId, fileName, userId, signType) {
        let vm = this
        let userPages = []
        let selfPages = []
        if (signType === 'BOTH') {
          userPages = [
            { page: '1', x: 510, y: 250 },
            { page: '4', x: 445, y: 165 },
          ]
          selfPages = [
            { page: '1', x: 200, y: 250 },
            { page: '4', x: 120, y: 165 },
          ]
        } else {
          userPages = [
            { page: '1', x: 505, y: 205 },
            { page: '2', x: 105, y: 230 },
          ]
        }
        let url = process.env.rootPath + '/app/sign/pdf'
        let param = {
          idNo: idNo,
          name: name,
          userPages: userPages,
          selfPages: selfPages,
          attachmentInfo: {
            downloadApiName: 'attment_view',
            downloadSysName: 'HLS_APP',
            attachmentId: 6,
            uploadApiName: 'attachment_upload',
            uploadSysName: 'HLS_APP',
            userId: 1,
            sourceType: 'HLS_DOC_FILE_TEMPLET',
            pkValue: 42,
            fileName: fileName,
          },
          personArea: 0,
          sealData: imgData,
        }
        vm.$post(url, param).then(function (res) {
          vm.hlsPopup.hideLoading()
          if (res.success) {
            vm.hlsPopup.showConfirm({
              title: '签名成功',
              content: '是否预览合同',
              onConfirm: function (index) {
                if (index === 1) {
                  // 签名合同预览
                  vm.PDF(parseInt(res.message))
                }
              },
            })
          } else {
            vm.hlsPopup.hideLoading()
            vm.hlsPopup.showLongCenter('签名失败请重试')
          }
        })
      },
      // pdf转图片预览
      PDF (attachmentId) {
        let vm = this
        vm.hlsPopup.showLoading('正在预览请稍等!')
        let url = process.env.rootPath + '/app/pdf/png?sysName=HLS_APP&apiName=attment_view&attachment_id=' + attachmentId
        let param = {}
        vm.$post(url, param).then(function (res) {
          if (res.success) {
            let length = res.message
            // PDF装图片数组
            let pirtureList = []
            for (let i = 0; i < length; i++) {
              pirtureList.push({
                pic: process.env.file_url + 'esign/' + attachmentId + '/temp/' + 'temp_' + (i + 1) + '.png',
              })
            }
            vm.hlsPopup.hideLoading()
            vm.alpviewimg(pirtureList)
          } else {
            vm.hlsPopup.hideLoading()
            vm.hlsPopup.showLongCenter('预览文件失败')
          }
        })
      },
      alpviewimg (pirtureList) {
        this.$router.push({
          name: 'EsignPicture',
          params: {
            pirtureList: pirtureList,
          },
        })
      },
    },
  }
</script>

<style scoped lang="less" rel="stylesheet">
  /* //name="modal-fade"
     .modal-fade-enter, .modal-fade-leave-active { opacity: 0; } .modal-fade-enter-active, .modal-fade-leave-active { transition: opacity .5s ease }*/
  /* 可以设置不同的进入和离开动画 */
  /* 设置持续时间和动画函数 */

  .slide-fade-enter-active {
    transition: all 0.3s ease;
  }
  .slide-fade-leave-active {
    transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1);
  }
  .slide-fade-enter, .slide-fade-leave-to
    /* .slide-fade-leave-active for below version 2.1.8 */ {
    transform: translateX(10px);
    opacity: 0;
  }

  .sign-modal {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.1);
    position: fixed;
    z-index: 100;
    bottom: 0;
    .pane {
      background-color: #fff;
      position: absolute;
      width: 100%;
      height: 50%;
      bottom: 0;
      padding: 10px 15px;
      .layout {
        height: 20px;
        font-size: 16px;
        color: #1e82d2;
        line-height: 20px;
        display: flex;
        display: -webkit-flex;
        justify-content: space-between;
        -webkit-justify-content: space-between;
      }
      .draw {
        width: 100%;
        height: 95%;
        .sig {
          width: 100%;
          height: 100%;
          canvas {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
</style>
