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

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

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', 'close'],
  setup(props, { emit }) {
    const { item, isEmtry } = toRefs(props);
    const data = reactive({
      timer: null as any,
      currentTime: 0,
      duration: 0.1,
      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();
          data.playState = 'pause';
        }
      }
    );
    watch(
      () => props.pageVisibility,
      val => {
        if (val === 'hidden' && props.show) {
          audioRef.value.pause();
          data.playState = 'pause';
        }
      }
    );

    // 切换音频播放
    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;
    };

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

    /** 播放结束 */
    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 + '?t=2'}
              ref={audioRef}
              loop={data.loop}
              onLoadedmetadata={onLoadedmetadata}
              onTimeupdate={() => {
                if (data.timer && data.playState === 'pause') return;
                data.currentTime = audioRef.value.currentTime;
              }}
              onError={() => {
                console.log('error');
                audioRef.value.pause();
                data.playState = 'pause';
              }}
              onPause={() => {
                console.log('pause');
                data.playState = 'pause';
              }}
              onEnded={onEnded}
              crossorigin="anonymous"
              playsinline="false"></audio>
          </div>
        </div>

        <div
          class={[styles.controls, props.showModel ? '' : styles.hide]}
          onClick={(e: Event) => {
            e.stopPropagation();
          }}
          onTouchmove={(e: TouchEvent) => {
            emit('close');
          }}>
          <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)}
            /> */}
            <Slider
              step={0.01}
              class={styles.timeProgress}
              v-model={data.currentTime}
              max={data.duration}
              onUpdate:modelValue={val => {
                handleChangeTime(val);
              }}
            />
          </div>
          <div class={styles.actions} onClick={() => emit('close')}>
            <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>
    );
  }
});
