import { defineComponent, nextTick, 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.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';
import tickMp3 from '../../image/tick.mp3';

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,
      dragStatus: false, // 是否开始拖动
      playState: 'pause' as 'play' | 'pause',
      vudio: null as any,
      afterMa3: true,
      count: 0
    });
    const canvasRef: any = ref();
    const audioRef: any = ref();
    const contetRef = ref();

    watch(
      () => props.show,
      val => {
        data.count = 0;
        if (val && props.item.autoPlay) {
          // data.count = 0;
          // audioRef.value.src = item.value.content;
          onToggleAudio();
        } else {
          audioRef.value.pause();
          // audioRef.value.src = '';
          data.playState = 'pause';
          // data.vudio = null;
        }
      }
    );
    // watch(
    //   () => props.item,
    //   () => {
    //     // data.count = 0;
    //     // audioRef.value.src = item.value.content;
    //     onToggleAudio();
    //   }
    // );
    watch(
      () => props.pageVisibility,
      val => {
        if (val === 'hidden' && props.show) {
          audioRef.value.pause();
          data.playState = 'pause';
        }
      }
    );

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

    const onInit = (audio: undefined, canvas: undefined) => {
      if (!data.vudio && data.count > 1) {
        console.log(data.vudio, 'data.vudio');
        try {
          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();
        } catch (e) {
          console.log(e, 'e');
        }
      } else {
      }
    };
    /** 加载成功 */
    const onLoadedmetadata = () => {
      data.duration = audioRef.value?.duration;
      // onInit(audioRef.value, canvasRef.value);
      if (props.item.autoPlay && audioRef.value && props.show) {
        // data.vudio = null;
        // data.count = 0;
        onToggleAudio();
      }

      // if (audioRef.value) {
      //   audioRef.value.stop = () => {
      //     audioRef.value?.pause();
      //   };
      //   audioRef.value.onPlay = () => {
      //     audioRef.value?.play();
      //     onInit(audioRef.value, canvasRef.value);
      //   };
      // }
    };

    /** 改变播放时间 */
    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');
    };

    let vudio1 = null;
    const canvas1: any = ref();
    const audio1: any = ref();
    nextTick(() => {
      const rect = contetRef.value.getBoundingClientRect() || {
        width: 200,
        height: 200
      };
      vudio1 = new Vudio(audio1.value, canvas1.value, {
        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
        }
      });
      vudio1.dance();
    });
    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 && data.playState === 'pause') return;
                if (data.count <= 1) {
                  data.count += 1;
                  onInit(audioRef.value, canvasRef.value);
                }
                // 开始拖动时也不能更新
                if (data.dragStatus) 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>

            {data.afterMa3 && (
              <div class={styles.tempVudio}>
                <audio ref={audio1} src={tickMp3} />
                <canvas ref={canvas1}></canvas>
              </div>
            )}
          </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);
              }}
              onDragStart={() => {
                data.dragStatus = true;
                console.log('onDragStart');
              }}
              onDragEnd={() => {
                data.dragStatus = false;
                console.log('onDragEnd');
              }}
            />
          </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>
    );
  }
});
