<template>
  <view v-if="isOpen" class="synchronous-dialog">
    <view class="synchronous-content">
      <view class="row-item">
        <text class="title"
          >巡检签字 <text class="tip">请在下方虚线框内进行签字</text></text
        >
				<view class="warning-text">注:签字后巡检内容无法修改，请先检查巡检内容确认无误后签字。</view>
      </view>
      <view class="operating-instructions"
        ><!-- 签字区域 -->
        <canvas
          canvas-id="signatureCanvas"
          class="signature-canvas"
          @touchstart="handleTouchStart"
          @touchmove="handleTouchMove"
          @touchend="handleTouchEnd"
        ></canvas>
      </view>

      <view class="row-item bottom-row">
        <button class="button btn" @click="clearSignature">重新签字</button>
        <button class="button" @click="confirmSignature">完成签字</button>
      </view>

      <!-- 关闭按钮 -->
      <div class="close-button">
        <text class="iconfont icon-shibai1" @click="close"></text>
      </div>
    </view>
  </view>
</template>

<script>
	import { createFolder, copyImage } from "@/utils/plus.js";
export default {
  components: {},
  data() {
    return {
      isOpen: false,
      points: [], // 存储绘制点
      ctx: null, // canvas 上下文
      canvasWidth: 761.6,
      canvasHeight: 302.4,
      isDrawing: false, // 是否正在绘制
    };
  },

  mounted() {
    this.initCanvas();
  },
  methods: {
    initCanvas() {
      this.ctx = uni.createCanvasContext("signatureCanvas", this);
      // 设置画布背景为白色
      this.ctx.fillStyle = "#ffffff";
      this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
      this.ctx.setStrokeStyle("#000000"); // 设置线条颜色
      this.ctx.setLineWidth(4); // 设置线条宽度
      this.ctx.setLineCap("round"); // 设置线条端点样式
      this.ctx.setLineJoin("round"); // 设置线条连接样式
      this.ctx.draw(true); // 立即绘制背景
      this.hasSigned = false; // 初始化时没有签字内容
    },
    handleTouchStart(e) {
      this.isDrawing = true;
      this.points = [];
      const startX = e.touches[0].x;
      const startY = e.touches[0].y;
      this.points.push({ x: startX, y: startY });
    },
    handleTouchMove(e) {
      if (!this.isDrawing) return;

      const x = e.touches[0].x;
      const y = e.touches[0].y;
      this.points.push({ x, y });

      if (this.points.length >= 2) {
        this.ctx.beginPath();
				this.ctx.setLineWidth(4); // 设置线条宽度
				this.ctx.setLineCap("round"); // 设置线条端点样式
				this.ctx.setLineJoin("round"); // 设置线条连接样式
        this.ctx.moveTo(
          this.points[this.points.length - 2].x,
          this.points[this.points.length - 2].y
        );
        this.ctx.lineTo(x, y);
        this.ctx.stroke();
        this.ctx.draw(true);
        this.hasSigned = true; // 标记有签字内容
      }
    },
    handleTouchEnd() {
      this.isDrawing = false;
      this.points = [];
    },
    clearSignature() {
      // 清空画布
      this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
      // 重新设置背景为白色
      this.ctx.fillStyle = "#ffffff";
      this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
      this.ctx.draw(true); // 立即更新画布
      this.hasSigned = false; // 标记没有签字内容
    },
    async confirmSignature() {
      // 如果没有签字内容，直接提示
      if (!this.hasSigned) {
        uni.showToast({
          title: "请先签字",
          icon: "none",
        });
        return;
      }

      // 生成签字图片
      uni.canvasToTempFilePath({
        canvasId: "signatureCanvas",
				fileType: 'jpg', // 不使用png是因为预览的时候黑底，字也是黑色，导致看不见图片签字
        success: async (res) => {
          const tempFilePath = res.tempFilePath;
		  await createFolder("data/sign");
		  const fileName = tempFilePath.split("/").pop();
		  const targetPath = `_documents/data/sign/${fileName}`;
		  const savedPath = await copyImage(tempFilePath, targetPath);
          // 存储照片到本地
          // uni.saveImageToPhotosAlbum({
          //   filePath: tempFilePath,
          //   success: function () {
          //     console.log("图片已成功保存到相册");
          //   },
          //   fail: function (err) {
          //     console.error("保存图片到相册失败:", err);
          //   },
          // });
		  
          // console.log("base64",base64)
          // 这里可以将 tempFilePath 上传到服务器或进行其他处理
          uni.showToast({
            title: "签字已保存",
            icon: "success",
          });
          this.$emit("confirm", savedPath);
          this.close();
        },
        fail: (err) => {
          console.error("生成图片失败", err);
        },
      });
    },
    // 转化为base64
    convertFileToBase64(filePath) {
      return new Promise((resolve, reject) => {
        plus.io.resolveLocalFileSystemURL(
          filePath,
          function (entry) {
            entry.file(
              function (file) {
                const reader = new plus.io.FileReader();
                reader.onloadend = function (evt) {
                  const base64 = evt.target.result; // 获取 Base64 数据
                  resolve(base64); // 返回 Base64 数据
                };
                reader.readAsDataURL(file); // 读取文件并转换为 Base64
              },
              function (error) {
                reject("获取文件对象失败：" + error.message);
              }
            );
          },
          function (error) {
            reject("解析文件路径失败：" + error.message);
          }
        );
      });
    },
    open() {
      this.isOpen = true;
    },
    // 关闭弹窗
    close() {
      this.isOpen = false;
    },
  },
};
</script>
<style scoped lang="less">
.synchronous-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
	z-index: 5000;
  .signature-canvas {
    width: 761.6px;
    height: 302.4px;
    background: #ffffff;
    border: 1px solid rgba(224, 224, 224, 1);
    border-radius: 9.6px;
  }

  .button-container {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;

    button {
      flex: 1;
      margin: 0 5px;
    }
  }
  .synchronous-content {
    padding: 25.6px 19.2px;
    width: 800px;
    height: 444.8px;
    box-sizing: border-box;
    background-image: linear-gradient(
      -6deg,
      #f9ffe7 0%,
      #ffffff 12%,
      #fcfeff 73%,
      #ccf1ff 100%
    );
    border: 0.4px solid rgba(224, 224, 224, 1);
    border-radius: 12px;
    position: relative;

    .row-item {
			position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .title {
      font-family: PingFangSC-Medium;
      font-size: 14.4px;
      color: #000000;
      text-align: center;
      line-height: 20.8px;
      font-weight: 500;
      margin-bottom: 20.8px;
      .tip {
        font-size: 12.8px;
        color: #4a4a4a;
        text-align: center;
        line-height: 20.8px;
        font-weight: 400;
        margin-right: 6.4px;
      }
    }
    .count-num {
      margin: 5% 0 5% 0;
      align-items: flex-end;
      .num {
        display: inline-block;
        font-family: AlibabaPuHuiTi_2_65_Medium;
        font-size: 50px;
        color: #3774f6;
        line-height: 44px;
        font-weight: 500;
      }
    }

    .operating-instructions {
      .title {
        font-size: 13px;
        color: #4a4a4a;
        line-height: 24px;
        font-weight: 600;
        text-align: left;
      }
      .instructions-item {
        font-size: 12px;
        color: #7c7c7c;
        line-height: 22px;
        font-weight: 400;
      }
    }

    // 打包按钮
    .bottom-row {
      position: absolute;
      bottom: 25.6px;
      left: 50%;
      transform: translateX(-50%);

      .button {
        display: flex;
        align-items: center;
        justify-content: center;
        background-image: linear-gradient(180deg, #3773f6 0%, #2c57f6 99%);
        box-shadow: 0px 10px 24px 0px rgba(51, 104, 246, 0.24);
        border-radius: 27px;
        width: 128px;
        height: 32px;
        color: #fff;
        margin: 0 5px;
        &.btn {
          background: #ffffff;
          color: #000000;
        }
      }
    }

    // 关闭按钮
    .close-button {
      position: absolute;
      bottom: -40px;
      left: 50%;
      transform: translateX(-50%);
      .iconfont {
        color: #fff;
        font-size: 24px;
      }
    }
  }
}
.warning-text {
	position: absolute;
	bottom: 5px;
	text-align: center;
	color: #f44;
	font-size: 12px;
}

</style>
