<template>
  <div class="canvaspanel-conntainer">
    <div class="canvaspanel">
      <div class="canvasborder">
        <vue-esign
          ref="esign"
          :width="width"
          :height="300"
          :isCrop="isCrop"
          :lineWidth="lineWidth"
          :lineColor="lineColor"
          :bgColor.sync="bgColor"
          style="width: 100% !important"
        />
      </div>
      <div class="buttongroup">
          <a-button type="gray" size="large" @click="handleReset" icon="delete"> 清除 </a-button>
          <a-button type="link" size="large" @click="handleGenerate" icon="check-circle"> 保存 </a-button>
      </div>
    </div>
    <img :src="resultImg" alt="" v-show="false" />
  </div>
</template>
<script>
export default {
  name: 'esign',
  components: {},
  data() {
    return {
      title: '手写签名',
      width: 0,
      lineWidth: 10,
      lineColor: '#000000',
      bgColor: '',
      resultImg: '',
      isCrop: false,
    };
  },
  created() {
    this.width = window.innerWidth - 16*2 - 16*2;
  },
  methods: {
    handleReset() {
      this.$refs['esign'].reset(); //清空画布
      this.$emit('reset');
    },
    handleGenerate() {
      this.$refs['esign']
        .generate()
        .then(res => {
          this.resultImg = res; // 得到了签字生成的base64图片
          this.base64ImgtoFile(this.resultImg);
          let data = this.base64ImgtoFile(this.resultImg);
          //调用接口
          this.$emit('close', data);
        })
        .catch(err => {
          this.$message.error('请签名后再保存');
        });
    },
    // 将base64，转换成图片
    base64ImgtoFile(dataurl, filename = 'file') {
      const arr = dataurl.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const suffix = mime.split('/')[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
      });
    },
  },
};
</script>
<style lang="less" scope>
.canvasborder {
  background: #efefef;
  border-radius: 8px;
  width: 100%;

}
.canvaspanel {
  display: flex;
  position: relative;
  margin: 16px 0;
}

.buttongroup {
  position: absolute;
  right: 16px;
  bottom: 16px;
}

.autograph {
  margin-left: 20px;
}
.clos {
  width: 88px;
}
</style>
