import {
  App,
  computed,
  defineComponent,
  nextTick,
  onActivated,
  onMounted,
  onUnmounted,
  ref,
  Teleport,
  Transition,
  watch
} from 'vue';

// @ts-ignore
import style from './style/index.module.less';

// import './style/index.less';

const Loading = defineComponent({
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  setup(props, { attrs, slots }) {
    const createLoading = 'loading...'
      .split('')
      .map(_ => (
        <div
          class={`${style['loading-dot-wrapper__dot']} float-left mx-[0.5px]`}
        >
          {_}
        </div>
      ));

    const visibleDot = ref(false);
    const run = ref(false);
    const clsRun = computed(() => (run.value ? `${style['run']}` : ''));

    let t1: number, t2: number;
    const loop = () => {
      visibleDot.value = true;
      run.value = true;
      t1 = setTimeout(() => {
        run.value = false;
        t2 = setTimeout(() => {
          loop();
        }, 400);
        // 2.6s
      }, 2600);
    };

    const unmount = () => {
      clearTimeout(t2);
      clearTimeout(t1);
      run.value = false;
      visibleDot.value = false;
    };

    // 和传统不一样的是，这里初始化就会被触发
    watch(
      () => props.visible,
      (val: boolean) => {
        if (!val) {
          unmount();
        } else {
          loop();
        }
      }
    );
    onUnmounted(unmount);
    onActivated(unmount);

    return () => (
      <Teleport to={'body'}>
        <Transition name="loading-fade">
          <div
            class={`${style.loading} fixed top-0 left-0 w-full h-full z-[9999] bg-[rgba(255,255,255,.8)] select-none`}
            v-show={props.visible}
          >
            <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-center">
              <img
                class="align-middle w-[125px]"
                src={require('./assets/imgs/loading.gif')}
                alt="loading"
              />
              <div
                style={{ visibility: visibleDot.value ? 'visible' : 'hidden' }}
                class={`${style['loading-dot-wrapper']} ${clsRun.value} flex justify-center text-[#999] text-[14px] after:block after:content-[''] after:clear-both`}
              >
                {createLoading}
              </div>
            </div>
          </div>
        </Transition>
      </Teleport>
    );
  }
});

export default Loading as typeof Loading & {
  install: (app: App, ...options: any[]) => any;
};
