import React, { useState, useEffect } from 'react';
import moment from 'moment';
import { useSessionStorage } from 'react-use';
import { useNavigate } from 'react-router-dom';
import FPlatformEnum from '../../utils/enum';
import * as coursesAPI from '../../apis/coursesAPI';

const CoursesCatalogItem = ({ course }) => {
  const navigate = useNavigate();

  const { index, Name, PlayCount, CreateTime, Code } = course;
  const [platform] = useSessionStorage('platform', FPlatformEnum.web.index);

  const [isShowBuy, setIsShowBuy] = useState(false);
  const [isShowPlay, setIsShowPlay] = useState(false);

  function getCourseCreatedTime() {
    const dateObj = moment(CreateTime).local();
    const formattedTime = dateObj.format('YYYY-MM-DD HH:mm');
    return <div>{formattedTime}</div>;
  }
  function onClickPlay() {
    let token = '';
    if (sessionStorage.getItem('token')) {
      token = `/${JSON.parse(sessionStorage.getItem('token'))}`;
    }
    const url = '/video_course_player/' + Code + `/${platform}` + token;
    navigate(url);
  }

  // 来判断是否显示按钮
  useEffect(() => {
    if (course) {
      if (
        course.NeedPay && // 需要购买
        !course.isPay // 未购买
      ) {
        setIsShowBuy(true);
        setIsShowPlay(false);
      } else {
        setIsShowBuy(false);
        setIsShowPlay(true);
      }
    }
  }, [course]);
  const buyCourse = async (code, type) => {
    const buyInfo = await coursesAPI.buyCourse(code, type);

    const { PayUrl } = buyInfo;
    window.open(PayUrl, '_blank');
    // 设置支付二维码内容和显示支付二维码的状态
    // setQRCodeValue(PayUrl); // TODO: 替换为合适的支付二维码内容
    // setIsShowingQRCode(true);
  };

  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>
      <div className='w-1/4 hidden md:block'>{PlayCount}</div>
      <div className='w-1/4 hidden md:block'>{getCourseCreatedTime()}</div>
      <div className='w-1/4  flex flex-row'>
        {isShowPlay && (
          <button
            className='bg-white hover:bg-gray-100 text-gray-500 text-sm py-1 px-3 border rounded'
            onClick={onClickPlay}>
            播放
          </button>
        )}
        {isShowBuy && (
          <button
            className='bg-white hover:bg-gray-100 text-gray-500 text-sm py-1 px-3 border rounded'
            onClick={() => {
              buyCourse(
                course.Code,
                FPlatformEnum.byIndex(platform).isMobile() ? 1 : 0,
              );
            }}>
            购买
          </button>
        )}
      </div>
    </div>
  );
};

export default CoursesCatalogItem;
