<template>
  <div v-if="!dialog">
    <div>
      <el-button type="primary" @click="fnOpen">手写签字</el-button>
    </div>
    <div style="border: 1px dashed #ccc" class="mt-10" v-if="modelValue">
      <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"
      :line-width="6"
      line-color="#000"
      bg-color="#FFFFFF"
    />
    <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 VueEsign from "vue-esign";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { useVModel } from "@vueuse/core";

defineOptions({
  name: "LayoutSign",
});
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  dialog: {
    type: Boolean,
    default: false,
  },
  visible: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(["update:modelValue", "update:visible", "confirm"]);
const signRef = ref(null);
const visible = props.dialog ? useVModel(props, "visible", emits) : ref(false);
const fnOpen = () => {
  visible.value = true;
};
const fnReset = () => {
  signRef.value.reset();
};
const fnGenerate = () => {
  signRef.value
    .generate()
    .then((res) => {
      emits("update:modelValue", 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>
