<style>
  .loadingtext {
    transform: rotate(-90deg);
    color: red;
  }

  .signature .Sign_Item {
    -webkit-transform: rotate(-90deg);
  }

  .signature .Sign_Text {
    text-align: center;
  }

  .signature .boardBox {
    width: 100vw;
    height: 90vh;
    background: #f9f9f9;
  }

  .signature .sigfn_Bar {
    box-sizing: border-box;
    padding: 0rem 1rem;
    display: flex;
    width: 100vw;
    height: 10vh;
    background-color: #ffffff;
    justify-content: space-around;
    align-items: center;
  }

  .signature .icoDicv {
    width: 40px;
    height: 40px;
    background: gray;
    border-radius: 50%;
    color: #fff;
    text-align: center;
    line-height: 40px;
  }

  .signature .icoDicv i {
    font-size: 25px;
  }

</style>
<template>
  <div class="signature" @touchmove.prevent>
    <div class="boardBox" ref="boardBox">
      <canvas ref="board" id="canvas" @touchstart="mStart" @touchmove="mMove" @touchend="mEnd"></canvas>
    </div>
    <div class="sigfn_Bar">
      <div class="Sign_Item" @click="goback">
        <div class="icoDicv">
          <i class="iconfont icon-tuichu"></i>
        </div>
        <div class="Sign_Text">退出</div>
      </div>
      <div class="Sign_Item" @click="clearcanvas">
        <div class="icoDicv">
          <i class="iconfont icon-zhongzhi"></i>
        </div>
        <div class="Sign_Text">重绘</div>
      </div>
      <div class="Sign_Item" @click="getcanvas">
        <div class="icoDicv" style="background:red;">
          <i class="iconfont icon-xiazai"></i>
        </div>
        <div class="Sign_Text">保存</div>
      </div>
    </div>
  </div>
</template>
<script>
  import {
    SetEducationContractSign,
    SetBackClassProtocolSign
  } from '../api/sale/contract'
  import {
    UploadSelfFile
  } from '../api/common/common'
  import {
    Encrypt,
    Decrypt
  } from '../utils/encrypt'


  export default {
    data() {
      return {
        familysignatureurl: "",
        basedata: "",
        ctx: null,
        point: {
          x: 0,
          y: 0,
        },
        moving: false, // 是否正在绘制中且移动
        msg: {
          ContractId: 0,
          Sign: ''
        },
        Money: 0,
        Type: 1, //1为电子合同签字 2为退课协议签字
        BackMsg: {
          Id: 0,
          sign: ''
        },
        StudentName: ''
      };
    },
    mounted() {
      let board = this.$refs.board; // 获取DOM
      board.width = this.$refs.boardBox.offsetWidth; // 设置画布宽
      board.height = this.$refs.boardBox.offsetHeight; // 设置画布高
      this.ctx = board.getContext("2d"); // 二维绘图
      this.ctx.strokeStyle = "#000"; // 颜色
      this.ctx.lineWidth = 5; // 线条宽度
      if (this.$route.query.a) {
        let ContractId = Decrypt(decodeURIComponent(this.$route.query.a));
        this.msg.ContractId = ContractId;
      }
      if (this.$route.query.StudentName) {
        this.StudentName = this.$route.query.StudentName
      }
      if (this.$route.query.Money) {
        this.Money = this.$route.query.Money;
      }
      if (this.$route.query.Id) {
        this.BackMsg.Id = this.$route.query.Id;
      }
      if (this.$route.query.Type) {
        this.Type = this.$route.query.Type;
      }
    },
    methods: {
      // 触摸(开始)
      mStart(e) {
        let x = e.touches[0].clientX - e.target.offsetLeft,
          y = e.touches[0].clientY - e.target.offsetTop; // 获取触摸点在画板（canvas）的坐标
        this.point.x = x;
        this.point.y = y;
        this.ctx.beginPath();
        this.moving = true;
      },
      // 滑动中...
      mMove(e) {
        if (this.moving) {
          let x = e.touches[0].clientX - e.target.offsetLeft,
            y = e.touches[0].clientY - e.target.offsetTop; // 获取触摸点在画板（canvas）的坐标
          this.ctx.moveTo(this.point.x, this.point.y); // 把路径移动到画布中的指定点，不创建线条(起始点)
          this.ctx.lineTo(x, y); // 添加一个新点，然后创建从该点到画布中最后指定点的线条，不创建线条
          this.ctx.stroke(); // 绘制
          (this.point.x = x), (this.point.y = y); // 重置点坐标为上一个坐标
        }
      },
      // 滑动结束
      mEnd() {
        if (this.moving) {
          this.ctx.closePath(); // 停止绘制
          this.moving = false; // 关闭绘制开关
        }
      },
      getcanvas() {
        //绘画转图片
        document.getElementById("canvas").toDataURL("image/png");
        document.getElementById("canvas").toBlob(async (blobObj) => {
          var file1 = new File([blobObj], "pic.png", {
            type: blobObj.type,
            lastModified: Date.now(),
          });
          this.convertImg(file1);
        });
      },
      //旋转图片
      convertImg(file) {
        let _this = this;
        var canvas1 = document.createElement("canvas");
        var context1 = canvas1.getContext("2d");
        var oReader = new FileReader();
        oReader.readAsDataURL(file);
        oReader.onload = function (e) {
          var img = new Image();
          img.src = e.target.result;
          img.onload = function () {
            // 图片原始尺寸
            var originWidth = this.width;
            var originHeight = this.height;
            // 最大尺寸限制
            var maxWidth = 1080,
              maxHeight = 1080;
            // 目标尺寸
            var targetWidth = originWidth,
              targetHeight = originHeight;
            // 图片尺寸超过300x300的限制
            if (originWidth > maxWidth || originHeight > maxHeight) {
              if (originWidth / originHeight > maxWidth / maxHeight) {
                targetWidth = maxWidth;
                targetHeight = Math.round(
                  maxWidth * (originHeight / originWidth)
                );
              } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(
                  maxHeight * (originWidth / originHeight)
                );
              }
            }
            var type = "image/jpeg";
            // canvas对图片进行缩放
            canvas1.width = targetHeight;
            canvas1.height = targetWidth;
            // 旋转90度
            context1.translate(0, 0);
            context1.rotate(Math.PI / 2);
            // (0,-imgHeight) 从旋转原理图那里获得的起始点
            // context.clearRect(0,  -targetHeight, targetWidth, targetHeight);
            context1.drawImage(img, 0, -targetHeight, targetWidth, targetHeight);
            // 将canvas的透明背景设置成白色
            var imageData = context1.getImageData(
              0,
              0,
              canvas1.width,
              canvas1.height
            );
            for (var i = 0; i < imageData.data.length; i += 4) {
              // 当该像素是透明的，则设置成白色
              if (imageData.data[i + 3] == 0) {
                imageData.data[i] = 255;
                imageData.data[i + 1] = 255;
                imageData.data[i + 2] = 255;
                imageData.data[i + 3] = 255;
              }
            }
            context1.putImageData(imageData, 0, 0);
            var dataurl = canvas1.toDataURL(type);
            // _this.basedata = dataurl;
            _this.msg.Sign = canvas1.toDataURL(type);
            _this.BackMsg.sign = canvas1.toDataURL(type);
            _this.SaveMsg();

          };
        };
      },
      dataURLtoFile(dataurl, filename) { //将base64转换为文件
        var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {
          type: mime
        });
      },

      uuid(len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [],
          i;
        radix = radix || chars.length;
        if (len) {
          // Compact form
          for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
          var r;
          uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
          uuid[14] = '4';
          for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
              r = 0 | Math.random() * 16;
              uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
          }
        }
        return uuid.join('');
      },

      //提交数据
      SaveMsg() {
        if (this.Type == 1) {
          SetEducationContractSign(this.msg).then(res => {
            if (res.Code == 1) {
              this.$q.notify({
                icon: 'iconfont icon-chenggong',
                color: 'accent',
                timeout: 2000,
                message: '保存成功！',
                position: 'top'
              })
              this.$router.push({
                path: '/contractPay',
                query: {
                  contractId: this.msg.ContractId,
                  Money: this.Money
                }
              });
            }
          })
        }
        if (this.Type == 2) {
          SetBackClassProtocolSign(this.BackMsg).then(res => {
            if (res.Code == 1) {
              this.$q.notify({
                icon: 'iconfont icon-chenggong',
                color: 'accent',
                timeout: 2000,
                message: '保存成功！',
                position: 'top'
              })
              this.$router.push({
                path: '/courseRefundH5',
                query: {
                  Id: this.BackMsg.Id
                }
              });
            }
          })
        }
      },

      //base64转Blob
      base64ToBlob(base64Data) {
        let arr = base64Data.split(","),
          fileType = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          l = bstr.length,
          u8Arr = new Uint8Array(l);

        while (l--) {
          u8Arr[l] = bstr.charCodeAt(l);
        }
        return new Blob([u8Arr], {
          type: fileType,
        });
      },
      //清除画布
      clearcanvas() {
        var c = document.getElementById("canvas");
        var cxt = c.getContext("2d");
        c.height = c.height;
        this.ctx.lineWidth = 3;
      },
      //返回上一级
      goback() {
        if (this.Type == 1) {
          this.$router.push({
            path: '/contractConfirm',
            query: {
              a: encodeURIComponent(Encrypt(this.msg.ContractId.toString())),
            }
          });
        } else {
          this.$router.push({
            path: '/courseRefundH5',
            query: {
              Id: this.BackMsg.Id
            }
          });
        }
      },
    },
  };

</script>
