import React, { useState, useRef, useEffect, useContext } from 'react';
import Breadcrumbs from '@/components/Breadcrumbs';
import { Form, Alert, Input, Button, InputNumber, DatePicker, Switch, Radio, message, Modal, Tooltip } from 'antd';
import { Route, withRouter } from 'react-router-dom';
import User from '@/common/js/user';
import moment from 'moment';
import Service from '@/common/js/service';
import _ from 'underscore';
import GraphicsEditor from '../../course-manage/components/GraphicsEditor';
import SelectPaperModal from './SelectPaperModal';
import PreviewModal from './PreviewModal';
import ShowTips from '@/components/ShowTips';

import './AddExam.less';

const { RangePicker } = DatePicker;

function AddExam(props: any) {
  const paperInfoInit: any = { passScore: 60 };
  const [showModal, setShowModal] = useState(false);
  const [paperInfo, setPaperInfo] = useState(paperInfoInit);
  const [paperId, setPaperId] = useState('');
  const [passRate, setPassRate] = useState(60); //及格线
  const [examStartTime, setStartTime] = useState('');
  const [examEndTime, setExamEndTime] = useState('');
  const [examName, setExamName] = useState('');
  const [needPhone, setNeedPhone] = useState('DO_NOT_NEED_PHONE_VERIFY');
  const [needOptionDisorder, setNeedOptionDisorder] = useState('OPTION_SORT');
  const [resultContent, setResultContent] = useState('PASS_AND_SCORE');
  const [answerAnalysis, setAnswerAnalysis] = useState('RIGHT_OR_WRONG');
  const [resultShow, setResultShow] = useState('IMMEDIATELY');
  const [examDesc, setExamDesc] = useState('');
  const [passScore, setPassScore] = useState(100);
  const [desclen, setDescLen] = useState(0);
  const [check, setCheck] = useState(false);
  const [getData, setGetData] = useState(false);
  const [preview, setPreview] = useState(false);
  const [examTotal, setExamTotal] = useState(0);
  const request = useRef(false);
  const { match } = props;

  const [examDuration, setExamDuration] = useState(undefined);

  useEffect(() => {
    switch (props.type) {
      case 'copy': // 考试列表-复制考试进入
      case 'edit': // 考试列表-编辑考试进入
        queryExamDetail();
        break;
      case 'organizeExam': // 试卷列表-组织考试进入
      case 'newPaperToAddExam': // 组卷页面-新建保存试卷并组织考试
      case 'editPaperToAddExam': // 组卷页面-编辑保存试卷并组织考试
        setGetData(true);
        setPaperInfo(props.paperInfo);
        break;
    }
  }, []);

  useEffect(() => {
    setPaperId(paperInfo.paperId);
    setPassRate(paperInfo.passRate);
  }, [paperInfo.paperId]);

  useEffect(() => {
    setPassScore(Math.round((((paperInfo.totalScore || 0) * (passRate || 0)) as any) / 100));
    setExamTotal(paperInfo.singleChoiceCnt + paperInfo.multiChoiceCnt + paperInfo.judgeCnt + paperInfo.gapFillingCnt + paperInfo.indefiniteChoiceCnt || 0);
  }, [paperInfo.paperId, passRate]);

  function disabledDate(current: any) {
    // Can not select days before today and today
    return current && current < moment().startOf('day');
  }

  function queryExamDetail() {
    Service.Hades('public/hades/queryExamDetail', {
      examId: match.params.id,
      tenantId: User.getStoreId(),
      userId: User.getStoreUserId(),
      source: 0,
    }).then((res) => {
      const { result } = res;
      setPaperInfo(result.examPaper);
      setPaperId(result.examPaper.paperId);
      setStartTime(props.type === 'edit' ? result.examStartTime : '');
      setExamEndTime(props.type === 'edit' ? result.examEndTime : '');
      setExamName(props.type === 'edit' ? result.examName : `${result.examName}（复制）`);
      setPassRate(result.passRate * 100);
      setNeedPhone(result.needPhone);
      setExamDesc(result.examDesc);
      setExamDuration((result.examDuration / 60 / 1000) as any);
      setAnswerAnalysis(result.answerAnalysis);
      setNeedOptionDisorder(result.needOptionDisorder);
      setPassScore(result.passScore);
      setResultContent(result.resultContent);
      setResultShow(result.resultShow);
      setGetData(true);
    });
  }

  function handleSave() {
    if (request.current) {
      return;
    }

    setCheck(true);
    const param = {
      paperId,
      startTime: examStartTime,
      endTime: examEndTime,
      examName,
      passRate: passRate / 100,
      examStartTime,
      examEndTime,
      examDesc,
      needPhone,
      needOptionDisorder,
      resultContent,
      answerAnalysis,
      resultShow,
      examDuration: (examDuration || 0) * 60 * 1000,
      passScore,
      tenantId: User.getStoreId(),
      userId: User.getStoreUserId(),
      source: 0,
      examId: '',
    };

    if (!param.examName) {
      message.warning('请输入考试名称');
      return;
    }

    if (param.examName && param.examName.length > 40) {
      message.warning('考试名称最多40字');
      return;
    }

    if (!paperId) {
      message.warning('请选择试卷');
      return;
    }

    if (!passRate) {
      message.warning('请输入及格线');
      return;
    }

    if (!examStartTime || !examEndTime) {
      message.warning('请选择考试起止时间');
      return;
    }

    if (Number(examStartTime) < moment().valueOf()) {
      message.warning('开始时间不能早于现在');
      return;
    }

    if (!examDuration) {
      message.warning('请输入考试时长');
      return;
    }

    if (examStartTime + (examDuration as any) * 60 * 1000 > examEndTime) {
      message.warning('考试时长不得超过考试有效期时长');
      return;
    }

    if (desclen > 1000) {
      message.warning('内容过长，不能超过1000字');
      return;
    }

    request.current = true;
    setTimeout(() => {
      request.current = false;
    }, 2000);

    if (props.type === 'edit') {
      param.examId = match.params.id;
    }

    Service.Hades(props.type === 'edit' ? 'public/hades/editExam' : 'public/hades/createExam', param).then((res) => {
      message.success(props.type === 'edit' ? '编辑成功' : '创建成功');
      switch (props.type) {
        case 'organizeExam': // 试卷列表-组织考试进入
        case 'newPaperToAddExam': // 组卷保存组织考试
        case 'editPaperToAddExam':
          window.RCHistory.push('/examination-manage-index');
          break;
        case 'add':
        case 'edit': // 考试列表-新建或编辑
        case 'copy': // 考试列表-新建或编辑
          props.freshList();
          props.history.goBack();
          break;
      }
    });
  }

  function disabledRangeTime(date: any, type: any) {
    if (moment(date).isSame(moment(), 'day')) {
      return {
        disabledHours: () => {
          const hours = [];
          for (let i = 0; i < moment().hour(); i++) {
            hours.push(i);
          }
          return hours;
        },
        disabledMinutes: () => {
          const currentMinute = moment().minute();
          const currentHour = moment(date).hour();
          const minutes = [];
          if (currentHour === moment().hour()) {
            for (let i = 0; i < currentMinute; i++) {
              minutes.push(i);
            }
          }
          return minutes;
        },
      };
    }
    return {
      disabledHours: () => [],
      disabledMinutes: () => [],
      disabledSeconds: () => [],
    };
  }

  function handleGoBack() {
    Modal.confirm({
      title: '确定要返回吗？',
      content: '返回后，本次编辑的内容将不被保存',
      okText: '确认返回',
      cancelText: '留在本页',
      icon: <span className='icon iconfont default-confirm-icon'>&#xe6f4;</span>,
      onOk: () => {
        window.RCHistory.push('/examination-manage-index');
      },
    });
  }

  let title = '';
  switch (props.type) {
    case 'add':
    case 'organizeExam':
    case 'newPaperToAddExam':
    case 'editPaperToAddExam':
      title = '新建考试';
      break;
    case 'edit':
      title = '编辑考试';
      break;
    case 'copy':
      title = '复制考试';
      break;
    default:
      break;
  }
  return (
    <div className='page examPage'>
      <Breadcrumbs navList={title} goBack={handleGoBack} />

      <div className='box'>
        <div className='show-tips'>
          <ShowTips message='请遵守国家相关规定，切勿上传低俗色情、暴力恐怖、谣言诈骗、侵权盗版等相关内容，小麦企学院保有依据国家规定及平台规则进行处理的权利' />
        </div>{' '}
        <div className='form'>
          <div className='title'>基本信息</div>
          <Form labelCol={{ span: 3 }} wrapperCol={{ span: 14 }} layout='horizontal'>
            <Form.Item
              label='考试名称'
              validateStatus={check && (!examName ? '请输入考试名称' : examName.length > 40 && '考试名称最多40字') ? 'error' : ''}
              help={check && (!examName ? '请输入考试名称' : examName.length > 40 && '考试名称最多40字')}
              required>
              <Input
                placeholder='请输入考试名称（40字以内）'
                maxLength={40}
                value={examName}
                onChange={(e) => {
                  setExamName(e.target.value);
                }}
                style={{ width: 320 }}
              />
            </Form.Item>

            <Form.Item label='选择试卷' validateStatus={check && !paperId ? 'error' : ''} help={check && !paperId && '请选择试卷'} required>
              <Button
                onClick={() => {
                  setShowModal(true);
                }}>
                {paperInfo.paperId ? '重新选择' : '选择试卷'}
              </Button>

              {paperInfo.paperId && (
                <div className='paperTitle'>
                  <img src='https://image.xiaomaiketang.com/xm/pY5imEhjzw.png' alt='' /> {paperInfo.paperName}
                </div>
              )}

              {paperInfo.paperId && (
                <div className='table'>
                  <div className='header'>
                    <div className='item'>单选题</div>
                    <div className='item'>多选题</div>
                    <div className='item'>判断题</div>
                    <div className='item'>填空题</div>
                    <div className='item long'>不定项选择题</div>
                    <div className='item'>合计</div>
                  </div>
                  <div className='body-list'>
                    <div className='item'>{paperInfo.singleChoiceCnt || 0}题</div>
                    <div className='item'>{paperInfo.multiChoiceCnt || 0}题</div>
                    <div className='item'>{paperInfo.judgeCnt || 0}题</div>
                    <div className='item'>{paperInfo.gapFillingCnt || 0}题</div>
                    <div className='item long'>{paperInfo.indefiniteChoiceCnt || 0}题</div>
                    <div className='item'>{examTotal}题</div>
                  </div>
                  <div className='body-list'>
                    <div className='item'>{paperInfo.singleChoiceScore || 0}分</div>
                    <div className='item'>{paperInfo.multiChoiceScore || 0}分</div>
                    <div className='item'>{paperInfo.judgeScore || 0}分</div>
                    <div className='item'>{paperInfo.gapFillingScore || 0}分</div>
                    <div className='item long'>{paperInfo.indefiniteChoiceScore || 0}分</div>
                    <div className='item'>{paperInfo.totalScore || 0}分</div>
                  </div>
                </div>
              )}
            </Form.Item>

            <Form.Item
              label={
                <div>
                  <span>及格线</span>
                  <Tooltip title='默认为选中试卷所设置的及格线，可修改'>
                    <span className='icon iconfont' style={{ color: '#BFBFBF', marginLeft: 4 }}>
                      &#xe61d;
                    </span>
                  </Tooltip>
                </div>
              }
              style={{ marginTop: 24 }}
              validateStatus={check && !passRate ? 'error' : ''}
              help={check && !passRate && '请输入及格线'}
              required>
              <InputNumber
                value={passRate}
                min={0}
                max={100}
                onChange={(value: any) => {
                  setPassRate(parseInt(value));
                }}
                style={{ width: 100 }}
              />
              <span style={{ marginLeft: 4 }}>%</span>
              <span style={{ marginLeft: 16, color: '#999' }}>
                {`  总分(${paperInfo.totalScore || 0})*及格线（${passRate || 0}%）=及格分数（${passScore}）`}
              </span>
            </Form.Item>

            <Form.Item
              label='考试有效期'
              validateStatus={check && !examStartTime ? 'error' : ''}
              help={check && !examStartTime && '请选择考试起止时间'}
              required>
              <RangePicker
                style={{ width: 320 }}
                showTime={{ defaultValue: [moment().add(5, 'minutes'), moment().add(5, 'minutes')] }}
                ranges={{
                  近七天: [moment().add(5, 'minute'), moment().add(6, 'day').endOf('day')],
                  近1个月: [moment().add(5, 'minute'), moment().add(1, 'month').endOf('day')],
                  近3个月: [moment().add(5, 'minute'), moment().add(3, 'month').endOf('day')],
                }}
                disabledDate={disabledDate}
                value={[examStartTime ? moment(Number(examStartTime)) : null, examEndTime ? moment(Number(examEndTime)) : null]}
                disabledTime={disabledRangeTime}
                format='YYYY/MM/DD HH:mm'
                onChange={(date: any) => {
                  setStartTime(date && date[0]?.valueOf());
                  setExamEndTime(date && date[1]?.valueOf());
                }}
              />
            </Form.Item>
            <Form.Item label='考试时长' validateStatus={check && !examDuration ? 'error' : ''} help={check && !examDuration && '请输入考试时长'} required>
              <InputNumber
                value={examDuration}
                max={1440}
                min={1}
                onChange={(value: any) => {
                  setExamDuration(parseInt(value) as any);
                }}
                style={{ width: 100 }}
              />
              <span style={{ marginLeft: 4 }}>分钟</span>
              <span style={{ marginLeft: 16, color: '#999' }}>{` 时长不能超过1440分钟（24小时）`}</span>
            </Form.Item>

            <Form.Item label='考试说明' validateStatus={check && desclen > 1000 ? 'error' : ''} help={check && desclen > 1000 && '最多只能输入1000个字'}>
              {(getData || props.type === 'add') && (
                <GraphicsEditor
                  maxLimit={1000}
                  isIntro={true}
                  detail={{
                    content: examDesc,
                  }}
                  onChange={(val: any, len: any) => {
                    setExamDesc(val);
                    setDescLen(len);
                  }}
                />
              )}
            </Form.Item>
            <div className='title' style={{ marginTop: 40 }}>
              考试设置
            </div>
            <Form.Item label='身份验证' required>
              <div style={{ display: 'flex', marginLeft: 4 }}>
                <Switch
                  checked={needPhone == 'NEED_PHONE_VERIFY'}
                  onChange={(val) => {
                    setNeedPhone(val ? 'NEED_PHONE_VERIFY' : 'DO_NOT_NEED_PHONE_VERIFY');
                  }}></Switch>
                <div style={{ position: 'relative', left: 8, color: '#999' }}>
                  {needPhone == 'NEED_PHONE_VERIFY' ? '已开启，学员需绑定手机号才可参与考试' : '已关闭，学员无需绑定手机号即可参与考试'}
                </div>
              </div>
            </Form.Item>

            <Form.Item label='选项乱序' required>
              <div style={{ display: 'flex', marginLeft: 4 }}>
                <Switch
                  checked={needOptionDisorder == 'OPTION_RANDOM'}
                  onChange={(val) => {
                    setNeedOptionDisorder(val ? 'OPTION_RANDOM' : 'OPTION_SORT');
                  }}></Switch>
                <div style={{ position: 'relative', left: 8, color: '#999' }}>
                  {needOptionDisorder == 'OPTION_RANDOM' ? '已开启，选项随机排序' : '已关闭，选项按设置顺序排序'}
                </div>
              </div>
            </Form.Item>

            <Form.Item label='考试结果查看' required>
              <Radio.Group
                onChange={(e: any) => {
                  setResultShow(e.target.value);
                }}
                value={resultShow}>
                <Radio value={'IMMEDIATELY'}>交卷后立即显示考试结果</Radio>
                <Radio value={'AFTER_EXAM_END'}>到达考试截止日期才显示结果</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item label=' 考试结果内容' required>
              <Radio.Group
                onChange={(e: any) => {
                  setResultContent(e.target.value);
                }}
                value={resultContent}>
                <Radio value={'PASS_AND_SCORE'}>显示考试分数和是否及格</Radio>
                <Radio value={'ONLY_SCORE'}>仅显示考试分数</Radio>
                <Radio value={'ONLY_PASS'}>仅显示是否及格</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item label='答案与解析' required>
              <Radio.Group
                onChange={(e: any) => {
                  setAnswerAnalysis(e.target.value);
                }}
                value={answerAnalysis}>
                <Radio value={'ANALYSE_AND_RIGHT_OR_WRONG'}>显示对错与解析</Radio>
                <Radio value={'RIGHT_OR_WRONG'}>仅显示对错</Radio>
                <Radio value={'CAN_NOT_CHECK'}>都不显示</Radio>
              </Radio.Group>
            </Form.Item>
          </Form>
        </div>
      </div>
      {showModal && (
        <SelectPaperModal
          onSelect={(info: any) => {
            setPaperInfo(info);
          }}
          paperInfo={paperInfo}
          close={() => {
            setShowModal(false);
          }}></SelectPaperModal>
      )}
      <div className='footer shrink-footer'>
        <Button onClick={handleGoBack}>取消</Button>
        <Button
          onClick={() => {
            setPreview(true);
          }}>
          预览
        </Button>
        <Button type='primary' onClick={handleSave}>
          保存
        </Button>
      </div>
      {preview && (
        <PreviewModal
          info={{
            paperId,
            startTime: examStartTime,
            endTime: examEndTime,
            examName,
            passRate: passRate / 100,
            examStartTime,
            examEndTime,
            examDesc,
            needPhone,
            needOptionDisorder,
            resultContent,
            answerAnalysis,
            resultShow,
            examDuration,
            passScore,
            examTotal,
            totalScore: paperInfo.totalScore,
          }}
          onClose={() => {
            setPreview(false);
          }}></PreviewModal>
      )}
    </div>
  );
}

export default withRouter(AddExam);
