<template>
  <div class="kole-sign">
    <div class="kole-sign-pad" ref="pad">
      <canvas ref="canvas" class="kole-sign-canvas" @mousedown="down" @mousemove="move" @mouseup="up" @touchstart="down" @touchmove="move" @touchend="up"></canvas>
      <div class="kole-sign-placeholder" v-show="!hasInk">请在此处签名</div>
    </div>
    <div class="kole-sign-actions">
      <button class="kole-btn" @click="undo">撤销</button>
      <button class="kole-btn" @click="clear">清除</button>
      <button class="kole-btn kole-btn--primary" @click="save">保存</button>
      <span class="kole-sign-preview" v-if="saved">{{ saved }}</span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'KoleSignaturePad',
  data() {
    return { drawing: false, last: null, strokes: [], cur: [], hasInk: false, saved: '' };
  },
  mounted() { this.fit(); window.addEventListener('resize', this.fit); this.$once('hook:beforeDestroy', () => window.removeEventListener('resize', this.fit)); },
  methods: {
    fit() { var r = this.$refs.pad.getBoundingClientRect(); this.$refs.canvas.width = r.width; this.$refs.canvas.height = r.height; this.redraw(); },
    pos(e) { var r = this.$refs.canvas.getBoundingClientRect(); var t = e.touches && e.touches[0]; return { x: (t ? t.clientX : e.clientX) - r.left, y: (t ? t.clientY : e.clientY) - r.top }; },
    down(e) { e.preventDefault(); this.drawing = true; this.last = this.pos(e); this.cur = [this.last]; this.strokes.push(this.cur); this.hasInk = true; },
    move(e) { if (!this.drawing) return; e.preventDefault(); var p = this.pos(e); this.ctx().lineTo(p.x, p.y); this.ctx().stroke(); this.cur.push(p); },
    up() { this.drawing = false; this.last = null; },
    ctx() { return this.$refs.canvas.getContext('2d'); },
    undo() { this.strokes.pop(); this.redraw(); if (!this.strokes.length) this.hasInk = false; },
    clear() { this.strokes = []; this.redraw(); this.hasInk = false; this.saved = ''; },
    save() { this.saved = '已导出（' + this.$refs.canvas.width + '×' + this.$refs.canvas.height + '）'; },
    redraw() {
      var c = this.$refs.canvas, x = c.getContext('2d');
      x.clearRect(0, 0, c.width, c.height);
      x.strokeStyle = '#1F2329'; x.lineWidth = 2; x.lineCap = 'round'; x.lineJoin = 'round';
      this.strokes.forEach(function (s) {
        x.beginPath();
        s.forEach(function (p, i) { i ? x.lineTo(p.x, p.y) : x.moveTo(p.x, p.y); });
        x.stroke();
      });
    }
  }
};
</script>

<style src="./SignaturePad.css"></style>
