<template>
  <view class="nana-vso-text">
    <Text 
      v-bind="props"
      :innerClass="['holder']"
      :innerStyle="{
        visibility: 'hidden',
        ...$props.innerStyle || {},
      }"
      :text="oneStr"
    />
    <view
      class="scroll"
      :style="{
        transform: `translateY(${currentScrollTop ? '0%' : '-50%'})`,
        transition: anim ? `linear ${animDuration}ms all` : 'none',
      }"
    >
      <Text 
        v-bind="props"
        :innerStyle="$props.innerStyle"
        :text="upText"
      />
      <Text 
        v-bind="props"
        :innerStyle="$props.innerStyle"
        :text="downText"
      />
    </view>
  </view>
</template>

<script setup lang="ts">
/**
 * 垂直滚动切换动画单个文字。默认是在 oneStr 更换时触发动画。
 */

import { nextTick, onMounted, ref, watch, type PropType } from 'vue';
import Text, { type TextProps } from '../basic/Text.vue';

export interface VerticalScrollOneTextProps extends TextProps {
  /**
   * 文字
   */ 
  oneStr?: string,
  /**
   * 动画时长
   * @default 230
   */
  animDuration?: number,
  /**
   * 动画方向
   * @default 'auto'
   */
  animDirection?: 'down'|'up'|'auto',
}

defineOptions({
  options: {
    virtualHost: true,
    styleIsolation: "shared",
  },
});

const props = withDefaults(defineProps<VerticalScrollOneTextProps>(), {
  oneStr: '',
  animDuration: 230,
  animDirection: 'auto',
});
const currentScrollTop = ref(true);
const upText = ref('');
const downText = ref('');
const anim = ref(false);

onMounted(() => {
  upText.value = props.oneStr;
})

watch(() => props.oneStr, (currentStr, prevStr) => {
  anim.value = false;

  if (!currentStr || !prevStr) {
    currentScrollTop.value = true;
    upText.value = currentStr;
    downText.value = currentStr;
    return;
  }
  
  const isDown = props.animDirection === 'down' ||
    //根据数字自动判断应该往上还是往下
    (props.animDirection === 'auto' && 
      currentStr.length === 1 && prevStr > currentStr && 
      !(prevStr === '9' && currentStr === '0'));
      
  if (isDown) {
    //下
    currentScrollTop.value = true;
    upText.value = prevStr;
    downText.value = currentStr;
    setTimeout(() => {
      currentScrollTop.value = false;
      anim.value = true;
    }, 90)
  } else {
    //上
    currentScrollTop.value = false;
    upText.value = currentStr;
    downText.value = prevStr;
    setTimeout(() => {
      currentScrollTop.value = true;
      anim.value = true;
    }, 90)
  }
})
</script>

<style lang="scss">
.nana-vso-text {
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: row;
  height: auto;
  width: auto;

  .holder {
    visibility: hidden;
    opacity: 0;
  }
  .scroll {
    position: absolute;
    display: flex;
    flex-direction: column;
    top: 0;
    left: 0;
  }
}
</style>

