import {
  defineComponent,
  reactive,
  ref,
  nextTick,
  onMounted,
  onUnmounted
} from 'vue';
import styles from './index.module.less';
import iconplay from '@views/attend-class/image/icon-pause.png';
import iconpause from '@views/attend-class/image/icon-play.png';
import iconReplay from '@views/attend-class/image/icon-replay.png';
import iconPreviewDownload from '@views/attend-class/image/icon-preivew-download2.png';
import iconFullscreen from '@views/attend-class/image/icon-fullscreen.png';
import iconFullscreenExit from '@views/attend-class/image/icon-fullscreen-exit.png';
import { NSlider, useMessage } from 'naive-ui';
import Vudio from 'vudio.js';
import tickMp3 from '@views/attend-class/image/tick.mp3';
import { saveAs } from 'file-saver';
import { exitFullscreen } from '/src/utils';

export default defineComponent({
  name: 'audio-play',
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    isEmtry: {
      type: Boolean,
      default: false
    },
    isDownload: {
      type: Boolean,
      default: false
    },
    fullscreen: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const videoId =
      'vFullscreen' + Date.now() + Math.floor(Math.random() * 100);
    const message = useMessage();
    const audioForms = reactive({
      isFullScreen: false, // 是否全屏
      paused: true,
      currentTimeNum: 0,
      currentTime: '00:00',
      durationNum: 0,
      duration: '00:00',
      showBar: true,
      afterMa3: true,
      timer: null as any
    });
    const canvas: any = ref();
    const audio: any = ref();
    let vudio: any = null;

    // 切换音频播放
    const onToggleAudio = (e?: MouseEvent) => {
      e?.stopPropagation();
      if (audio.value.paused) {
        onInit(audio.value, canvas.value);
        audio.value.play();
        audioForms.afterMa3 = false;

        setModelOpen();
      } else {
        audio.value.pause();

        clearTimeout(audioForms.timer);
        audioForms.showBar = true;
      }
      audioForms.paused = audio.value.paused;
    };

    const onInit = (audio: undefined, canvas: undefined) => {
      if (!vudio) {
        vudio = new Vudio(audio, canvas, {
          effect: 'waveform',
          accuracy: 256,
          width: 1024,
          height: 600,
          waveform: {
            maxHeight: 200,
            color: [
              [0, '#44D1FF'],
              [0.5, '#44D1FF'],
              [0.5, '#198CFE'],
              [1, '#198CFE']
            ],
            prettify: false
          }
        });
        vudio.dance();
      }
    };

    // 对时间进行格式化
    const timeFormat = (num: number) => {
      if (num > 0) {
        const m = Math.floor(num / 60);
        const s = num % 60;
        return (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s);
      } else {
        return '00:00';
      }
    };

    const onReplay = () => {
      if (!audio.value) return;
      audio.value.currentTime = 0;

      console.log(props.item);
    };

    // 下载资源
    const onDownload = () => {
      if (!props.item.content) {
        message.error('下载失败');
        return;
      }
      const fileUrl = props.item.content;
      const filename =
        props.item.title +
        (props.item.studentName ? '-' + props.item.studentName : '');
      const sfixx = fileUrl.substring(fileUrl.lastIndexOf('.'));
      // 发起Fetch请求
      fetch(fileUrl)
        .then(response => response.blob())
        .then(blob => {
          saveAs(blob, (filename || new Date().getTime()) + sfixx);
        })
        .catch(() => {
          message.error('下载失败');
        });
    };

    let vudio1 = null;
    const canvas1: any = ref();
    const audio1: any = ref();
    nextTick(() => {
      vudio1 = new Vudio(audio1.value, canvas1.value, {
        effect: 'waveform',
        accuracy: 256,
        width: 1024,
        height: 600,
        waveform: {
          maxHeight: 200,
          color: [
            [0, '#44D1FF'],
            [0.5, '#44D1FF'],
            [0.5, '#198CFE'],
            [1, '#198CFE']
          ],
          prettify: false
        }
      });
      vudio1.dance();
    });

    /** 全屏 */
    const isElementFullscreen = (element: any) => {
      const dom: any = document;
      return (
        element ===
        (dom.fullscreenElement ||
          dom.webkitFullscreenElement ||
          dom.mozFullScreenElement ||
          dom.msFullscreenElement)
      );
    };
    const onFullScreen = () => {
      const el: any = document.querySelector('#' + videoId);

      //   //进入全屏
      if (el) {
        if (isElementFullscreen(el)) {
          exitFullscreen();
        } else {
          (el.requestFullscreen && el.requestFullscreen()) ||
            (el.mozRequestFullScreen && el.mozRequestFullScreen()) ||
            (el.webkitRequestFullscreen && el.webkitRequestFullscreen()) ||
            (el.msRequestFullscreen && el.msRequestFullscreen());
        }
        // audioForms.isFullScreen = isElementFullscreen(el);
      }
    };

    /** 延迟收起模态框 */
    const setModelOpen2 = () => {
      clearTimeout(audioForms.timer);
      audioForms.showBar = !audioForms.showBar;
      audioForms.timer = setTimeout(() => {
        audioForms.showBar = false;
      }, 3000);
    };
    /** 延迟收起模态框 */
    const setModelOpen = () => {
      clearTimeout(audioForms.timer);
      audioForms.showBar = true;
      audioForms.timer = setTimeout(() => {
        audioForms.showBar = false;
      }, 3000);
    };

    const onFullScreenChange = () => {
      if (document.fullscreenElement) {
        audioForms.isFullScreen = true;
      } else {
        audioForms.isFullScreen = false;
      }
    };

    onMounted(() => {
      console.log(props.item, 'props.item');
      window.addEventListener('fullscreenchange', onFullScreenChange);
    });

    onUnmounted(() => {
      window.removeEventListener('fullscreenchange', onFullScreenChange);
    });

    return () => (
      <div class={styles.audioWrap} id={videoId} onClick={setModelOpen2}>
        <div class={styles.audioContainer}>
          <audio
            ref={audio}
            crossorigin="anonymous"
            src={props.item.content + '?time=1'}
            onEnded={() => {
              audioForms.paused = true;
            }}
            onPause={() => {
              clearTimeout(audioForms.timer);
              audioForms.showBar = true;
            }}
            onTimeupdate={() => {
              audioForms.currentTime = timeFormat(
                Math.floor(audio.value?.currentTime || 0)
              );
              audioForms.currentTimeNum = audio.value?.currentTime || 0;
            }}
            onLoadedmetadata={() => {
              audioForms.duration = timeFormat(
                Math.floor(audio.value?.duration)
              );
              audioForms.durationNum = audio.value?.duration;

              onToggleAudio();
            }}></audio>

          <canvas ref={canvas}></canvas>

          {audioForms.afterMa3 && (
            <div class={styles.tempVudio}>
              <audio ref={audio1} src={tickMp3} />
              <canvas ref={canvas1}></canvas>
            </div>
          )}
        </div>

        <div
          class={[
            styles.controls,
            audioForms.showBar ? '' : styles.sectionAnimate
          ]}
          onClick={(e: MouseEvent) => {
            e.stopPropagation();
            setModelOpen();
          }}>
          <div class={styles.actions}>
            <div class={styles.actionWrap}>
              <button class={styles.actionBtn} onClick={onToggleAudio}>
                {audioForms.paused ? (
                  <img class={styles.playIcon} src={iconplay} />
                ) : (
                  <img class={styles.playIcon} src={iconpause} />
                )}
              </button>
              <button class={styles.iconReplay} onClick={onReplay}>
                <img src={iconReplay} />
              </button>
            </div>
          </div>

          <div class={styles.slider}>
            <NSlider
              value={audioForms.currentTimeNum}
              step={0.01}
              max={audioForms.durationNum}
              tooltip={false}
              onUpdate:value={(val: number) => {
                audio.value.currentTime = val;
                audioForms.currentTimeNum = val;
                audioForms.currentTime = timeFormat(Math.round(val || 0));
              }}
            />
          </div>

          <div class={styles.actions}>
            <div class={styles.time}>
              <div
                class="plyr__time plyr__time--current"
                aria-label="Current time">
                {audioForms.currentTime}
              </div>
              <span class={styles.line}>/</span>
              <div
                class="plyr__time plyr__time--duration"
                aria-label="Duration">
                {audioForms.duration}
              </div>
            </div>
            <div class={styles.actionWrap}>
              {props.isDownload && (
                <button class={styles.iconDownload} onClick={onDownload}>
                  <img src={iconPreviewDownload} />
                </button>
              )}
              {props.fullscreen && (
                <button class={styles.iconDownload} onClick={onFullScreen}>
                  <img
                    src={
                      audioForms.isFullScreen
                        ? iconFullscreenExit
                        : iconFullscreen
                    }
                  />
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }
});
