/*
 * @Author: yuananting
 * @Date: 2021-08-03 17:05:32
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-03 18:05:53
 * @Description: 新建培训任务-关联考试抽屉
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useState, useRef } from 'react';
import { Drawer, Form, Input, Button, Tooltip, Switch, Radio, DatePicker, InputNumber } from 'antd';
import GraphicsEditor from '@/modules/course-manage/components/GraphicsEditor';
import moment from 'moment';
import './RelatedExamDrawer.less';

const { RangePicker } = DatePicker;

function RelatedExamDrawer(props) {
  const paperInfoInit = { 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 [examList, setExamList] = useState([]);
  const request = useRef(false);
  const { match } = props;

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

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

  function queryExamList() {
    let param = {
      current: 1,
      size: 9999,
      order: 'EXAM_START_TIME_DESC',
      userId: User.getStoreUserId(),
      tenantId: User.getStoreId(),
      source: 0,
    };
    Service.Hades('public/hades/queryExamPageList', param).then((res) => {
      const { result = {} } = res;
      setExamList(result.records || []);
    });
  }

  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);
      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 (checkExist(param.examName)) {
      message.warning('此考试名称已存在');
      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 * 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, type) {
    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');
      },
    });
  }

  // 校验考试名称是否存在
  function checkExist(examName) {
    var result = null;
    examList.length > 0 &&
      examList.forEach((item) => {
        if (result != null) {
          return result;
        }
        if (props.type === 'edit') {
          if (item.examName === examName && item.examId !== match.params.id) {
            result = item;
          }
        } else {
          if (item.examName === examName) {
            result = item;
          }
        }
      });
    return result;
  }

  return (
    <Drawer title='添加考试' width={720} maskClosable={false} closable={true} onClose={props.onClose} visible={true} mask className='related-exam-drawer'>
      <div>
        <div className='module-title'>基本信息</div>
        <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} layout='horizontal'>
          <Form.Item label='选择试卷' validateStatus={check && !paperId ? 'error' : ''} help={check && !paperId && '请选择试卷'} required>
            <Button
              onClick={() => {
                setShowModal(true);
              }}>
              {paperInfo.paperId ? '重新选择' : '选择试卷'}
            </Button>
          </Form.Item>

          <Form.Item
            label='考试名称'
            validateStatus={check && (!examName || examName.length > 40 || checkExist(examName)) ? 'error' : ''}
            help={check && (!examName ? '请输入考试名称' : examName.length > 40 ? '考试名称最多40字' : checkExist(examName) && '此考试名称已存在')}
            required>
            <Input
              placeholder='请输入考试名称（40字以内）'
              maxLength={40}
              value={examName}
              onChange={(e) => {
                setExamName(e.target.value);
              }}
              style={{ width: 300 }}
            />
          </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) => {
                setPassRate(parseInt(value));
              }}
              style={{ width: 100 }}
            />
            <span style={{ marginLeft: 8 }}>%</span>
            <span style={{ marginLeft: 16, color: '#999' }}>{`  总分(${paperInfo.totalScore || 0})*及格线（${passRate || 0}%）=及格分数（${passScore}）`}</span>
          </Form.Item>
          <Form.Item label='考试时长' validateStatus={check && !examDuration ? 'error' : ''} help={check && !examDuration && '请输入考试时长'} required>
            <InputNumber
              value={examDuration}
              max={1440}
              min={1}
              onChange={(value) => {
                setExamDuration(parseInt(value));
              }}
              style={{ width: 100 }}
            />
            <span style={{ marginLeft: 8 }}>分钟</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个字'}>
            <GraphicsEditor
              maxLimit={1000}
              isIntro={true}
              detail={{
                content: examDesc,
              }}
              onChange={(val, len) => {
                setExamDesc(val);
                setDescLen(len);
              }}
            />
          </Form.Item>
          <div className='module-title'>考试设置</div>

          <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) => {
                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) => {
                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>
    </Drawer>
  );
}

export default RelatedExamDrawer;
