<template>
  <h-view class="public-style signature" title="电子签名">
    <h-content>
      <list-item>
        <item :proportion="[3,1]">
          <img slot="left-icon" class="left-icon" src="@/assets/image/esign/pen.png">
          <section slot="name">请您审核信息后在线签名</section>
        </item>
        <item>
          <div slot="name">姓名</div>
          <div slot="content">\{{ info.description }}</div>
        </item>
        <item>
          <div slot="name">身份证号</div>
          <div slot="content">\{{ info.id_card_no }}</div>
        </item>
        <item style="background-color: #eee">
          <div slot="content" class="create" @click="createSign">+创建签名</div>
        </item>
      </list-item>
    </h-content>
    <h-modal ref="modal" v-model="show" position="bottom" cus-class="sign-modal">
      <h-view>
        <h-header>
          <div v-tap="confirm" slot="left" class="h-header-btn">确定</div>
          <div v-tap="cleanData" slot="right" class="h-header-btn">清除</div>
        </h-header>
        <h-content>
          <div id="draw" class="draw">
            <canvas
              id="canvas"
              @mousedown="beginDraw"
              @mouseup="endDraw"
              @mousemove="drawing"
              @touchstart="beginDraw"
              @touchend="endDraw"
              @touchmove="drawing"/>
          </div>
        </h-content>
      </h-view>
    </h-modal>
  </h-view>
</template>

<script>
export default {
  name: 'Sign',
  data () {
    return {
      info: {
        description: '张三',
        id_card_no: '361021197607154329',
      },
      show: false,
      signData: '',
      // canvas参数
      canvas: {},
      context: {},
      height: '',
      mousePress: false,
      last: null,
      config: {
        strokeStyle: '#ff0000',
        lineWidth: 3,
      },
      // 是否开始签名
      hasSignature: false,
    }
  },
  created: function () {
  },
  mounted () {
    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: {
    /**
       * 弹出窗口
       * */
    createSign () {
      this.show = true
    },
    /**
       * 隐藏窗口
       * */
    hideModal () {
      this.$refs.modal.hideModal()
    },
    /**
       * 清空画布
       * */
    cleanData () {
      this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
      this.hasSignature = false
    },
    /**
       * 获取画图内容
       *
       * */
    confirm () {
      let vm = this
      if (!this.hasSignature) {
        vm.hlsPopup.showLongBottom('未创建签名！')
      } else {
        let signData = this.canvas.toDataURL('image/png').split(',')[1]
        this.$refs.modal.hideModal()
        vm.cleanData()
        vm.hlsPopup.showLoading('正在签名请稍等!')
        // 先创建账号
        let url = process.env.rootPath + '/app/sign/register'
        let param = {
          'idNo': vm.info.id_card_no,
          'name': vm.info.description,
        }
        hlsHttp.post(url, param).then(function (res) {
          if (!res.success) {
            // 如果成功进行签名
            // success_atm = []
            let fileName = '测试e签宝-盖章.pdf'
            vm.getSignPdf(vm.info.description, vm.info.id_card_no, signData, '', '', '', fileName, '', 'BOTH')
          } else {
            vm.hlsPopup.hideLoading()
            vm.hlsPopup.showPopup('', '签名失败请返回重试', function () {
            })
          }
        })
      }
    },
    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 = $config.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,
      }
      hlsHttp.post(url, param).then(function (res) {
        vm.hlsPopup.hideLoading()
        if (res.success) {
          vm.hlsPopup.showConfirm({
            title: '签名成功',
            content: '是否预览合同',
            onConfirm: function (index) {
              if (index === 1) {
                // 签名合同预览
                vm.fileToPdf(parseInt(res.message))
              }
            },
          })
        } else {
          vm.hlsPopup.showLongCenter('签名失败请重试')
        }
      })
    },

    fileToPdf (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 = {}
      hlsHttp.post(url, param).then(function (res) {
        if (res.success) {
          let length = res.message
          // PDF装图片数组
          let pirtureList = []
          for (var 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,
        },
      })
    },
    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,
      }
    },
    isTouch (e) {
      let type = e.type
      if (type.indexOf('touch') >= 0) {
        return true
      } else {
        return false
      }
    },
    /**
       * 重置画布操作
       * @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)
    },
  },

}
</script>

<style lang="less">
  .signature {
    background-color: #FFFFFF;
    .content {
      width: 100%;
      background-color: #eeeeee;
      .create {
        font-size: 14px;
        color: #e84544;
      }
    }
    .sign-modal {
      top: 50%;
      .content {
        background-color: #fff;
      }
    }
  }
</style>
