import { defineComponent, reactive, toRefs, watch } from 'vue';
import { ref } from 'vue';
import styles from './index.module.less';

import iconLoop from '../../image/icon-loop.svg';
import iconLoopActive from '../../image/icon-loop-active.svg';
import iconplay from '../../image/icon-play.svg';
import iconpause from '../../image/icon-pause.svg';
import { NSlider } from 'naive-ui';
import Vudio from 'vudio.js';
import { getSecondRPM } from '@/helpers/utils';

export default defineComponent({
  name: 'video-play',
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    show: {
      type: Boolean,
      default: false
    },
    pageVisibility: {
      type: String,
      default: ''
    },
    showModel: {
      type: Boolean,
      default: false
    },
    isEmtry: {
      type: Boolean,
      default: false
    }
  },
  emits: ['loadedmetadata', 'togglePlay', 'ended', 'reset'],
  setup(props, { emit }) {
    const { item, isEmtry } = toRefs(props);
    const data = reactive({
      timer: null as any,
      currentTime: 0,
      duration: 0,
      loop: false,
      playState: 'pause' as 'play' | 'pause',
      vudio: null as any
    });
    const canvasRef: any = ref();
    const audioRef: any = ref();
    const contetRef = ref();

    watch(
      () => props.show,
      val => {
        if (val) {
          onToggleAudio();
        } else {
          audioRef.value.pause();
        }
      }
    );
    watch(
      () => props.pageVisibility,
      val => {
        if (val === 'hidden' && props.show) {
          audioRef.value.pause();
        } else {
          if (props.show){
            onToggleAudio();
          }
        }
      }
    );

    // 切换音频播放
    const onToggleAudio = () => {
      if (audioRef.value.paused) {
        onInit(audioRef.value, canvasRef.value);
        audioRef.value.play();
        data.playState = 'play';
      } else {
        audioRef.value.pause();
        data.playState = 'pause';
      }
    };

    const onInit = (audio: undefined, canvas: undefined) => {
      if (!data.vudio) {
        const rect = contetRef.value.getBoundingClientRect() || {
          width: 200,
          height: 200
        };
        data.vudio = new Vudio(audio, canvas, {
          effect: 'waveform',
          accuracy: 128,
          width: rect.width,
          height: rect.height,
          waveform: {
            maxHeight: 160,
            color: [
              [0, '#44D1FF'],
              [0.5, '#44D1FF'],
              [0.5, '#198CFE'],
              [1, '#198CFE']
            ],
            prettify: false
          }
        });
        data.vudio.dance();
      }
    };
    /** 加载成功 */
    const onLoadedmetadata = () => {
      data.duration = audioRef.value.duration;
      // 加载成功后台, 如果是第一次加载, 且是show状态, 则播放
      if (props.show) {
        onToggleAudio();
      }
    };

    /** 改变播放时间 */
    const handleChangeTime = (val: number) => {
      data.currentTime = val;
      clearTimeout(data.timer);
      data.timer = setTimeout(() => {
        audioRef.value.currentTime = val;
        data.timer = null;
      }, 300);
    };

    /** 播放结束 */
    const onEnded = () => {
      data.playState = 'pause';
      emit('ended');
    };
    return () => (
      <div class={styles.videoWrap}>
        <div class={styles.content}>
          <div ref={contetRef} class={styles.contentWrap}>
            <canvas ref={canvasRef}></canvas>
            <audio
              src={isEmtry.value ? '' : item.value.content}
              ref={audioRef}
              loop={data.loop}
              onLoadedmetadata={onLoadedmetadata}
              onTimeupdate={() => {
                if (data.timer) return;
                data.currentTime = audioRef.value.currentTime;
              }}
              onEnded={onEnded}
              crossorigin="anonymous"
              playsinline="false"></audio>
          </div>
        </div>

        <div class={[styles.controls, props.showModel ? '' : styles.hide]}>
          <div class={styles.time}>
            <div>{getSecondRPM(data.currentTime)}</div>
            <div>{getSecondRPM(data.duration)}</div>
          </div>
          <div class={styles.slider}>
            <NSlider
              tooltip={false}
              step={0.01}
              class={styles.timeProgress}
              value={data.currentTime}
              max={data.duration}
              onUpdate:value={val => handleChangeTime(val)}
            />
          </div>
          <div class={styles.actions}>
            <div class={styles.actionBtn} onClick={() => onToggleAudio()}>
              <img src={data.playState === 'pause' ? iconplay : iconpause} />
            </div>
            <div
              class={styles.actionBtn}
              onClick={() => (data.loop = !data.loop)}>
              <img src={data.loop ? iconLoopActive : iconLoop} />
            </div>
          </div>
        </div>
      </div>
    );
  }
});
