<script>
import * as PIXI from "pixi.js";
import {load, throttle} from "../utils/tools.js";
import {Live2DModel} from "pixi-live2d-display";

window.PIXI = PIXI;

export default {
  name: "metaHuman",
  props: {
    voice: String
  },
  data() {
    return {
      ins: null,
      speech: null
    }
  },
  watch: {
    voice(v) {
      v && this.speak(v)
    }
  },
  methods: {
    initLive2d() {
      return load(window.Live2D && window.Live2DCubismCore)
          .then(() => Live2DModel.from("/live2d/ots14_1203/ots14_1203.model.json"))
          .then(model => {
            this.ins.stage.addChild(model)
            model.rotation = Math.PI;
            model.skew.x = Math.PI;
            model.x = 380
            model.y = 100
            model.scale.set(0.16, 0.16);
            // interaction
            model.on('hit', (hitAreas) => {
              if (hitAreas.includes('body')) {
                model.motion('tap_body');
              }
            });
            this.draggable(model)
          }).catch(err => console.log(err));
    },
    draggable(model) {
      model.buttonMode = true;
      model.on("pointerdown", (e) => {
        model.dragging = true;
        model._pointerX = e.data.global.x - model.x;
        model._pointerY = e.data.global.y - model.y;
      });
      model.on("pointermove", (e) => {
        if (model.dragging) {
          model.position.x = e.data.global.x - model._pointerX;
          model.position.y = e.data.global.y - model._pointerY;
        }
      });
      model.on("pointerupoutside", () => (model.dragging = false));
      model.on("pointerup", () => (model.dragging = false));
    },
    speak(text) {
      if (!this.speech) {
        this.speech = new SpeechSynthesisUtterance()
      }
      const synth = speechSynthesis
      throttle(() => {
        this.speech.text = text
        // this.speech.voice = speechSynthesis.getVoices()[13]
        synth.cancel()
        synth.speak(this.speech)
      })
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.ins = new PIXI.Application({
        autoStart: true,
        resizeTo: this.$el,
        backgroundAlpha: 0,
      })
      this.$el.appendChild(this.ins.view)
      this.initLive2d().then(() => this.speak("大家好,我是AI小助手"))
    })
  }
}
</script>

<template>
  <section class="metaHuman"/>
</template>

<style scoped lang="scss">
.metaHuman {
  width: 375px;
}

</style>
