<template>
  <div>
    <el-dialog
      v-dialogDrag
      :visible.sync="visible"
      :close-on-click-modal="false"
      width="550px"
      title="电子签名"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="在线签名" name="handleSign">
          <!--手写 - satrt-->
          <div>
            <VueSignaturePad
              id="signature"
              ref="signaturePad"
              width="486px"
              height="246px"
              :options="options"
            />
          </div>
          <!--手写 - end-->
        </el-tab-pane>
        <el-tab-pane label="导入签名" name="importSign">
          <!--导入 - satrt-->
          <el-upload
            multiple
            type="drag"
            :action="action"
            :on-success="_handelsuccess"
            :before-upload="_beupload"
            :data="dataObj"
            :with-credentials="true"
            :show-file-list="false"
            :accept="accept"
          >
            <div style="padding: 20px 0;width:100%">
              <Icon type="ios-cloud-upload" size="52" style="color: #3399ff" />
              <p>
                点击或拖拽进行上传签名，建议图片大小为<a class="red-color">
                  120*60px(.png格式)
                </a>
              </p>
            </div>
          </el-upload>
          <!--导入 - satrt-->
        </el-tab-pane>
      </el-tabs>
      <div style="margin-top: 20px;text-align: center;border: 1px solid #eee;padding: 10px">
        <img :src="imgUrl" alt="电子签名" style="width:120px;height:60px">
      </div>
      <div v-show="activeName === 'handleSign'" slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import VueSignaturePad from 'vue-signature-pad'
import axios from 'axios'
import global from '../../../api/config'

export default {
  components: { VueSignaturePad },
  data() {
    return {
      footerList: [
        { name: '清除', type: '' },
        { name: '后退', type: '' },
        { name: '取消', type: '' },
        { name: '保存', type: 'primary' }
      ],
      visible: false,
      action: '',
      dataObj: {
        file: ''
      },
      userId: '',
      activeName: 'handleSign',
      imgUrl: '',
      options: {
        velocityFilterWeight: 1.0 // 调整笔画粗细
      },
      accept: '.png,.PNG'
    }
  },
  methods: {
    _open(id) {
      this.userId = id
      this.action = global.baseURL + '/v1/file_signature/' + id
      this.visible = true
      // 设置签名的宽度与高度（强制赋值）
      $('#signature canvas').attr('width', '480px')
      $('#signature canvas').attr('height', '240px')
      this.activeName = 'handleSign'
      this.imgUrl =
        global.baseURL +
        '/v1/file_signature/download/' +
        id +
        '?' +
        Math.random()
      this.$nextTick(() => {
        this._clearSign()
      })
    },
    // excel文件导入
    _beupload(file) {
      const type = !!(file.type === 'image/png')
      if (!type) {
        this.$message.error('请上传格式为png的图片!')
      }
      this.dataObj.file = file.name
      return type
    },
    _handelsuccess(response, file, fileList) {
      // 上传成功
      if (response.success) {
        this.$message.success('上传成功！')
        this._refresh()
      } else {
        this.$message.warning(response.msg)
      }
    },
    // modal-footer
    _footerResult(name) {
      this._hideLoading()
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '清除':
          this._clearSign()
          break
        case '后退':
          this._undo()
          break
        case '保存':
          this._ok()
          break
      }
    },
    _hideLoading() {
      this.$refs.footerModal._hideLoading()
    },
    _cancel() {
      this.visible = false
    },
    // 保存
    _ok() {
      const result = this.$refs.signaturePad.saveSignature()
      const uri = global.baseURL + '/v1/file_signature/' + this.userId
      if (result.data) {
        const instanceFile = axios.create()
        instanceFile.defaults.withCredentials = true
        const formData = new FormData()
        formData.append(
          'file',
          this.$baseCharCode(result.data, 'image/png'),
          'signature.png'
        )
        instanceFile.post(uri, formData).then(res => {
          if (res.data.data) {
            this.$message.success('保存成功')
            this._clearSign()
            this._refresh()
          } else {
            this.$message.error('保存失败')
          }
        })
      } else {
        this.$message.warning('签名后方可保存！')
      }
    },
    // 刷新签名
    _refresh() {
      this.imgUrl =
        global.baseURL +
        '/v1/file_signature/download/' +
        this.userId +
        '?' +
        Math.random()
    },
    // 后退
    _undo() {
      this.$refs.signaturePad.undoSignature()
    },
    // 清除
    _clearSign() {
      this.$refs.signaturePad.clearSignature()
    }
  }
}
</script>
<style>
#signature {
  border: double 3px transparent;
  border-radius: 5px;
  background-image: linear-gradient(white, white),
    radial-gradient(circle at top left, #00a0e9, #32b16c);
  background-origin: border-box;
  background-clip: content-box, border-box;
}
</style>
