<!-- eslint-disable vue/no-v-html -->
<template>
  <div class="write-base-preview" :style="getAreaStyle()">
    <SerialNumberPosition v-if="isEnable(data.property.sn_display_mode)" :property="data.property" />

    <div v-if="width" class="main">
      <h2>书写区</h2>
      <div class="esign-box">
        <vue-esign
          ref="esign"
          class="esign-canvas"
          :width="width"
          :height="150"
          :is-crop="isCrop"
          :line-width="lineWidth"
          :line-color="lineColor"
          :bg-color.sync="bgColor"
        />
        <div class="btn-box">
          <SvgIcon icon-class="clear" size="24" title="清除" @click="handleReset" />
          <SvgIcon icon-class="camera" size="24" title="保存" @click="handleGenerate" />
        </div>
      </div>
      <template v-if="data.write_base64[0]">
        <h2>展示区</h2>
        <img style="background-color: #f7f8fa" :src="data.write_base64[0]" alt="write-show" />
      </template>
    </div>
  </div>
</template>

<script>
import { getWriteBaseData } from '@/views/book/courseware/data/writeBase';

import PreviewMixin from '../common/PreviewMixin';
import vueEsign from 'vue-esign';

export default {
  name: 'WriteBasePreview',
  components: { vueEsign },
  mixins: [PreviewMixin],
  data() {
    return {
      data: getWriteBaseData(),
      lineWidth: 2,
      lineColor: '#000000',
      bgColor: '#f7f8fa',
      isCrop: false,
      width: 0,
    };
  },
  computed: {},
  watch: {},
  mounted() {
    this.width = document.getElementsByClassName('write-base-preview')[0].clientWidth - 16;
  },
  methods: {
    handleReset() {
      this.$refs.esign.reset();
      this.$nextTick(() => {
        this.bgColor = '#f7f8fa';
      });
    },
    handleGenerate() {
      this.$refs.esign
        .generate({ format: 'png', quality: 0.8 })
        .then((res) => {
          this.data.write_base64[0] = res;
          this.$forceUpdate();
        })
        .catch((err) => {
          console.error(err);
          // alert('生成图片失败：' + err.message);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
@use '@/styles/mixin.scss' as *;

.write-base-preview {
  @include preview-base;

  display: block;

  .main {
    h2 {
      margin: 5px 0;
      font-size: 14px;
    }

    .esign-box {
      position: relative;
      background-color: #f7f8fa;

      .btn-box {
        position: absolute;
        right: 10px;
        bottom: 10px;
        display: flex;
        gap: 5px;
        cursor: pointer;
      }
    }
  }
}
</style>
