import React, {useState, useEffect, useCallback} from "react";
import { Form, Input, Icon, Button, Tabs, Radio, message } from "antd";
import { Link } from "react-router-dom";
import bg from '../img/bgPng.png';
import { getAuditList, getMediumTermExamineInfo, submitTutorEvaluation, updateTutorEvaluation, hasAuditRole } from '../api';
import './index.scss';
import '../check/index.scss'
import Nodata from "../../forge/Nodata";
import {httpUrl} from '../fetch';
const { TabPane } = Tabs;
const { TextArea } = Input;

function TutorReview(props){
  const {form, current_user, showNotification, checkTime2, history} = props;
  const {getFieldDecorator, setFieldsValue, validateFieldsAndScroll, resetFields } = form;
  const [taskId, setTaskId] = useState();
  const [taskList, setTaskList] = useState([]);
  const [wordNum, setWordNum] = useState(0);
  const [detail, setDetail] = useState(undefined);
  const [reload, setReload] = useState(undefined);
  // 导师提交过之后是否是编辑状态
  const [isEdit, setIsEdit] = useState(false);
  // 导师提交信息之后按钮置灰（确保无重复提交）
  const [disabled, setDisabled] = useState(false);

  useEffect(() => {
    if(!new Date().getTime() > new Date('2022/10/01 8:0').getTime()){
      history.push("/glcc");
    }else if (!current_user.login) {
      history.push('/login?go_page=/glcc/final/examination');
    }else{
      hasAuditRole({ userId: current_user.user_id }).then(res => {
        if (!(res && res.message == 'success' && res.data.hasRole)) {
          history.push('/glcc');
        }
      })
    }
    getAuditList({ userId: current_user.user_id, pass: 1 }).then(res => {
      if (res.message === 'success') {
        const filterStuNull = res.data.rows.filter(item=>{return item.studentName !== null})
        setTaskList(filterStuNull);
        filterStuNull.length && setTaskId(filterStuNull[0].id);
      } else {
        res && showNotification(res.message || '查询课题列表失败');
      }
    })
  }, [])

  useEffect(()=>{
    // 查询是否已经提交考核材料
    taskId && getMediumTermExamineInfo(taskId,{term: 2}).then(res=>{
      if(res && res.message === "success"){
        setDetail(res.data);
        if(res && res.data && res.data.glccTutorEvaluation){
          setWordNum(res.data.glccTutorEvaluation.comment.length);
          setFieldsValue({...res.data.glccTutorEvaluation});
        }
      }
    })
  },[taskId, reload])

  // 导师打分
  function submit(e){
    setDisabled(true);
    e.preventDefault();
    validateFieldsAndScroll((err, values) => {
      if(!err){
        const params = {
          ...values,
          mediumTermExamineMaterialId: detail.id,
          tutorUserId: detail.studentRegId,
          term: 2
        }
        if(detail.glccTutorEvaluation){
          params['id'] = detail.glccTutorEvaluation.id;
          updateTutorEvaluation(params).then(res=>{
            if(res && res.message === "success"){
              setIsEdit(false);
              message.success("修改成功");
              setReload(Math.random());
            }
          })
        }else{
          submitTutorEvaluation(params).then(res=>{
            if(res && res.message === "success"){
              message.success("您已成功评分");
              setReload(Math.random());
            }
          })
        }
      }
    })
  }

  const RadioGroup = <Radio.Group disabled={detail && detail.glccTutorEvaluation && !isEdit}>
    <Radio value={'S'}>S</Radio>
    <Radio value={'A'}>A</Radio>
    <Radio value={'B'}>B</Radio>
    <Radio value={'C'}>C</Radio>
    <Radio value={'D'}>D</Radio>
  </Radio.Group>;

  const helper = useCallback(
    (label, name, rules, widget, className) => (
      <Form.Item label={label} className={`referItem ${className}`}>
        {getFieldDecorator(name, { rules, validateFirst: true })(widget)}
      </Form.Item>
    ),[taskId, reload]
  );

  return <div className="interimBox glcc-check">
    <img src={bg} alt="" className="bg1"/>
    <img src={bg} alt="" className="bg2"/>
    <div className="mainBox">
      <div className="navBox font-16"><Link to={`/glcc`} className="linkBox">开源夏令营 / </Link>导师拟定考核结果</div>
      <div className="tipBox mt30">
        <div className="font-15 spanBox">导师考核说明:</div>
        <div>1、请各位导师从“工作态度”“开发进度”“项目完成质量”“总体评分”四个角度，根据学生提交的考核材料与实际开发情况客观地进行打分。打分标准分为：S:特别优秀、A:优秀、B:良好、C:合格、D:不合格五个等级。</div>
        <div>2、“总体评分”这一项将决定学生是否通过本次考核。若总体评分为“S、A、B、C”，则视为通过结项考核。若该结果为“D”，则该课题结项考核不通过，不予发放结项奖金。请各位导师谨慎做出评价。</div>
        <div>3、导师提交打分结果后，可对考核结果进行更改，期间考核结果也将实时反馈给学生；更改考核结果截止时间为<span className="spanBox">2022年10月20日24点</span>。</div>
        <div>4、北京时间<span className="spanBox">2022年10月24日20点</span>前GLCC官网将公布结项考核结果，敬请留意。</div>
      </div>
      <div className="tutorContent">
        <Tabs className="task-tabs" onChange={(e) => { resetFields(); setTaskId(e); setIsEdit(false); setWordNum(0); setDisabled(false);}} activeKey={taskId + ''}>
          {
            taskList.map((item, i) => {
              return <TabPane tab={`课题${i + 1}`} key={item.id} >
                <div className="task-title-stuName font-16">{item.studentName} — {item.taskName}</div>
              </TabPane>
            })
          }
        </Tabs>
        {detail ? <div className="reviewBox">
          {/* 已评分提示语句 */}
          {detail.glccTutorEvaluation && !isEdit && <div className="successReviewBox font-15">您已评分成功! 在审核期间，您可对评分结果进行更改</div>}
          {/* 学生提交的资料 */}
          <div className="stuCont pl20 pr20">
            <div className="title font-16 mb15"><span className="blueBox"></span>基本信息</div>
            <div className="flexBox">
              <div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;答辩视频:<span className="blueSpan ml10"><a className="blueSpan" href={detail.defenceVideoUrl} target="_blank">{detail.defenceVideoUrl}</a></span></div>
              <div>代码/pr地址:<span className="blueSpan ml10"><a className="blueSpan" href={detail.codeOrPrUrl} target="_blank">{detail.codeOrPrUrl}</a></span></div>
              <div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PPT附件:<i className="iconfont icon-lianjie3 font-13 mr5 ml10"></i><a className="mr10 pptAttachment" href={`${httpUrl}/busiAttachments/download/${detail.pptAttachment.id}`}>{detail.pptAttachment.fileName}</a>{detail.pptAttachment.fileSizeString}</div>
            </div>
          </div>
          <div className="title font-16 pl20 mt25"><span className="blueBox"></span>导师评分</div>
          {/* 导师打分 */}
          <Form className="referBox tutor" onSubmit={submit} labelAlign="left" labelCol={{ span: 5 }} colon={false}>
            {helper('工作态度',
              'workAttitudeEvaluation',
              [{ required: true, message: "请打分" }],
              RadioGroup
            )}
            {helper('工作进度',
              'developProgressEvaluation',
              [{ required: true, message: "请打分" }],
              RadioGroup
            )}
            {helper('项目完成质量',
              'projectQualityEvaluation',
              [{ required: true, message: "请打分" }],
              RadioGroup
            )}
            {helper('总体评分',
              'totalityEvaluation',
              [{ required: true, message: "请打分" }],
              RadioGroup
            )}
            <div className="remarkBox">
              {helper('填写评语',
                'comment',
                [{ required: true, message: "请输入评语!" }],
                <TextArea placeholder="请对学生项目表现进行总体评价" className="contentBox" maxLength={2000} onChange={(e)=>{setWordNum(e.target.value.length);}} disabled={detail.glccTutorEvaluation && !isEdit} autoSize={{minRows: 8}}/>,
                'oneCont'
              )}
              <div className="wordNum">{wordNum} / 2000</div>
            </div>
            {checkTime2 && <Form.Item className="referItem oneCont">
              {(!detail.glccTutorEvaluation || (detail.glccTutorEvaluation && isEdit)) && <Button style={{width: '100px', height: '36px'}} className="mt20" type="primary" htmlType="submit" disabled={disabled}>{detail.glccTutorEvaluation ? '保存' : '提交'}</Button>}
              {detail.glccTutorEvaluation && !isEdit && <Button style={{width: '100px', height: '36px'}} className="mt20" type="primary" onClick={()=>{setIsEdit(true);setDisabled(false);}}>修改</Button>}
            </Form.Item>}
          </Form>
        </div>:<Nodata _html="该课题学生暂未提交结项考核材料，请提醒学生尽快提交"/>}
      </div>
    </div>
  </div>
}
export default Form.create()(TutorReview);