import React from "react";
import { observer } from "mobx-react";
import styles from "./VideoPanel.module.less";
import { Button } from "@grace/ui";
import { _asyncThrottle } from "@/utils/utils.ts";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
import classNames from "classnames";
import API from "@/api";
import ObtainPanel from "@/panels/ObtainPanel/ObtainPanel.tsx";
import store from "@/store/store.ts";

export interface IVideoPanelProps {
  url: string;
  taskId: string;
  isExp: string;
}

@observer
class VideoPanel extends React.Component<IVideoPanelProps> {

  state = {
    cd: 15,
  }

  video: HTMLVideoElement;

  completeData = null;

  componentDidMount() {
    this.video.onpause = this.onPause;
    this.video.play();
    this.startCd();
  }

  intervalId: number = 0;
  startCd = () => {
    this.intervalId = window.setInterval(() => {
      const cd = this.state.cd - 1;
      this.setState({ cd });

      if (cd <= 0) {
        clearInterval(this.intervalId);
        this.finishVideoTask();
        return;
      }
    }, 1000);
  }

  finishVideoTask = _asyncThrottle(async () => {
    const { taskId } = this.props;
    const { success, data } = await API.startVideo({ taskId });
     store.updateIndex();
    if (!success) return;
    this.completeData = data;
  });


  onPause = () => {
  }

  clickClose = () => {
    ModalCtrl.closeModal();

    if (this.completeData?.creditNum) {
      ModalCtrl.showModal(ObtainPanel, {
        creditNum: this.completeData.creditNum,
        isExp: this.props.isExp,
      });
    }

  };

  render() {
    const { url, isExp } = this.props;
    const { cd } = this.state;

    return <div className={classNames(styles.VideoPanel, "modal_center", isExp ? "md10_0" : "md10_1")}>
      <video
        ref={(el) => this.video = el}
        id="my-player"
        className={styles.video}
        preload="auto"
        controls={true}
        poster={`${url}?x-oss-process=video/snapshot,t_1000,f_jpg,w_648,h_1148,m_fast`}
      >
        <source src={url} type="video/mp4"/>
        <p className="vjs-no-js">
          To view this video please enable JavaScript, and consider upgrading to a
          web browser that
          <a href="https://videojs.com/html5-video-support/" target="_blank">
            supports HTML5 video
          </a>
        </p>
      </video>

      <div className={styles.cd}>{cd ? `${cd}s` : "已完成"}</div>
      <div className={styles.progressBar}>
        <div className={styles.progressFill} style={{
          width: `${100 - cd / 15 * 100}%`,
        }}/>
      </div>

      <div className="com_banner"/>

      <Button className={styles.close} onClick={this.clickClose}/>
    </div>;
  }
}

export default VideoPanel;
