<script setup>
/**
 * @file
 *
 * 【模块 export 内容】
 * Poster3D：3d移动动画的组件。
 *  props说明:
 *      @prop {Object}      position       包含x,y,y旋转的初始配置。
 *      @prop {Number}      animDuration   动画时间，默认1秒
 *      @prop {Object}      style          组件的width/height
 *      @prop {Object}      divStyle       提供给jsv3dDiv的宽高
 */

import { shallowRef, watch } from "vue";
import { Jsv3dDiv, getKeyFramesGroup } from "jsview";
const props = defineProps({
  position: { require: true, type: Object },
  xRotate: { require: true, type: Number },
  animDuration: { type: Number, default: 1 },
  style: { type: Object, require: true },
  divStyle: { type: Object, require: true },
});
const myPosition = {
  x: props.position.x,
  y: props.position.y,
  rotateY: props.position?.rotateY,
};
let myAnim = shallowRef("");
const styleShell = getKeyFramesGroup();
let aniName = "";
watch(
  () => props.position,
  (newValue, oldValue) => {
    if (newValue.rotateY !== 0) {
      aniName = `@keyframes go
    { 
    from { transform: translate3d(${-(
      newValue.x - myPosition.x
    )},0,0) rotate3d(0,1,0,${-newValue.rotateY}deg); } 
    to 
    { transform: translate3d(0,0,0)  rotate3d(0,1,0,${0}deg);  } }`;
      myAnim.value = `go ${props.animDuration}s`;
    } else {
      aniName = `@keyframes start
    { 
    from { transform: translate3d(${-(
      newValue.x - myPosition.x
    )},0,0) rotate3d(0,1,0,${myPosition.rotateY}deg); } 
    to 
    { transform: translate3d(0,0,0)  rotate3d(0,1,0,${
      newValue.rotateY
    }deg);  } }`;
      myAnim.value = `start ${props.animDuration}s`;
    }
    styleShell.insertRule(aniName);
    myPosition.x = newValue.x;
    myPosition.y = newValue.y;
    myPosition.rotateY = newValue?.rotateY;
  },
  { deep: true }
);
const myEnd = () => {
  const containsGo = aniName.includes("go");
  if (containsGo) {
    styleShell?.removeRule("go");
  } else {
    styleShell?.removeRule("start");
  }
  myAnim.value = null;
};
</script>
<template>
  <Jsv3dDiv
    :style="{
      width: props.style.width,
      height: props.style.height,
      left: props.position.x,
      top: props.position.y,
      transform: props.position.rotateY
        ? `rotate3d(0,1,0,${props.position.rotateY}deg)`
        : '',
      backgroundColor: '#FF1313',
      animation: myAnim,
    }"
    @animationend="myEnd"
  >
    <Jsv3dDiv :position="props.divStyle">
      <slot></slot>
    </Jsv3dDiv>
  </Jsv3dDiv>
</template>
<style scoped></style>
