import React, {useState, useEffect} from "react";

import { Route, Switch } from "react-router-dom";
import { withRouter } from "react-router";

import { SnackbarHOC } from "educoder";
import { CNotificationHOC } from "../modules/courses/common/CNotificationHOC";
import { TPMIndexHOC } from "../modules/tpm/TPMIndexHOC";
import "./index.scss";

import Loadable from "react-loadable";
import Loading from "../Loading";
import { ImageLayerOfCommentHOC } from "../modules/page/layers/ImageLayerOfCommentHOC";
import { getStudentApplyInfo } from "./api";
import { message } from "antd";


// 任务管理审核
const Home = Loadable({
  loader: () => import("./home"),
  loading: Loading,
});
// 开源夏令营报名页面
const Apply = Loadable({
  loader: () => import("./apply"),
  loading: Loading,
});
// 开源夏令营帮助中心页面
const Help = Loadable({
  loader: () => import("./help"),
  loading: Loading,
});
// 学生报名课题
const Student = Loadable({
  loader: () => import("./student"),
  loading: Loading,
});
// 教师审核学生
const Check = Loadable({
  loader: () => import("./check"),
  loading: Loading,
});

// 开源夏令营项目、课题列表页面
const Project = Loadable({
  loader: () => import("./project"),
  loading: Loading,
});
// 课题详情页面
const TaskDetail = Loadable({
  loader: () => import("./project/taskDetail"),
  loading: Loading,
});
// 开源夏令营项目、课题列表页面
const Openmmlab = Loadable({
  loader: () => import("./openmmlab"),
  loading: Loading,
});
// 开源夏令营审核结果页面
const Result = Loadable({
  loader: () => import("./checkResult"),
  loading: Loading,
});
const Glcc = (propsF) => {
  const {current_user, showLoginDialog} = propsF;
  // 判断时间是否在开源夏令营报名时间内（4月15日~5月20日）
  const isGlccApplyDate = Date.parse(new Date()) < 1653062400000;

  // 学生报名时间
  const studentApplyStart = new Date().getTime() > new Date('2022-05-26').getTime();
  const isStudentApplyDate = new Date().getTime() > new Date('2022-05-26').getTime() && new Date().getTime() < new Date('2022-06-25 0:0').getTime();
  const secondStudentApplyDate = new Date().getTime() > new Date('2022-06-29 1:0').getTime() && new Date().getTime() < new Date('2022-06-30 0:0').getTime();

  // 用户已报名课题id数组
  const [applyTaskId, setApplyTaskId] = useState({});
  // 刷新用户课题报名信息
  const [studentInfoReset, setStudentInfoReset] = useState(undefined);
  const [cancelCount,setCancelCount]=useState(0);
  // 用户是否已经被导师选中
  const [lockedTaskName, setLockedTaskName] = useState(undefined);

  useEffect(()=>{
    // 获取用户课题报名信息current_user user_id
    current_user && current_user.login && getStudentApplyInfo({userId: current_user.user_id}).then(response=>{
      if(response && response.message === "success"){
        // setData(response.data.rows);
        const data = {};
        response.data && response.data.registrationStudentTaskList.map(item=>{
          data[item.taskId] = item.id;
          item.locked && setLockedTaskName(item.taskName);
        })
        setApplyTaskId(data);
        response.data&&setCancelCount(Number(response.data.cancelCount));
      }
    })
  },[studentInfoReset, current_user])

  // 申请课题按钮点击函数
  function applyTask(id){
    // 判断用户是否已经登录
    if(current_user && current_user.login){
      // 判断该学生是否已经被某位导师选中
      if(lockedTaskName){
        message.error(`由于你已入选 ${lockedTaskName} 课题，无法申请其他课题`);
      }else if(applyTaskId && Object.keys(applyTaskId).length >= 3){
        // 判断用户是否已经报名三个课题
        message.error('最多只能同时报名三个课题');
      }else{
        // 跳转到学生报名页
        window.location.href=`/glcc/student/apply/${id}`;
      }
    }else{
      showLoginDialog();
    }
  }

  return (
    <div className="newMain clearfix">
      <Switch {...propsF}>
        {/* 学生报名 */}
        <Route
          path="/glcc/student/apply/:taskId"
          render={(props) => (
            <Student {...propsF} {...props} isGlccApplyDate={isGlccApplyDate} setStudentInfoReset={setStudentInfoReset}/>
          )}
        ></Route>
        {/* 开源夏令营报名页面 */}
        <Route
          path="/glcc/apply"
          render={(props) => (
            <Apply {...propsF} {...props} isGlccApplyDate={isGlccApplyDate}/>
          )}
        ></Route>
        {/* 教师审核 */}
        <Route
          path="/glcc/mentoradmin"
          render={(props) => (
            <Check {...propsF} {...props} isGlccApplyDate={isGlccApplyDate}/>
          )}
        ></Route>
        {/* 帮助中心 */}
        <Route
          path="/glcc/help"
          render={(props) => (
            <Help {...propsF} {...props} />
          )}
        ></Route>
        <Route
            path="/glcc/subjects/detail/:taskId"
            render={(props) => (
              <TaskDetail {...propsF} {...props} isStudentApplyDate={isStudentApplyDate} secondStudentApplyDate={secondStudentApplyDate} applyTaskId={applyTaskId} applyTask={applyTask} />
            )}
          ></Route>
        {/* 项目/课题列表 */}
        <Route
          path="/glcc/projects"
          render={(props) => (
            <Project {...propsF} {...props} isStudentApplyDate={isStudentApplyDate} secondStudentApplyDate={secondStudentApplyDate} applyTaskId={applyTaskId} setStudentInfoReset={setStudentInfoReset} applyTask={applyTask}/>
          )}
        ></Route>

        {/* 课题列表 */}
        <Route
          path="/glcc/subjects"
          render={(props) => (
            <Project {...propsF} {...props} isStudentApplyDate={isStudentApplyDate} secondStudentApplyDate={secondStudentApplyDate} applyTaskId={applyTaskId} setStudentInfoReset={setStudentInfoReset} cancelCount={cancelCount} applyTask={applyTask}/>
          )}
        ></Route>

        {/* openmmlab列表 */}
        <Route
          path="/glcc/openmmlab"
          render={(props) => (
            <Openmmlab {...propsF} {...props} isStudentApplyDate={isStudentApplyDate} secondStudentApplyDate={secondStudentApplyDate} applyTaskId={applyTaskId} setStudentInfoReset={setStudentInfoReset} applyTask={applyTask}/>
          )}
        ></Route>

        {/* 审核结果页面 */}
        <Route
          path="/glcc/result"
          render={(props) => (
            <Result current_user={current_user} history={props.history}/>
          )}
        ></Route>

        {/* 首页 */}
        <Route
          path="/glcc"
          render={(props) => (
            <Home {...propsF} {...props} studentApplyStart={studentApplyStart} isStudentApplyDate={isStudentApplyDate} secondStudentApplyDate={secondStudentApplyDate}/>
          )}
        ></Route>

      </Switch>
    </div>
  );
}

export default withRouter(
  ImageLayerOfCommentHOC({
    imgSelector: ".imageLayerParent img, .imageLayerParent .imageTarget",
    parentSelector: ".newMain",
  })(CNotificationHOC()(SnackbarHOC()(TPMIndexHOC(Glcc))))
);
