import React, { useState, useRef, useEffect, useContext } from 'react'
import Breadcrumbs from "@/components/Breadcrumbs";
import { Form, Alert, Input, Button, InputNumber, DatePicker, Switch, Radio } 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 './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 [examDuration, setExamDuration] = useState(0);
    useEffect(() => {
        console.log(paperInfo)
        setPaperId(paperInfo.paperId)
        setPassRate(paperInfo.passScore)

    }, [paperInfo.paperId])

    useEffect(() => {
        setPassScore(parseInt((paperInfo.totalScore || 0) * (passRate || 0) as any / 100 + ''))

    }, [paperInfo.paperId, passRate])

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


    function handleSave() {
        const param = {
            paperId,
            startTime:examStartTime,
            endTime:examEndTime,
            examName,
            passRate,
            examStartTime,
            examEndTime,
            examDesc,
            needPhone,
            needOptionDisorder,
            resultContent,
            answerAnalysis,
            resultShow,
            examDuration,
            passScore,
            tenantId: User.getStoreId(),
            source: 0
        }
        Service.Hades("public/hades/createExam", param).then((res) => {

        })
    }


    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: () => [],
        };
    }

    return <div className="page examPage">
        <Breadcrumbs navList={"新建考试"} goBack={() => props.history.goBack()} />

        <div className="box">
            <Alert message="请遵守国家相关规定，切勿上传低俗色情、暴力恐怖、谣言诈骗、侵权盗版等相关内容，小麦企培保有依据国家规定及平台规则进行处理的权利" type="info" showIcon />
            <div className="form">
                <div className="title">基本信息</div>
                <Form
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 14 }}
                    layout="horizontal"
                >
                    <Form.Item label="考试名称" required>

                        <Input placeholder='请输入试卷名称（40字以内）' value={examName} onChange={(e) => {
                            console.log(e.target.value)
                            setExamName(e.target.value)
                        }} style={{ width: 300 }} />
                    </Form.Item>

                    <Form.Item label="选择试卷" required>
                        <span style={{ marginRight: 12, lineHeight: '32px' }}>{paperInfo.paperName}</span>  <Button onClick={() => { setShowModal(true) }} >{paperInfo.paperId ? '重新选择' : '选择试卷'}</Button>


                    </Form.Item>

                    {
                        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">不定项选择题</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">{paperInfo.singleChoiceCnt + paperInfo.multiChoiceCnt + paperInfo.judgeCnt + paperInfo.gapFillingCnt + paperInfo.indefiniteChoiceCnt || 0}题</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">{paperInfo.totalScore || 0}分</div>
                            </div>
                        </div>
                    }


                    <Form.Item label="及格线" style={{marginTop:24}} required>
                        <InputNumber value={passRate} onChange={(value: any) => { setPassRate(value) }} style={{ width: 100 }} />
                        <span style={{ marginLeft: 4 }}>%
                        </span>
                        <span style={{ marginLeft: 20, color: "#999" }}>
                            {`  总分(${paperInfo.totalScore || 0})*及格线（${passRate || 0}%）=及格分数（${passScore}）`}</span>
                    </Form.Item>

                    <Form.Item label="考试有效期" required>
                        <RangePicker
                            ranges={{
                                '近七天': [moment(), moment().add(6, 'day').endOf('day')],
                                '近1个月': [moment(), moment().add(1, 'month').endOf('day')],
                                '近3个月': [moment(), moment().add(3, 'month').endOf('day')],
                            }}
                            disabledDate={disabledDate}
                            value={[
                                examStartTime ? moment(Number(examStartTime)) : null,
                                examEndTime ? moment(Number(examEndTime)) : null
                            ]}
                            disabledTime={disabledRangeTime}
                            showTime
                            format="YYYY/MM/DD HH:mm"
                            onChange={(date: any) => {
                                setStartTime(date && date[0]?.startOf('day').valueOf());
                                setExamEndTime(date && date[1]?.endOf('day').valueOf());

                            }}
                        />
                    </Form.Item>
                    <Form.Item label="考试时长" required>
                        <InputNumber value={examDuration} max={1440} min={1} onChange={(value: any) => { setExamDuration(value) }} style={{ width: 100 }} />
                        <span style={{ marginLeft: 4 }}>分钟
                        </span>
                        <span style={{ marginLeft: 20, color: "#999" }}>
                            {` 时长不能超过1440分钟（24小时）`}</span>
                    </Form.Item>

                    <Form.Item label="考试说明" required>
                        <GraphicsEditor

                            isIntro={true}
                            detail={{
                                content: examDesc
                            }}
                            onChange={(val: any) => { setExamDesc(val) }}
                        />
                    </Form.Item>
                    <div className="title" style={{ marginTop: 40 }}>考试设置</div>
                    <Form.Item label="身份验证" required>
                        <div style={{ display: 'flex', marginLeft: 4, }}>
                            <Switch style={{ position: 'relative', top: 6 }}
                                checked={needPhone == 'NEED_PHONE_VERIFY'}
                                onChange={(val) => { setNeedPhone(val ? 'NEED_PHONE_VERIFY' : 'DO_NOT_NEED_PHONE_VERIFY') }}
                            ></Switch>
                            <div style={{ position: 'relative', top: 3, left: 8, color: "#999" }}><p>开启：需要验证手机号才能参加考试</p>
                                <p>关闭：仅需微信/企业微信授权登录验证</p></div>
                        </div>

                    </Form.Item>

                    <Form.Item label="选项乱序" required>
                        <div style={{ display: 'flex', marginLeft: 4, }}>
                            <Switch style={{ position: 'relative', top: 6 }}
                                checked={needOptionDisorder == 'OPTION_RANDOM'}
                                onChange={(val) => { setNeedOptionDisorder(val ? 'OPTION_RANDOM' : 'OPTION_SORT') }}
                            ></Switch>
                            <div style={{ position: 'relative', top: 3, left: 8, color: "#999" }}><p>开启：选择题的选项随机排序</p>
                                <p>关闭：选择题按题目原有顺序展示</p></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) => {
                console.log(info, 'jkhjkhjk')
                setPaperInfo(info)
            }} paperInfo={paperInfo} close={() => { setShowModal(false) }}></SelectPaperModal>
        }
        <div className="footer">
            <Button onClick={() => { }}>取消</Button>
            <Button onClick={() => { }}>预览</Button>
            <Button type="primary" onClick={_.debounce(() => { handleSave() }, 3000, true)}>保存</Button>
        </div>
    </div>
}


export default withRouter(AddExam);