<template>
  <a-modal
    :maskClosable="false"
    :keyboard="false"
    :title="title"
    :width="width"
    :visible="visible"
    @cancel="handleCancel"
    :cancelText="LocleUtil.getLocale('m.common.button.close')">
    <canvas :ref="field"
            id="signCanvas"
            :style="{'background-color':'#fff','border': '1px solid #dcdfe6'}"
            :width="width-45"
            :height="height"
            @touchstart="touchStart"
            @touchmove="touchMove"
            @touchend="touchEnd"
            @mousedown="mouseDown"
            @mousemove="mouseMove"
            @mouseup="mouseUp">
    </canvas>
    <template slot="footer">
      <a-button @click.native="overwrite" size="small" class="gray resetBtn" round>{{ LocleUtil.getLocale('m.common.button.reset') }}</a-button>
      <a-button  type="primary" @click="handleOk">{{ LocleUtil.getLocale('m.common.button.ok') }}</a-button>
      <a-button @click="handleCancel">{{ LocleUtil.getLocale('m.common.button.close') }}</a-button>
    </template>
  </a-modal>
</template>

<script>
  import {uploadAction,getFileAccessHttpUrl,uidGenerator } from '../utils/manage'
  import YchConstant from "../utils/YchConstant";
  import LocleUtil from "../utils/LocleUtil";
  // import store from '@/store'
  export default {
    name: "SignatureDialog",
    props:{
      width:{
        type:[Number,String],
        default:800,
      },
      height:{
        type:[Number,String],
        default:300,
      },
      fileName:{
        type:String,
      },
      field:{
        type: String,
        default:'signCanvas'
      },
      bizPath:{
        type:String
      }
    },
    data() {
      return{
        title:LocleUtil.getLocale('m.common.button.signature'),
        visible:false,
        d_signed: false, // 签过名
        stageInfo: {},
        points: [],
        canvasTxt: null,
        personName: "",
        isSignCanvas: false,
        startX: 0,
        startY: 0,
        moveY: 0,
        moveX: 0,
        w: null,
        h: null,
        isDown: false,
        url: {
          uploadAction: YchConstant.PREFIX_SYSTEM + "/common/upload",
        },
      }
    },
    computed: {
      LocleUtil() {
        return LocleUtil
      },
      optionsData () {
        return {
          biz: this.bizPath || 'temp'
        }
      }
    },
    methods: {
      handleCancel(){
        this.visible = false
      },
      /**** mobile start ****/
      touchStart(ev) {
        let canvas = this.$refs[this.field]
        this.canvasTxt = canvas.getContext('2d')
        this.stageInfo = canvas.getBoundingClientRect()

        ev = ev || event
        ev.preventDefault()
        if (ev.touches.length == 1) {
          let obj = {
            x: ev.targetTouches[0].clienX,
            y: ev.targetTouches[0].clientY
          }
          this.startX = obj.x
          this.startY = obj.y
          this.canvasTxt.beginPath()
          this.canvasTxt.moveTo(this.startX, this.startY)
          this.canvasTxt.lineTo(obj.x, obj.y)
          this.canvasTxt.lineWidth = 4 //线条宽度
          this.canvasTxt.stroke()
          this.canvasTxt.closePath()
          this.points.push(obj)
        }
      },
      touchMove(ev) {
        ev = ev || event
        ev.preventDefault()
        if (ev.touches.length == 1) {
          let obj = {
            x: ev.targetTouches[0].clientX - this.stageInfo.left,
            y: ev.targetTouches[0].clientY - this.stageInfo.top
          }
          this.moveY = obj.y
          this.moveX = obj.x
          this.canvasTxt.beginPath()
          this.canvasTxt.moveTo(this.startX, this.startY)
          this.canvasTxt.lineTo(obj.x, obj.y)
          this.canvasTxt.lineWidth = 4 //线条宽度
          this.canvasTxt.stroke()
          this.canvasTxt.closePath()
          this.startY = obj.y
          this.startX = obj.x
          this.points.push(obj)
        }
      },
      touchEnd(ev) {
        ev = ev || event
        ev.preventDefault()
        if (ev.touches.length == 1) {
          let obj = {
            x: ev.targetTouches[0].clientX - this.stageInfo.left,
            y: ev.targetTouches[0].clientY - this.stageInfo.top
          }
          this.canvasTxt.beginPath()
          this.canvasTxt.moveTo(this.startX, this.startY)
          this.canvasTxt.lineTo(obj.x, obj.y)
          this.canvasTxt.lineWidth = 4 //线条宽度
          this.canvasTxt.stroke()
          this.canvasTxt.closePath()
          this.points.push(obj)
        }
        this.d_signed = true
      },
      /**** mobile end ****/
      /**** pc start ****/
      mouseDown(ev) {
        let canvas = this.$refs[this.field]
        this.canvasTxt = canvas.getContext('2d')
        this.stageInfo = canvas.getBoundingClientRect()
        ev = ev || event
        ev.preventDefault()
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY
        }
        this.startX = obj.x
        this.startY = obj.y
        this.canvasTxt.beginPath()
        this.canvasTxt.moveTo(this.startX, this.startY)
        this.canvasTxt.lineTo(obj.x, obj.y)
        this.canvasTxt.lineWidth = 4 //线条宽度
        this.canvasTxt.stroke()
        this.canvasTxt.closePath()
        this.points.push(obj)
        console.log('down')
        this.isDown = true
      },
      mouseMove(ev) {
        ev = ev || event
        ev.preventDefault()
        if (this.isDown && this.width-10 > ev.offsetX && this.height-10 > ev.offsetY && ev.offsetY-10 > 0 && ev.offsetX-10 > 0) {
          let obj = {
            x: ev.offsetX,
            y: ev.offsetY
          }
          this.moveY = obj.y
          this.moveX = obj.x
          this.canvasTxt.beginPath()
          this.canvasTxt.moveTo(this.startX, this.startY)
          this.canvasTxt.lineTo(obj.x, obj.y)
          this.canvasTxt.lineWidth = 4 //线条宽度
          this.canvasTxt.stroke()
          this.canvasTxt.closePath()
          this.startY = obj.y
          this.startX = obj.x
          this.points.push(obj)
        }else if(this.isDown){
          this.isDown = false
        }
      },
      mouseUp(ev) {
        ev = ev || event
        ev.preventDefault()
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY
        }
        this.canvasTxt.beginPath()
        this.canvasTxt.moveTo(this.startX, this.startY)
        this.canvasTxt.lineTo(obj.x, obj.y)
        this.canvasTxt.lineWidth = 4 //线条宽度
        this.canvasTxt.stroke()
        this.canvasTxt.closePath()
        this.points.push(obj)
        this.points.push({
          x: -1,
          y: -1
        })
        console.log('up')
        this.isDown = false
        this.d_signed = true
      },
      /**** pc end ****/

      // 重置
      overwrite() {
        this.d_signed = false
        this.$nextTick(() => {
          this.canvasTxt && this.canvasTxt.clearRect && this.canvasTxt.clearRect(0, 0, this.$refs[this.field] && this.$refs[this.field].width, this.$refs[this.field] && this.$refs[this.field].height);
          this.points = [];
        })
      },
      //验证canvas画布是否为空函数
      isCanvasBlank(canvas) {
        let blank = document.createElement('canvas');//系统获取一个空canvas对象
        blank.width = canvas.width;
        blank.height = canvas.height;
        return canvas.toDataURL() == blank.toDataURL();//比较值相等则为空
      },
      // 将base64转换成file对象
      dataURLtoFile(dataurl, fileName) {
        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)
        }
        var file = new File([u8arr], `${fileName}.${suffix}`, {
          type: mime
        })
        var formdata = new FormData() // 创建form对象
        formdata.append('file', file) // 通过append向form对象添加数据,可以通过append继续添加数//或formdata1.append('img',file);
        formdata.append('biz',this.optionsData.biz)
        return formdata
      },
      //保存
      handleOk() {
        let context = this.$refs[this.field]; // 获取html的canvas对象，我这个id="canvas"
        //判断是否为空
        if(this.isCanvasBlank(context)){
          return;
        }
        let fileName = this.fileName?this.fileName:new Date().getTime()
        let formdata = this.dataURLtoFile(context.toDataURL(),fileName)
        // let userId = store.getters.userInfo.id
        // uploadAction(this.url.uploadAction, formdata).then((res) => {
        //   if (res.success) {
        //     let img ={
        //       type: 'img',
        //       name: fileName,
        //       status: "done",
        //       uid: uidGenerator(),
        //       url: getFileAccessHttpUrl(res.message) || '',
        //       userId:userId
        //     }
        //     this.$emit('setSignature',img)
        //     this.overwrite();
        //     this.handleCancel()
        //   } else {
        //     this.messageUtil.error(res.message)
        //   }
        // })
        //this.$emit('addSignFile', {formdata: formdata, base64Data: context.toDataURL()}) //将数据返回给组件v-model绑定的值
        //签字保存后清空画布

    },
    //使用笔迹
    pasteSign() {

    },

  }
}
</script>

<style scoped>

</style>
