/*
 * @Descripttion: 
 * @version: 
 * @Author: guanxiaoxin
 * @Date: 2023-06-15 15:29:21
 * @LastEditors: guanxiaoxin
 * @LastEditTime: 2023-06-15 15:53:05
 * @FilePath: \fis_h5_school\src\components\courses\CourseInformationItem.jsx
 */
import React from "react";
import * as coursesAPI from "../../apis/coursesAPI";
import { message } from "antd";
import moment from "moment";

const CoursesCatalogItem = ({ course, onChildData, currentPlatform }) => {
  const { index, Name, PlayCount, CreateTime, Code, VideoToken } = course;
  const downloadFile = async (url) => {
    if (
      currentPlatform === "FPlatformEnum.webOnWin" ||
      currentPlatform === "FPlatformEnum.webOnMac"
    ) {
      const result = await coursesAPI.sendCourseEntryNotice(
        `target=download?token=${url}`
      );
      if (result.error != null && result.error.code === 1) {
        message.error("无权限，请使用杏聆荟账号下载资源");
      }
    } else if (currentPlatform === "FPlatformEnum.web") {
      const filename = url.split("/").pop();
      downloadsFile(url, (percent) => {
        console.log(percent);
      }).then((blob) => {
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        a.remove();
      });
    } else {
      message.error("请至PC端下载");
    }
  };

  function handleClick() {
    downloadFile(VideoToken);
    // 调用父组件传递的函数并传递相关数据
  }
  function downloadsFile(url, onProgress) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        } else {
          reject(Error(xhr.statusText));
        }
      };
      xhr.onerror = () => reject(Error("Network Error"));
      xhr.onprogress = (event) => {
        if (event.lengthComputable) {
          const percent = Math.round((event.loaded / event.total) * 100);
          onProgress(percent);
        }
      };
      xhr.send();
    });
  }
  return (
    <div className="px-5 flex items-center justify-between py-2 text-sm hover:bg-gray-200 hover:rounded duration-150 cursor-pointer">
      <div className="w-20">
        <div className="w-6">
          <center>{index + 1}</center>
        </div>
      </div>
      <div className="w-1/2">{Name}</div>
      {
        ['FPlatformEnum.webOnWin','FPlatformEnum.webOnMac','FPlatformEnum.web'].includes(currentPlatform) &&  <div className="w-1/4  flex flex-row">
        <button
          className="bg-white hover:bg-gray-100 text-gray-500 text-sm py-1 px-3 border rounded"
          onClick={handleClick}
        >
          下载
        </button>
      </div>
      }
    </div>
  );
};

export default CoursesCatalogItem;
