<template>
  <div>
    <div>
      <el-button type="primary" @click="fnOpen">手写签字</el-button>
    </div>
    <div v-if="modelValue" style="border: 1px dashed #ccc" class="mt-10">
      <img :src="modelValue" alt="" style="width: 100%" />
    </div>
  </div>
  <el-dialog v-model="visible" title="签字">
    <vue-esign
      ref="signRef"
      :width="800"
      :height="300"
      :is-crop="false"
      :is-clear-bg-color="false"
      :line-width="6"
      line-color="#000"
      bg-color="#fff"
    />
    <template #footer>
      <el-button @click="fnReset">重签</el-button>
      <el-button type="primary" @click="fnGenerate">确定</el-button>
      <el-button @click="fnClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { useTemplateRef } from "vue";
import { ElDialog, ElButton, ElMessage } from "element-plus";
import "element-plus/es/components/dialog/style/css";
import "element-plus/es/components/button/style/css";
import VueEsign from "vue-esign";

defineOptions({
  name: "AppSign",
});
const emits = defineEmits(["confirm"]);
const modelValue = defineModel({ type: String, default: "" });
const visible = defineModel("visible", { type: Boolean, default: false });
const signRef = useTemplateRef("signRef");
const fnOpen = () => {
  visible.value = true;
};
const fnReset = () => {
  signRef.value.reset();
};
const fnGenerate = () => {
  signRef.value
    .generate()
    .then((res) => {
      modelValue.value = res;
      emits("confirm", res);
      fnClose();
    })
    .catch(() => {
      ElMessage.warning("请签字！");
    });
};
const fnClose = () => {
  fnReset();
  visible.value = false;
};
</script>

<style scoped lang="scss">
.title {
  display: flex;
  justify-content: space-between;

  div {
    flex-basis: 33.333%;

    &:nth-child(2) {
      text-align: center;
    }

    &:nth-child(3) {
      padding-right: 30px;
      text-align: right;
    }
  }
}

canvas {
  border: 1px dashed #7e7d7d;
  margin: auto;
}
</style>
