/*
 * @Author: yuananting
 * @Date: 2021-08-03 17:05:32
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-18 17:25:30
 * @Description: 新建培训任务-关联考试抽屉
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useState, useEffect, useRef } from 'react';
import { Drawer, Form, Input, Button, Tooltip, Switch, Radio, InputNumber, message } from 'antd';
import GraphicsEditor from '@/modules/course-manage/components/GraphicsEditor';
import moment from 'moment';
import './RelatedExamDrawer.less';
import SelectPaperModal from '@/modules/teach-tool/examination-manager/SelectPaperModal';
import User from '@/common/js/user';
import TaskCenterService from '@/domains/task-center-domain/TaskCenterService';
import Bus from '@/core/bus';

function RelatedExamDrawer(props) {
  const [showPaperModal, setShowPaperModal] = useState(false);
  const [paperInfo, setPaperInfo] = useState({});
  const [answerAnalysis, setAnswerAnalysis] = useState('RIGHT_OR_WRONG'); // 答案与解析-默认仅显示对错
  const [examDesc, setExamDesc] = useState(''); // 考试说明
  const [examDuration, setExamDuration] = useState(null); // 考试时长
  const [examName, setExamName] = useState(''); // 考试名称
  const [needOptionDisorder, setNeedOptionDisorder] = useState('OPTION_SORT'); // 选项乱序-默认正常顺序
  const [paperId, setPaperId] = useState(null); // 选择的试卷id
  const [passRate, setPassRate] = useState(0); // 及格比例
  const [passScore, setPassScore] = useState(60); // 及格分数
  const [resultContent, setResultContent] = useState('PASS_AND_SCORE'); // 考试结果内容
  const [resultShow, setResultShow] = useState('IMMEDIATELY'); // 考试结果查看-卷后立即显示考试结果

  const [editorTextLength, setEditorTextLength] = useState(0); // 考试说明长度

  const [check, setCheck] = useState(false);
  const [examTotal, setExamTotal] = useState(0);

  const [samePaper, setSamePaper] = useState(false);
  const request = useRef(false);

  useEffect(() => {
    Bus.bind('editorLimit', (editorTextLength) => {
      setEditorTextLength(editorTextLength);
    });
  }, []);

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

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

  function handleSave() {
    if (request.current) {
      return;
    }
    setCheck(true);
    const params = {
      paperId,
      examName,
      passRate,
      examDuration: (examDuration || 0) * 60 * 1000,
      examDesc,
      needOptionDisorder,
      resultShow,
      resultContent,
      answerAnalysis,
      examEndTime: props.basicInfo.endTime || null,
      examStartTime: props.basicInfo.startTime || new Date().valueOf(),
      passScore,
      source: 0,
      tenantId: User.getStoreId(),
      userId: User.getStoreUserId(),
    };

    console.log('新建入参==============>', params);

    if (
      !paperId ||
      samePaper ||
      !examName ||
      examName.length > 40 ||
      !passRate ||
      !examDuration ||
      editorTextLength > 1000 ||
      (props.basicInfo.timeType === 'VALIDITY' &&
        props.basicInfo.startTime &&
        props.basicInfo.endTime &&
        props.basicInfo.startTime + examDuration * 60 * 1000 > props.basicInfo.endTime)
    ) {
      return;
    }

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

    TaskCenterService.createTrainingExam(params).then((res) => {
      props.onSave(res.result);
    });
  }

  return (
    <Drawer title='添加考试' width={720} maskClosable={false} closable={true} onClose={props.onClose} visible={true} mask className='related-exam-drawer'>
      <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} layout='horizontal'>
        <div className='module-title'>基本信息</div>
        <Form.Item
          label='选择试卷'
          validateStatus={(check && !paperId) || samePaper ? 'error' : ''}
          help={(check && !paperId && '请选择试卷') || (samePaper && '已存在相同试卷')}
          required>
          <Button
            onClick={() => {
              setShowPaperModal(true);
            }}>
            {paperInfo.paperId ? '重新选择' : '选择试卷'}
          </Button>
          {paperInfo.paperId && (
            <div className='paper-title'>
              <img src='https://image.xiaomaiketang.com/xm/pY5imEhjzw.png' alt='' /> {paperInfo.paperName}
            </div>
          )}
          {paperInfo.paperId && (
            <div className='paper-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' style={{ borderBottom: '1px solid #e8e8e8' }}>
                <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='考试名称'
          validateStatus={check && (!examName || examName.length > 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: 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 ||
              (props.basicInfo.timeType === 'VALIDITY' &&
                props.basicInfo.startTime &&
                props.basicInfo.endTime &&
                props.basicInfo.startTime + examDuration * 60 * 1000 > props.basicInfo.endTime))
              ? 'error'
              : ''
          }
          help={
            check &&
            ((!examDuration && '请输入考试时长') ||
              (props.basicInfo.timeType === 'VALIDITY' &&
                props.basicInfo.startTime &&
                props.basicInfo.endTime &&
                props.basicInfo.startTime + examDuration * 60 * 1000 > props.basicInfo.endTime &&
                '考试时长不得超过培训有效期时长'))
          }
          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='考试说明'>
          <GraphicsEditor
            maxLimit={1000}
            isIntro={true}
            detail={{
              content: examDesc,
            }}
            onChange={(val) => {
              setExamDesc(val);
            }}
          />
        </Form.Item>
        <div className='module-title' style={{ marginTop: 16 }}>
          考试设置
        </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) => {
              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) => {
              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 className='footer shrink-footer'>
        <Button onClick={props.onClose}>取消</Button>
        <Button type='primary' onClick={handleSave}>
          确定
        </Button>
      </div>
      {showPaperModal && (
        <SelectPaperModal
          onSelect={(info) => {
            let newContentList = [];
            props.stageList.map((item) => {
              if (item.contentList && item.contentList.length > 0) {
                item.contentList.map((childItem) => {
                  newContentList.push(childItem);
                });
              }
            });
            const existedPaperId = newContentList.filter((item) => {
              return item.paperId === info.paperId;
            });
            if (existedPaperId.length > 0) {
              setSamePaper(true);
            } else {
              setSamePaper(false);
            }
            setPaperInfo(info);
          }}
          paperInfo={paperInfo}
          close={() => {
            setShowPaperModal(false);
          }}></SelectPaperModal>
      )}
    </Drawer>
  );
}

export default RelatedExamDrawer;
