<template>
  <div class="box">
    <div class="canvaspanel">
      <div class="buttongroup">
        <div class="left" @click="reset">
           <van-icon name="delete-o" size="18" style="margin-right: 3px" />
        <span class="empty">清除</span>
        </div>
        <div class="right" @click="save">
          <van-icon name="certificate" size="18" style="margin-right: 3px" />
        <span class="empty">确认</span>
        </div>
      </div>
      <div class="canvasborder">
        <canvas
        id="canvas"
        @touchstart="touchStart"
        @touchmove="touchMove"
        @touchend="touchEnd"
        ></canvas>
      </div>
      <div style="margin: 10px auto;width: 100px;">
        <van-icon name="arrow-up" size="20" @click="$parent.isSign = false"/>
      </div>
    </div>
  </div>
</template>
<script>
import { Toast } from 'vant'
const $ = (val) => document.querySelector(val)
// 配置内容
const config = {
  width: 0, // 宽度
  height: 0, // 高度
  lineWidth: 5, // 线宽
  strokeStyle: '#000000', // 线条颜色
  lineCap: 'round', // 设置线条两端圆角
  lineJoin: 'round' // 线条交汇处圆角
}

// 偏移量
const client = {
  offsetX: 0,
  offsetY: 0
}

let canvas
let ctx
export default {
  name: 'Signature',
  components: {

  },
  data () {
    return {
    }
  },
  mounted () {
    this.drawingBoardInit()
  },
  methods: {
    handleReset () {
    },
    confirm () {
      this.$refs.esign.generate().then(res => {
        const img = this.rotateBase64(res)
        this.$emit('getSign', img)
        console.log(res)
        // this.$notify({ type: 'success', message: '签字数据已获取，可以上传！' })
      // eslint-disable-next-line handle-callback-err
      }).catch((err) => {
        Toast.fail('请签名')
        // 画布没有签字时会执行这里 'Not Signned'
      })
    },
    drawingBoardInit () {
      console.log($('.canvasborder'), '$(canvasborder)')
      const {
        width, height, left, top
      } = $('.canvasborder').getBoundingClientRect()
      config.width = width
      config.height = height
      client.offsetX = left
      client.offsetY = top
      // canvas 实例
      canvas = $('#canvas')
      // 设置宽高
      canvas.width = config.width
      canvas.height = config.height
      // 设置边框
      //   canvas.style.border = '1px solid #000';
      // 创建上下文
      ctx = canvas.getContext('2d')
      // 设置填充背景色
      ctx.fillStyle = 'transparent'
      // 绘制填充矩形
      ctx.fillRect(
        0, // x 轴起始绘制位置
        0, // y 轴起始绘制位置
        config.width, // 宽度
        config.height // 高度
      )
    },
    // 鼠标按下
    touchStart (event) {
      event.preventDefault()
      // 获取偏移量及坐标
      const { clientX, clientY } = event.changedTouches[0]
      // 清除以上一次 beginPath 之后的所有路径，进行绘制
      ctx.beginPath()
      // 根据配置文件设置相应配置
      ctx.lineWidth = config.lineWidth
      ctx.strokeStyle = config.strokeStyle
      ctx.lineCap = config.lineCap
      ctx.lineJoin = config.lineJoin
      // 设置画线起始点位（减去 左边、上方的偏移量很关键）
      ctx.moveTo(clientX - client.offsetX, clientY - client.offsetY)
    },
    // 绘制
    touchMove (event) {
      // 获取当前坐标点位
      const { clientX, clientY } = event.changedTouches[0]
      // 根据坐标点位移动添加线条（减去 左边、上方的偏移量很关键）
      ctx.lineTo(clientX - client.offsetX, clientY - client.offsetY)
      // 绘制
      ctx.stroke()
    },
    // 结束绘制
    touchEnd () {
      // 结束绘制
      ctx.closePath()
      // 移除鼠标移动或手势移动监听器
      window.removeEventListener('mousemove', this.draw)
    },
    // 清除
    reset () {
      // 清空当前画布上的所有绘制内容
      ctx.clearRect(0, 0, config.width, config.height)
    },
    // 将画布内容保存为图片
    save () {
      return new Promise((resolve, reject) => {
        if (!this.isCanvasBlank(canvas)) {
          this.rotateBase64(canvas.toDataURL('image/png')).then((img) => {
            const imgBase64 = img
            // console.log(imgBase64, 'imgBase64-->>'); // base64编码
            this.$emit('getSign', imgBase64)
            resolve(imgBase64)
          })
        }
      })
    },
    // 判断canvas对象是否空
    isCanvasBlank (canvas) {
      const blank = document.createElement('canvas') // 系统获取一个空canvas对象
      blank.width = config.width
      blank.height = config.height
      return canvas.toDataURL() === blank.toDataURL() // 比较值相等则为空
    },
    // 将base64图片旋转90度以后上传
    rotateBase64 (imgBase64) {
      return new Promise((resolve) => {
        const imgView = new Image()
        imgView.src = imgBase64
        const canvas = document.createElement('canvas')
        const context = canvas.getContext('2d')
        const cutCoor = {
          sx: 0,
          sy: 0,
          ex: 0,
          ey: 0
        }
        // 裁剪坐标
        imgView.onload = () => {
          const imgW = imgView.width
          const imgH = imgView.height
          const size = imgH
          //   常量大小 = imgH;
          canvas.width = size * 2
          canvas.height = size * 2
          cutCoor.sx = size
          cutCoor.sy = size - imgW
          cutCoor.ex = size + imgH
          cutCoor.ey = size + imgW
          context.translate(size, size)
          context.rotate((Math.PI / 2) * 3)
          context.drawImage(imgView, 0, 0)
          const imgData = context.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey)
          for (var i = 0; i < imgData.data.length; i += 4) {
            // 当该像素是透明的，则设置成白色
            if (imgData.data[i + 3] === 0) {
              imgData.data[i] = 255
              imgData.data[i + 1] = 255
              imgData.data[i + 2] = 255
              imgData.data[i + 3] = 255
            }
          }
          canvas.width = imgH
          canvas.height = imgW
          context.putImageData(imgData, 0, 0)
          resolve(canvas.toDataURL('image/png'))
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.box{
  position: absolute;
  left: 0; top: 0;
  background: #fff;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
}
.canvasborder {
  width: 280px !important;
  height: 100%;
  border: solid 1px #ccc;
}
.canvaspanel {
  display: flex;
  width: 100vw;
  height: 100%;
  overflow: hidden;
}

.buttongroup {
    width: 50px;
    font-size: 16px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    transform: rotate(0deg);
    padding: 30px 0;
    .left,.right{
      width: 200px;
      height: 50px;
      line-height: 50px;
      transform: rotate(90deg);
    }
  }
  .autograph {
    margin-left: 20px;
  }
</style>
