import React from 'react';
import * as coursesAPI from '../../apis/coursesAPI';
import { message } from 'antd';
import FPlatformEnum from '../../utils/enum';

const CoursesCatalogItem = ({ course, onChildData, platform }) => {
  const { index, Name, VideoToken } = course;
  const downloadFile = async (url) => {
    if (FPlatformEnum.byIndex(platform).isShell()) {
      const result = await coursesAPI.sendCourseEntryNotice(
        `target=download?token=${url}&filename=${Name}`,
      );
      if (result.error != null && result.error.code === 1) {
        message.error('无权限，请使用杏聆荟账号下载资源');
      }
    } else if (FPlatformEnum.byIndex(platform).isPureWeb()) {
      // const filename = url.split('/').pop();
      downloadsFile(url, (percent) => {
        console.log('%c Line:19 🎂 下载进度', 'color:#ed9ec7', percent);
      }).then((blob) => {
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = Name;
        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.byIndex(platform).isWeb && (
        <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;
