import { defineComponent, reactive, ref, nextTick } 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-download.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';

export default defineComponent({
  name: 'audio-play',
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    isEmtry: {
      type: Boolean,
      default: false
    },
    isDownload: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const message = useMessage();
    const audioForms = reactive({
      paused: true,
      currentTimeNum: 0,
      currentTime: '00:00',
      durationNum: 0,
      duration: '00:00',
      showBar: true,
      afterMa3: true
    });
    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;
      } else {
        audio.value.pause();
      }
      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;
      // 发起Fetch请求
      fetch(fileUrl)
        .then(response => response.blob())
        .then(blob => {
          saveAs(blob, filename || new Date().getTime() + '.mp3');
        })
        .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();
    });

    return () => (
      <div class={styles.audioWrap}>
        <div class={styles.audioContainer}>
          <audio
            ref={audio}
            crossorigin="anonymous"
            src={props.item.content + '?time=1'}
            onEnded={() => {
              audioForms.paused = true;
            }}
            onTimeupdate={() => {
              audioForms.currentTime = timeFormat(
                Math.floor(audio.value?.currentTime || 0)
              );
              audioForms.currentTimeNum = audio.value.currentTime;
            }}
            onLoadedmetadata={() => {
              audioForms.duration = timeFormat(
                Math.floor(audio.value.duration)
              );
              audioForms.durationNum = audio.value.duration;
            }}></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();
          }}>
          <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.iconReplay}
                  onClick={onDownload}
                  style={{ marginLeft: '15px' }}>
                  <img src={iconPreviewDownload} />
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }
});
