<script setup lang="ts">
import { stat } from "fs";
import { kill } from "process";
import { showToast } from "vant";
import wx from "weixin-js-sdk";

// 播放状态
const state = ref(false);
const stateChange = (stateNew: boolean) => {
  console.log("ooo");
  var audio = document.getElementById("music1");
  if (stateNew) {
    audio!.play();
  } else {
    audio!.pause();
  }
  state.value = stateNew;
};
const getAssetURL = (image: string) => {
  return new URL(`../assets/img/${image}`, import.meta.url).href;
};

const props = defineProps({
  audioUrl: {
    default: "",
    type: String,
  },
});

const allTime = ref("");

// 拖拽(鼠标按下)
const handleMousedown = (e: any) => {
  const progressBg = document.getElementById("progressBg");

  // 改变播放状态
  state.value = false;
  // 计算进度条距离
  let moveMin = progressBg?.offsetParent?.offsetLeft + progressBg?.offsetLeft;
  let moveMax =
    progressBg?.offsetParent?.offsetLeft +
    progressBg?.offsetLeft +
    progressBg?.clientWidth;

  console.log(document, e);
  if (e.targetTouches[0].pageX >= moveMax) {
    return;
  } else if (e.targetTouches[0].pageX <= moveMin) {
    return;
  }
  // circle!.style.left = e.targetTouches[0].pageX - moveMin - circleWidth + "px";
  updateProgress2(e.targetTouches[0].pageX - moveMin);
};

// 更新进度条（拖动进度条）
const updateProgress2 = (moveX: number) => {
  console.log(moveX);
  const progressBg = document.getElementById("progressBg");
  const progressBar = document.getElementById("progressBar");

  var audio = document.getElementById("music1");
  //当前移动的位置 = 当前移动的位置 / 当前进度条的可视长度    //this.$refs.progress.clientWidth 注意一定要拿总长度 否则会拿进度条已经走过的长度
  let clickProgress = moveX / progressBg!.clientWidth;
  //设置播放的时间 = 总时长 * 当前点击的长度
  audio!.currentTime = audio!.duration * clickProgress;
  //设置移动的位置
  progressBar!.style.width = moveX + "px";

  var audio = document.getElementById("music1");
  setTimeout(() => {
    audio!.play();
    state.value = true;
  }, 200);
};

// 更新进度条（播放中）
const updateProgress = (e: any) => {
  e.target.autoplay = true
  const progressBar = document.getElementById("progressBar");
  var value = e.target.currentTime / e.target.duration;
  if (progressBar) {
    progressBar!.style.width = value * 100 + "%";
    if (e.target.currentTime === e.target.duration) {
      state.value = false;
    }
  } else {
    state.value = true;
  }
};

const durationRef = ref(null);

const formatePlayerDuration = (node: any) => {
  node.onloadedmetadata = (e: any) => {
    const audio = e.target;
    const audioDuration = audio.duration;
    if (audioDuration === Infinity) {
      audio.currentTime = 1e101;
      audio.ontimeupdate = () => {
        audio.ontimeupdate = () => {
          return;
        };
        // 不重新设置currtTime,会直接触发audio的ended事件，因为之前将currentTime设置成了一个比音频时长还大的值。所以要将currentTime重置为初始状态。
        // 注: 这里有一个问题，直接设置为0 是不起作用的。需要重新设置一下audio.currentTime = 1e101;然后再设置为
        audio.currentTime = 1e101;
        audio.currentTime = 0;
      };
    }
  };
};

// 计算音频的时长
const countAudioTime = async () => {
  var audio = document.getElementById("music1");

  while (isNaN(audio!.duration) || audio!.duration === Infinity) {
    // 延迟一会 不然网页都卡死
    await new Promise((resolve) => setTimeout(resolve, 200));
    // 设置随机播放时间，模拟调进度条
    // audio!.currentTime = 10000000 * Math.random();
    durationRef.value = timeToMinute(audio!.duration);
  }
  // showToast(audio!.duration);
  // console.log("音频的总时长:", audio.duration);
};

const getDuration = () => {
  var audio = document.getElementById("music1");
  countAudioTime();
  // formatePlayerDuration(audio)
  setTimeout(() => {
    durationRef.value = timeToMinute(audio!.duration);
    // showToast(isNaN(audio!.duration), audio!.duration);
  }, 100);
};
const timeToMinute = (times: any) => {
  var t = "";
  if (times > -1) {
    var min = Math.floor(times / 60) % 60;
    var sec = times % 60;
    if (min < 10) {
      t += "0";
    }
    t += min + ":";
    if (sec < 10) {
      t += "0";
    }
    t += sec.toFixed(2);
  }
  t = t?.substring(0, t.length - 3);
  return t;
};

const clear = () => {
  const progressBar = document.getElementById("progressBar");
  progressBar!.style.width = 0 + "px";
  var audio = document.getElementById("music1");
  audio!.play();
  state.value = true;
};

//暴露state和play方法
defineExpose({
  clear,
});

const autoPlayFn = () => {
  const IS_IOS = !/(Android)/i.test(navigator.userAgent); //ios终端
  if (IS_IOS) {
    wx.config({
      // 配置信息, 即使不正确也能使用 wx.ready
      debug: false,
      appId: "",
      timestamp: 1,
      nonceStr: "",
      signature: "",
      jsApiList: [],
    });
    wx.ready(function () {
      document.getElementById("music1")!.load();
      document.getElementById("music1")!.play();
      state.value = true;
    });
  }
};

onMounted(() => {
  getDuration();
  clear();
  autoPlayFn()
});
</script>

<template>
  <audio
    id="music1"
    :src="props.audioUrl"
    @timeupdate="updateProgress"
    controls
    ref="audioRef"
    style="display:none"
    @canplay="getDuration"
    preload="meta"
  ></audio>
  <div class="audio-box">
    <img
      @click="stateChange(!state)"
      :src="state ? getAssetURL('pause.png') : getAssetURL('play.png')"
    />
    <div class="progress-box">
      <div class="progress-bg" id="progressBg">
        <div class="progress-active" id="progressBar">
          <div
            class="active-o"
            id="progressBtn"
            @touchmove="handleMousedown"
          ></div>
        </div>
      </div>
    </div>
    <div class="time">{{ durationRef }}</div>
  </div>
</template>

<style lang="less" scoped>
.audio-box {
  width: 100%;
  height: 100%;
  padding: 0;
  border-radius: 50px;
  background: rgba(0, 0, 0, 0.3);
  box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.6);
  border: 1px solid rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: space-between;

  .progress-box {
    width: 85%;
    height: 100%;
    display: flex;
    position: relative;
    align-items: center;
    justify-content: right;
    .progress-bg {
      width: 90%;
      height: 2px;
      background: rgba(255, 255, 255, 0.6);
      position: absolute;
    }
    .progress-active {
      width: 0;
      height: 2px;
      background: #3c7e70;
      position: relative;

      .active-o {
        width: 13px;
        height: 13px;
        border-radius: 100%;
        background: #3c7e70;
        position: absolute;
        right: 0;
        transform: translate(50%, -45%);
        z-index: 10000;
      }
    }
  }
  .time {
    width: 20%;
    height: 100%;
    font-size: 14px;
    color: rgba(255, 255, 255, 0.493);
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
