<template>
  <view 
    :id="id" 
    class="nana-horizontal-scroll-text" 
    :style="{
      ...outerStyle,
      justifyContent: selectStyleType(textAlign, '', {
        center: 'center',
        left: 'flex-start',
        right: 'flex-end',
        '': undefined,
      }),
    }"
  >
    <view 
      class="inner"
      :style="{
        animation: scrollAble ? `${animDuration}ms linear 0s ${props.direction === 'left' ? 'horizontalScrollTextLeft' : 'horizontalScrollTextRight'} infinite` : 'none',
      }"
    >
      <Text ref="realTextRef" v-bind="$props" :innerClass="['text']" />
    </view>
    <Text v-bind="$props" :innerClass="['placeholder','text']" />
  </view>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, onUpdated, ref } from 'vue';
import type { TextProps } from '../basic/Text.vue';
import type { ViewStyle } from '../theme/ThemeDefine';
import Text from '../basic/Text.vue';
import { RandomUtils, waitTimeOut } from '@imengyu/imengyu-utils';
import { selectStyleType } from '../theme/ThemeTools';

export interface HorizontalScrollTextProps extends TextProps {
  /**
   * 动画持续时间，单位毫秒
   * @default 25000
   */
  animDuration?: number,
  /**
   * 是否滚动
   * @default true
   */
  scroll?: boolean,
  /**
   * 外部样式
   */
  outerStyle?: ViewStyle,
  /**
   * 滚动方向
   * @default 'left'
   */
  direction?: 'left' | 'right',
}

const id = RandomUtils.genNonDuplicateID(12);
const scrollAble = ref(false);
const instance = getCurrentInstance();
const realTextRef = ref();

const props = withDefaults(defineProps<HorizontalScrollTextProps>(), {
  animDuration: 25000,
  scroll: true,
  direction: 'left',
});

async function lodScrollInfo() {
  if (!props.scroll) {
    scrollAble.value = false;
    return;
  }
  await waitTimeOut(200);

  const conWidth = await new Promise<number>((resolve) => {
    uni.createSelectorQuery()
      // #ifdef MP
      .in(instance)
      // #endif
      .select(`#${id}`)
      .boundingClientRect((data) => resolve((data as UniApp.NodeInfo)?.width ?? 0))
      .exec();
  })

  if (!realTextRef.value) return;

  let textWidth = await realTextRef.value.measureTextWidth();
  //console.log('textWidth', textWidth, 'conWidth', conWidth);
  
  if (textWidth == conWidth) { 
    await waitTimeOut(200);
    textWidth = await realTextRef.value.measureTextWidth();
  }
  scrollAble.value = conWidth < textWidth;
}

onMounted(() => {
  lodScrollInfo();
})
onUpdated(() => {
  lodScrollInfo();
})

defineOptions({
  options: {
    virtualHost: true,
    styleIsolation: "shared",
  },
})
</script>

<style lang="scss">
.nana-horizontal-scroll-text {
  position: relative;
  overflow: hidden;
  white-space: nowrap;
  display: flex;
  flex-direction: row;
  align-items: center;

  .placeholder {
    visibility: hidden;
  }
  .text {
    white-space: nowrap;
    overflow: hidden;
  }
  .inner {
    position: absolute;

    &.scroll {
      animation: 25000ms linear 0s infinite normal none running horizontalScrollText;
    }
  }
}
</style>