<template>
  <div v-if="bookText" class="strockplay-redInner">
    <div v-if="playStorkes" :class="['strock-play-box']" @click="playHanzi">
      <SvgIcon icon-class="hanzi-strock-play" class="strock-play-btn" />
    </div>
    <div class="character-target-box">
      <SvgIcon icon-class="hanzi-writer-bg" class="character-target-bg" />
      <div :id="targetDiv" :ref="targetDiv" class="character-target-div"></div>
    </div>
  </div>
</template>

<script>
const HanziWriter = require('hanzi-writer');
export default {
  components: {},
  props: {
    bookText: {
      type: String,
      default: '',
    },
    targetDiv: {
      type: String,
      default: '',
    },
    playStorkes: {
      type: Boolean,
      default: true,
    },
    strokeColor: {
      type: String,
      default: '',
    },
    bookStrokes: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      writer: null,
    };
  },
  computed: {},
  watch: {
    targetDiv: {
      handler(val, oldVal) {
        if (val !== oldVal) {
          this.$nextTick(() => {
            this.initHanziwrite();
          });
        }
      },
      deep: true,
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initHanziwrite();
    });
  },
  // 方法集合
  methods: {
    initHanziwrite() {
      let _this = this;
      if (this.$refs[this.targetDiv]) {
        let svg_arr = this.$refs[this.targetDiv].querySelectorAll('svg');
        svg_arr.forEach((item) => {
          item.remove();
        });
      }
      this.writer = HanziWriter.default.create(this.targetDiv, this.bookText, {
        charDataLoader(char, onComplete) {
          onComplete(_this.bookStrokes);
        },
        padding: 5,
        showOutline: true,
        strokeColor: this.strokeColor ? this.strokeColor : '#000',
      });
    },
    playHanzi(event) {
      event.stopPropagation();
      this.writer.animateCharacter();
    },
  },
};
</script>

<style lang="scss" scoped>
.strockplay-redInner {
  position: relative;
  box-sizing: border-box;
  width: 64px; // 444px
  height: 64px; // 480px
}

.character-target-div {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 99;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.character-target-box {
  position: relative;
  width: 100%;
  height: 100%;
}

.character-target-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  color: #dedede;
}

.strock-play-box {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 11px;
  height: 11px;
  color: $hanzi-writer-color;
  cursor: pointer;
}
</style>
