<template>
  <!-- 签字功能 -->
  <view catchtouchmove="true">
    <view class="sign-box">
      <view class="fixedIcon" @click.stop="changeDirection">
        <image style="height: 100rpx; width: 100rpx" :src="icon"></image>
      </view>

      <canvas class="mycanvas" :style="{ height: height + 'px' }" canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"></canvas>
      <canvas canvas-id="camCacnvs" :style="{ height: width + 'px' }" class="canvsborder"></canvas>

      <view :class="direction ? 'sigh_btns_true' : 'sigh_btns_false'">
        <nut-button :class="direction ? 'sigh_btns' : 'sigh_btns_noRotate'" style="height: 60rpx" shape="square" type="info" @click="handleCancel"> 取消 </nut-button>
        <nut-button :class="direction ? 'sigh_btns' : 'sigh_btns_noRotate'" style="height: 60rpx" shape="square" type="info" @click="handleReset"> 重写 </nut-button>
        <nut-button :class="direction ? 'sigh_btns' : 'sigh_btns_noRotate'" style="height: 60rpx" shape="square" type="info" @click="handleConfirm"> 确认 </nut-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import './signature.scss'
import Taro, { useLoad, useUnload } from '@tarojs/taro'
import { ref, onMounted, watch, computed } from 'vue'
import icon from '@/assets/images/rotate1.png'
const _index = ref(0)
import { useDailyStore } from '@/store/daily'
const store = useDailyStore()

const width = ref(0)
const height = ref(300)
const points = ref([]) // 画笔路径点集合
const tempPoint = ref([]) // 当前签名路径
let that
let id
let type
useLoad((options) => {
  _index.value = Number(options.index)
  Taro.setNavigationBarTitle({
    title: options.name,
  })
})
const ctx = ref(null)
onMounted(() => {
  that = this
  const { windowWidth, windowHeight } = Taro.getSystemInfoSync()
  width.value = windowWidth
  height.value = windowHeight * 0.98 // 控制画板的宽高

  // 创建绘图上下文
  ctx.value = Taro.createCanvasContext('mycanvas', this)
  ctx.value.lineWidth = 2
  ctx.value.lineCap = 'round'
  ctx.value.lineJoin = 'round'
})

const touchstart = (e) => {
  const startX = e.changedTouches[0].x
  const startY = e.changedTouches[0].y
  points.value.push({ X: startX, Y: startY })
  ctx.value.beginPath()
}

const touchmove = (e) => {
  const moveX = e.changedTouches[0].x
  const moveY = e.changedTouches[0].y
  points.value.push({ X: moveX, Y: moveY })
  if (points.value.length >= 2) {
    draw()
  }
  tempPoint.value.push({ X: moveX, Y: moveY })
}

const touchend = () => {
  points.value = []
}

const draw = () => {
  const point1 = points.value[0]
  const point2 = points.value[1]
  points.value.shift()
  ctx.value.moveTo(point1.X, point1.Y)
  ctx.value.lineTo(point2.X, point2.Y)
  ctx.value.stroke()
  ctx.value.draw(true)
}

const handleCancel = () => {
  Taro.navigateBack({ delta: 1 })
}

const handleReset = () => {
  ctx.value.clearRect(0, 0, width.value, height.value)
  ctx.value.draw(true)
  tempPoint.value = []
}

const handleConfirm = () => {
  if (tempPoint.value.length === 0) {
    Taro.showToast({ title: '请先签名', icon: 'none', duration: 2000 })
    return
  }

  Taro.canvasToTempFilePath({
    canvasId: 'mycanvas',
    success: (res) => {
      console.log('canvasToTempFilePath______________', res)

      const tempPath = res.tempFilePath
      const ctx = Taro.createCanvasContext('camCacnvs', that)
      const scale = 0.5
      var targetWidth
      var targetHeight
      // 前置图片旋转处理 ___________________________________________________________________
      if (direction.value) {
        targetWidth = height.value * scale
        targetHeight = width.value * scale
        // 计算旋转后的外接矩形尺寸
        const angle = (270 * Math.PI) / 180 // 逆时针旋转 270 度
        const rotatedWidth = Math.abs(width.value * Math.cos(angle)) + Math.abs(height.value * Math.sin(angle))
        const rotatedHeight = Math.abs(height.value * Math.cos(angle)) + Math.abs(width.value * Math.sin(angle))
        // 计算平移量
        const offsetX = 0 // 如果不需要水平偏移，则为 0
        const offsetY = rotatedHeight - targetHeight // 计算 y 轴的平移量
        // 将画布原点平移到适当位置
        ctx.translate(offsetX, offsetY)
        // 旋转画布
        ctx.rotate(angle)
        ctx.drawImage(tempPath, 0, 0, targetHeight, targetWidth)
      } else {
        targetWidth = width.value * scale
        targetHeight = height.value * scale
        ctx.drawImage(tempPath, 0, 0, targetWidth, targetHeight)
      }

      ctx.draw(false, () => {
        Taro.canvasToTempFilePath({
          canvasId: 'camCacnvs',
          width: targetWidth,
          height: targetHeight,
          success: (compressedRes) => {
            Taro.getFileSystemManager().readFile({
              filePath: compressedRes.tempFilePath,
              encoding: 'base64',
              success: (res) => {
                const base64Image = 'data:image/jpeg;base64,' + res.data

                console.log('base64Image_________________________', base64Image)

                if (_index.value === 1) {
                  store.change_base64_1(base64Image)
                  Taro.navigateBack({ delta: 1 })
                } else {
                  store.change_base64_2(base64Image)
                  Taro.navigateBack({ delta: 1 })
                }
              },
            })
          },
        })
      })
    },
  })
}
/**
 * @direction false 竖屏，true 横屏
 */

const direction = ref(true)
const changeDirection = () => {
  direction.value = !direction.value
  Taro.vibrateShort({ type: 'medium' }).then()
}
</script>
