<template>
    <div>
        <van-nav-bar
        title="电子签名"
        left-arrow
        @click-left="$router.back(-1)"
        />
        <van-cell-group style="width: 96%;margin:2%;border-radius: 6px;overflow: hidden;padding-top: 10px;padding-bottom: 10px;box-shadow: 0px 3px 6px 0px rgba(0,0,0,0.16);">
            <div class="signature-box">
                <vue-esign
                    ref="esign"
                    class="mySign"
                    :width="500"
                    :height="225"
                    :isCrop="signature.isCrop"
                    :lineWidth="signature.lineWidth"
                    :lineColor="signature.lineColor"
                    :bgColor.sync="signature.bgColor"
                  />
            </div>

            <div class="signature-footer">
                <signatureUploadSignature @signaImg = "signaImgFun"/>
                <van-button @click="handleGenerate" type="info" size="small">  生成签字图片</van-button>
                <van-button @click="handleReset" class="clearBtn" type="info" plain  size="small">清空画板</van-button>
            </div>

            <div class="esigh-result">
                <img :src="signatureImg"  class="imgs" v-if="signatureImg!=''"/>
            </div>
        </van-cell-group>
    </div>
</template>


<script>
import vueEsign from 'vue-esign'
import {getToken} from "@/utils/auth";
import axios from 'axios'
import { getUserProfile  } from "@/api/lawEnforcement/index";
import signatureUploadSignature from './signatureUploadSignature';
export default {
  name: "yinnongSignature",
  components:{vueEsign,signatureUploadSignature},
  data() {
    return {
        signatureImg:'',
        //上传图片
        uploadPictures:{
            action:process.env.VUE_APP_BASE_API+'/system/user/profile/electronicSignature',
            headers: { Authorization: "Bearer " + getToken() },
        },
        //电子签名
        signature:{
            lineWidth: 6, // 画笔的线条粗细
            lineColor: "#000000", // 画笔的颜色
            bgColor: "", // 画布的背景颜色
            resultImg: "", // 最终画布生成的base64图片
            isCrop: false, // 是否裁剪，在画布设定尺寸基础上裁掉四周空白部分
        }
    }
  },
  mounted(){
    this.getUser();
  },
  methods:{
    getUser(){

        getUserProfile().then(response => {
            const baseImgUrl = this.$store.getters.baseRoutingUrl;
            this.signatureImg = baseImgUrl+response.data.electronicSignature
            if(baseImgUrl==''){
                setTimeout(()=>{
                    const baseImgUrl = this.$store.getters.baseRoutingUrl;
                    this.signatureImg = baseImgUrl+response.data.electronicSignature
                },1000)
            }
        });
    },
    signaImgFun(url){
      this.signatureImg = url;
      // console.log(url)
    },

    // 清空画板
    handleReset() {
      this.$refs.esign.reset();
    },
    // 生成签字图
    handleGenerate() {
      this.$refs.esign
        .generate() // 使用生成器调用把签字的图片转换成为base64图片格式
        .then((res) => {
            console.log(res)
          this.signature.resultImg = res;
          let wj  =  this.dataURLtoBlob(res);
          let param = new FormData()  // 创建form对象
          param.append('electronicSignaturefile', wj)  // 通过append向form对象添加数据

          let config = {
            headers: this.uploadPictures.headers
          }
          // 添加请求头
          axios.post(this.uploadPictures.action, param, config)
              .then(res => {
                let content  = res.data;
                if(content.code == 200){
                   const baseImgUrl = this.$store.getters.baseRoutingUrl;
                  this.signatureImg = baseImgUrl+content.esUrl;
                }
              })

        })
        .catch((err) => {
          // 画布没有签字时会执行这里提示一下
          this.$toast.fail('请签名后再生成签字图片');

        });
    },
    dataURLtoBlob (dataurl, filename = 'file') {
        let arr = dataurl.split(',')
        let mime = arr[0].match(/:(.*?);/)[1]
        let suffix = mime.split('/')[1]
        let bstr = atob(arr[1])
        let n = bstr.length
        let u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], `${filename}.${suffix}`, {
            type: mime
        })
    },
  }
}

</script>


<style scoped lang="scss">
.signature-box{
    border:1px dashed #666;
    margin:2px 20px;
}
.signature-footer{
    margin:15px 20px 0;
    display: flex;
    .clearBtn{
        margin-left: 15px;
    }
}
.esigh-result{
    margin:15px 20px;
    // height: 110px;
    border:1px solid #666;
    font-size: 0;
    .imgs{
        width: 100%;
    }
}
</style>
