<template>
  <view class="u-p-50">
    <uni-collapse>
      <uni-collapse-item :border="false" :open="false" title="知情同意书存档">
        <view class="u-p-l-40">知情同意书内容</view>
      </uni-collapse-item>
    </uni-collapse>

    <canvas ref="canvasRef" style="width: 100%; height: 400px; background-color: #eee;" canvas-id="canvas" id="canvas" @touchstart="onStart"
            @touchmove="onMove" @touchend="onEnd"></canvas>

    <view class="flex u-p-t-40">
      <u-button size="medium" class="bg-main" type="primary" shape="circle" @click="onReset">重写</u-button>
      <u-button size="medium" class="bg-main" type="primary" shape="circle" @click="onSubmit">确认签名</u-button>
    </view>
  </view>
</template>

<script >
import { createInjectionState } from '@vueuse/core'


let ctx
let startX = 0
let startY = 0
let drawing = false
let pathArr = []
let canvasWidth, canvasHeight

export default {
  name: 'SignComp',
  mounted() {
    ctx = uni.createCanvasContext('canvas')
    ctx.setStrokeStyle('#333')
    ctx.setLineWidth(3)
    const query = uni.createSelectorQuery().in(this);
    query.select('#canvas').boundingClientRect(data => {
      canvasWidth = data.width
      canvasHeight = data.height
    }).exec();
  },
  methods: {
    onStart(event) {
      drawing = true
      startX = event.changedTouches[0].x
      startY = event.changedTouches[0].y

      pathArr.push([])
    },

    onMove(event) {
      event.preventDefault()
      if (!drawing) return
      const { x, y } = event.changedTouches[0]
      // console.log(x, y);
      pathArr[pathArr.length - 1].push([x, y])
      this.drawLine()
      ctx.stroke()
      ctx.draw()
    },

    onEnd(event) {
      drawing = false
    },

    drawLine() {
      if (!pathArr.length) return
      pathArr.forEach(path => {
        // path 是一条连续的路径
        if (path.length > 0) {
          path.forEach((point, index) => {
            if (index === 0) {
              ctx.moveTo(point[0], point[1])
            } else {
              ctx.lineTo(point[0], point[1])
            }
          })
        }
      })
    },

    onReset() {
      pathArr = []
      ctx.clearRect(0, 0, canvasWidth, canvasHeight)
      ctx.draw()
    },

    onSubmit() {
      uni.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: canvasWidth,
        height: canvasHeight,
        canvasId: 'canvas',
        success: res => {
          // 在H5平台下，tempFilePath 为 base64
          // #ifdef APP-PLUS
          // 按文件传
          this.uploadFile(res.tempFilePath)
          // #endif

          // #ifdef H5
          // TODO: 按base64传
          this.uploadBase64(res.tempFilePath)
          // #endif

          // 发送关闭的事件
          this.$emit('on-close')
        }
      })
    },

    async uploadFile(filePath) {
      console.log(filePath);
    },

    async uploadBase64(base64) { }
  }
}
</script>
