/*
 * @Author: sunbingqing
 * @Date: 2019-07-26 14:04:00
 * @Last Modified by: 吴文洁
 * @Last Modified time: 2020-04-18 10:54:32
 */

import React, { useState, useEffect, useRef } from "react";
import "./XMAudio.less";
import VideoUpload from "@/core/upload";
import { string } from "prop-types";

// interface XMAudioProps {
//   style?: any;
//   index?: any;
//   size?: number | string;
//   url?: any;
//   forbidParse?:boolean;
//   getDuration?: (value: number) => void;
// }

let timerInterval;

const XMAudio = (props) => {
  const ref = useRef();
  const { style, size,  getDuration } = props;
  const [url, setUrl] = useState(props.url);
  const [playing, setPlaying] = useState(false);
  const [timer, setTimer] = useState(null);
  const [playedTime, setPlayedTime] = useState(0);
  const [leftTime, setLeftTime] = useState(Math.round(Number(size)));
  const [totalTime, setTotalTime] = useState(Math.round(Number(size)));
  const prevTimeRef = useRef();
  useEffect(() => {
    if(!props.forbidParse){
      VideoUpload.getVideoParseRoute(props.url).then((newUrl) => {
        setUrl(newUrl);
      });
    }
    setLeftTime(Math.round(Number(size)));
    setTotalTime(Math.round(Number(size)));

    ref.current.addEventListener("pause", () => {
      clearInterval(timer);
      setPlaying(false);
      setTimer(null);
      if (ref.current && ref.current.ended) {
        setLeftTime(totalTime);
        setPlayedTime(0);
      }
    });
  }, [props.url]);

  useEffect(() => {

    if (playing) {
      timerInterval = setInterval(() => {
        setPlayedTime((preTime) => {
          prevTimeRef.current = preTime;
          return prevTimeRef.current + 20;
        });

        if ((prevTimeRef.current + 20) % 1000 === 0) {
          setLeftTime(totalTime - (prevTimeRef.current + 20));
        }
        if ((prevTimeRef.current + 30) >= totalTime) {
          clearInterval(timerInterval);
          setPlayedTime(0);
          setLeftTime(totalTime);
          setPlaying(false);
        }
      }, 20);
      const audioDomList = document.querySelectorAll("audio");
      for (let i = 0; i < Array.from(audioDomList).length; i++) {
        if (audioDomList[i] === ref.current) {
          ref.current.play();
          setTimer(timerInterval)
        } else {
          audioDomList[i].pause();
        }
      }
    } else {
      ref.current.pause();
      clearInterval(timer);
    }
  }, [playing]);

  const audioImg = `https://xiaomai-image.oss-cn-hangzhou.aliyuncs.com/${
    playing ? 1584514990496 : 1584514999661
    }.png`;

  function _togglePlay() {
    playing ? pausePlay() : startPlay();
  }

  function pausePlay() {
    setPlaying(false);
  }

  function startPlay() {
    setPlaying(true);
  }

  function _changeTimeShow() {
    let time = Math.floor(leftTime / 1000);
    if (leftTime / 1000 > 60) {
      const s = leftTime / 1000;
      const second = Math.ceil(s % 60);
      const minute = Math.floor(s / 60);
      time = `${minute}'${second}`;
    }
    return time;
  }

  function _getDuration() {
    const videoDiv = ref.current;
    const videoSize = Math.round(videoDiv.duration) * 1000;
    if (getDuration) {
      setTotalTime(videoSize);
      setLeftTime(videoSize);
      getDuration(videoSize);
    }
  }



  function _startTime() {
    let time = Math.floor(playedTime / 1000);
    let second = 0
    let minute = 0;
    let result = 0
    if (time > 0) {
      minute = Math.floor(time % 3600 / 60);
      second = Math.floor((time - 60 * minute) % 60);

      if (minute < 10) {
        minute = "0" + minute;
      }
      if (second < 10) {
        second = "0" + second;
      }
      result = minute + ':' + second
    }else{
      result = "00:00"
    }
    return result;
  }

  function _endTime() {
    let time = Math.floor(totalTime / 1000);
    let second = 0
    let minute = 0;
    let result = 0
    if (time > 0) {
      minute = Math.floor(time % 3600 / 60);
      second = Math.floor((time - 60 * minute) % 60);

      if (minute < 10) {
        minute = "0" + minute;
      }
      if (second < 10) {
        second = "0" + second;
      }
      result = minute + ':' + second
    }
   
    if(time === 0){
      result = "00:00"
    }
    return result;
  }


  function putDownFlag(event) {
    let dragDiv = event.target;
    dragDiv.style.cursor = "pointer";
    let offsetX = parseInt(dragDiv.style.left); // 获取当前的x轴距离
    let innerX = event.clientX - offsetX; // 获取鼠标在方块内的x轴距
    // 按住鼠标时为div修改样式
    dragDiv.style.width = "16px";
    dragDiv.style.height = "16px";
    dragDiv.style.top = "-7px";
    dragDiv.style.backGround = "linear-gradient(180deg, #FFB467 0%, #FF9143 100%)"
    // 鼠标移动的时候不停的修改div的left和top值
    document.onmousemove = function (event) {
      dragDiv.style.left = event.clientX - innerX + "px";
      // 边界判断
      if (parseInt(dragDiv.style.left) <= 0) {
        dragDiv.style.left = "0px";
      }
      if (parseInt(dragDiv.style.left) >= 181) {
        dragDiv.style.left = "176px";
      }

      setPlayedTime(parseInt(dragDiv.style.left) / 180 * totalTime)
    }
    // 鼠标抬起时，清除绑定在文档上的mousemove和mouseup事件
    // 否则鼠标抬起后还可以继续拖拽方块
    document.onmouseup = function () {
      document.onmousemove = null;
      document.onmouseup = null;
      // 清除border

      dragDiv.style.top = "-4px";
      dragDiv.style.width = "10px";
      dragDiv.style.height = "10px";
    }
  }
  function mouseOver(event){
    let dragDiv = event.target;
    dragDiv.style.cursor = "pointer";
    dragDiv.style.width = "16px";
    dragDiv.style.height = "16px";
    dragDiv.style.top = "-7px";
    dragDiv.style.backGround = "linear-gradient(180deg, #FFB467 0%, #FF9143 100%)"
  }
  function mouseLeave (event){
    let dragDiv = event.target;
    dragDiv.style.top = "-4px";
      dragDiv.style.width = "10px";
      dragDiv.style.height = "10px";
  }
  return (
    <div className="xm-audio" style={style}>
      <img src={audioImg} onClick={_togglePlay} className="audio-image" />
      <div className="process-area">
        <div
          className="complete-area"
          style={{ width: `${(playedTime / totalTime) * 150}px ` }}
        />
        <div
          className="flag"
          style={{ left: `${(playedTime / totalTime) * 150}px ` }}
          onMouseDown={(e) => putDownFlag(e)}
          onMouseOver={(e)=> mouseOver(e)}
          onMouseLeave={(e)=>mouseLeave(e)}
        />
      </div>
      <span className="sec-time">
            {`${_startTime()}`}/{`${_endTime()}`}
          </span>
      <audio
        src={url}
        ref={ref}
        autoPlay={false}
        onCanPlayThrough={_getDuration}
      />
    </div>
  );
};

export default XMAudio;
