<template>
  <h-view id="sign" class="public-style" title="电子签章">
    <!--<h-header>
      <div slot="left" class="h-header-btn" @click="$routeGo()">
        <i class="ion-ios-arrow-back"/>
      </div>
      <div slot="center">电子签章</div>
    </h-header>-->
    <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">{{ personName }}</div>
        </item>
        <item>
          <div slot="name">身份证号</div>
          <div slot="content">{{ identificationNumber }}</div>
        </item>
      </list-item>
      <list-item>
        <item :proportion="[1,3]">
          <section slot="name">选择签章类型</section>
          <radio-group slot="content" v-model="signType" style="display:flex;">
            <h-radio :checked="true" name="hand" title="手写签名"/>
            <h-radio name="key" title="关键字签章"/>
          </radio-group>
        </item>
      </list-item>

      <radio-group v-show="signType==='key'" v-model="radioValue">
        <h-radio :checked="true" name="76" title="出租人盖章"/>
        <h-radio name="77" title="合同签章"/>
        <h-radio name="78" title="上海汉得"/>
      </radio-group>
      <section v-show="signType==='key'" class="button">
        <h-button @click.native="sign()">签章</h-button>
      </section>
      <section v-show="signType==='hand'" class="button">
        <h-button @click.native="createSign()">创建签名</h-button>
      </section>
    </h-content>
    <h-modal ref="modal" v-model="show" position="bottom" cus-class="sign-modal">
      <h-view>
        <h-header style="padding-top: 0 !important;">
          <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 {
  data () {
    return {
      signType: 'hand',
      radioValue: 76,
      personName: this.$route.params.personName,
      identificationNumber: this.$route.params.identificationNumber,
      // sign
      show: false,
      signData: '',
      // canvas参数
      canvas: {},
      context: {},
      height: '',
      mousePress: false,
      last: null,
      config: {
        strokeStyle: '#ff0000',
        lineWidth: 3,
      },
      // 是否开始签名
      hasSignature: false,
    }
  },
  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: {
    reviewPdf () {
      cordova.InAppBrowser.open('http://hlsapp.hand-china.com/file/jinge/RZZLCON.pdf','_system')
    },
    /**
     * 演示用 不调用接口
     * url = $config.rootPath+'/electronicSignature/createContractFile'
     * 金格 1011创建合同(文件上传方式)
     * 此接口在项目实际开发需要按需改造，合同附件应从业务系统传输过来
     * 完成签名后调用 1019 进行下载
     */
    sign () {
      // TODO 此处应该调用金格电子电子签章 1011创建合同进行盖章
      let vm = this
      vm.hlsPopup.showLoading('正在签章请稍等！')
      setTimeout(function () {
        vm.hlsPopup.hideLoading()
        vm.hlsPopup.showPopup({
          title: '签章成功',
          content: '预览合同',
          onConfirm () {
            cordova.InAppBrowser.open('http://hlsapp.hand-china.com/file/jinge/ZL201907180000000' + vm.radioValue + '.pdf', '_system')
          },
        })
      }, 2000)
    },

    /**
     * 弹出窗口
     * */
    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.identificationNumber,
          'name': vm.personName,
        }
        hlsHttp.post(url, param).then(function (res) {
          if (!res.success) {
            // 如果成功进行签名
            // success_atm = []
            let fileName = '测试e签宝-盖章.pdf'
            vm.getSignPdf(vm.personName, vm.identificationNumber, signData, '', '', '', fileName, '', '')
          } 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': 510, 'y': 250}, {'page': '4', 'x': 445, 'y': 165}]
      }
      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.showPopup({
            title: '签名成功',
            content: '是否预览合同',
            onConfirm () {
              // 签名合同预览
              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 url = process.env.rootPath + '/app/downLoadPdf?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 (let i = 0; i < length; i++) {
            pirtureList.push({imgUrl: process.env.file_url + 'esign/' + attachmentId + '/temp/' + 'temp_' + (i + 1) + '.png'})
          }
          vm.hlsPopup.hideLoading()
          /* setTimeout(() => {
            window.open('http://hlsapp.hand-china.com/file/esign/' + attachmentId + '/temp.pdf', '_system')
          }, 1000) */

          vm.alpviewimg(pirtureList)
        } else {
          vm.hlsPopup.hideLoading()
          vm.hlsPopup.showLongCenter('预览文件失败')
        }
      })
      /* let pirtureList = [{
        imgUrl: 'http://hlsapp.hand-china.com/file/esign/185/temp/temp_1.png',
      }, {
        imgUrl: 'http://hlsapp.hand-china.com/file/esign/185/temp/temp_2.png',
      }, {
        imgUrl: 'http://hlsapp.hand-china.com/file/esign/185/temp/temp_3.png',
      }, {
        imgUrl: 'http://hlsapp.hand-china.com/file/esign/185/temp/temp_4.png',
      }]
      vm.alpviewimg(pirtureList) */
    },
    alpviewimg (pirtureList) {
      let vm = this
      /* vm.hlsPopup.showBigPicture({
        startPosition: 0,
        imgList: pirtureList,
      }) */
      vm.$router.push({
        name: 'ViewPicture',
        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" type="text/less">
  @import "../../../styles/vue-1px.less";
  .show-picture-backdrop .hls-swipe .hls-swipe-track .hls-swipe-item img{
    height: 100% !important;
    width: 100% !important;
  }
  #sign {
    .content {
      .add-content{
        .radio-group{
          display: flex;
          .h-radio {
            margin-right: 10px;
            justify-content: flex-end;
            &:after {
              border: none;
            }
          }
        }
      }
      .radio-group {
        width: 100%;
        background-color: #fff;
        padding-left: 15px;

        .h-radio {
          height: 44px;
          position: relative;

          &:after {
            .setBottomLine()
          }
        }

      }
      .button{
        width: 100%;
        margin-top: 40px;
        display: flex;
        justify-content: center;
        .hls-h-button{
          background-color: @headerColor;
          border: none;
          border-radius: 20px;
          width: 140px;
          height: 40px;
          color: #fff;
        }
      }
    }
    .sign-modal {
      top: 50%;
      .content {
        background-color: #fff;
      }
    }
  }

  // iPhoneX适配
  @media (device-width: 375px) and (device-height: 812px) and (-webkit-min-device-pixel-ratio: 3) {
    .platform-ios {
      #home {
      }
    }
  }

  // iPhoneX Max适配
  @media (device-width: 414px) and (device-height: 896px) {
    .platform-ios {
      .platform-ios {
        #home {
        }
      }
    }
  }
</style>
