/**
 * 作业类章节
 */
import React from 'react'
import Formsy from 'formsy-react';
import FormsyComponent from '../../components/formsy/Component.jsx'
import FormItem from '../../components/formsy/FormItem.jsx'
import CoursesAction from '../../actions/CoursesAction'
import OperateAction from '../../actions/OperateAction'
import { getRequestTypes } from '../../libs/utils';

class ChapterWork extends FormsyComponent {

    constructor(props) {
        super(props);
        this.state = { error: '' };
    }
    componentDidMount () {
        this.courseAction = new CoursesAction();
        this.operateAction = new OperateAction();

        this.startTime = (new Date()).getTime();
        // 加载回答
        this.props.dispatch(this.courseAction.loadChapterWork(this.props.semesterId, this.props.chapter.homework.id));
    }
    componentWillReceiveProps (nextProps) {
        let submitType = getRequestTypes(CoursesAction.SUBMIT_CHAPTER_WORK);
        switch (nextProps.action.type) {
            case submitType.success:
                this.enableSubmitButton();
                // 提交成功，重新获取答案
                nextProps.dispatch(this.courseAction.loadChapterWork(this.props.semesterId, nextProps.chapter.homework.id));
                nextProps.handleSubmited(nextProps.chapter.id);
                break;
            case submitType.failure:
                this.enableSubmitButton();
                nextProps.dispatch(this.operateAction.showErrorMessage(nextProps.action.error.message || '提交章节作业失败'));
                break;
        }
    }


    /**
     * 提交登录
     */
    onSubmit = model => {
        this.loadingSubmitButton();

        const {courseId, chapter, semesterId} = this.props;
        const questions = chapter.homework && chapter.homework.questions || [];
        let data = {
            course_id: courseId,
            chapter_id:chapter.id,
            work_id: chapter.homework.id,
            semester_id: semesterId,
            work_contents: '',
            duration: Math.ceil(((new Date()).getTime() - this.startTime) / 1000),
        }

        // 组织返回答案结构
        let answers = questions.map(q => {
            return {
                question_id: q.id,
                descreption: model['desc_' + q.id],
                file_url: model['file_' + q.id]
            };
        });

        data.work_contents = JSON.stringify(answers);

        this.props.dispatch(this.courseAction.submitChapterWork(data));
    }

    // 表单变更时，取消掉全局错误消息
    onFormChange = () => {
        this._setState({ error: '' });
    }
    handleUploadError = msg => {
        this.props.dispatch(this.operateAction.showErrorMessage(msg || '上传文件失败'));
    }

    render () {
        const {chapter, chapter_work} = this.props;
        const questions = chapter.homework && chapter.homework.questions || [];
        let work = null;
        let answers = {}
        if (chapter_work.data && chapter_work.data.work_contents) {
            work = chapter_work.data;
            try {
                let answerObject = JSON.parse(work.work_contents);
                answerObject.forEach(a => {
                    answers[a.question_id] = a;
                })
            } catch(e) {console.log('parse work_contents to json failed.')}
        }
        return (
            <div className="play-paper">
                <div className="play-paper-body">
                    <div className="play-paper-title"><div><h3>{chapter.name}</h3></div></div>
                    <div className="play-paper-content play-chapter-work">

                        <Formsy.Form
                            onValid={this.enableSubmitButton}
                            onInvalid={this.disableSubmitButton}
                            onValidSubmit={this.onSubmit}
                            onChange={this.onFormChange}
                        >
                            {questions.length ?
                                <ul>
                                    {questions.map((q, qi) => {
                                        let answer = answers[q.id] || {};
                                        return (
                                            <li key={qi}>
                                                <div className="work-number">{qi + 1}.</div>
                                                <div className="work-title">
                                                    <div className="edit_html" dangerouslySetInnerHTML={{__html: q.question_content}}></div>
                                                </div>
                                                <FormItem
                                                    name={'desc_' + q.id}
                                                    itemType={FormItem.TEXTRICH}
                                                    value={answer.descreption || ''}
                                                    required
                                                />
                                                <FormItem
                                                    name={'file_' + q.id}
                                                    fileVal="file"
                                                    value={answer.file_url || ''}
                                                    btnClassName="upbtn"
                                                    label="请上传对应的文件附件："
                                                    itemType={FormItem.FILE}
                                                    text="上传附件"
                                                    server="/api/tenant/util/upload-file"
                                                    fileSingleSizeLimit={1024*1024*10}
                                                    accept={[{extensions: 'docx'}]}
                                                    onFileError={this.handleUploadError}
                                                />
                                                <p className="help help-file">只支持docx格式的文件，文件小于10M</p>
                                                {answer.file_url && <a style={{display: 'block', marginBottom: '20px', color: 'blue'}} href={answer.file_url} >下载附件</a> }
                                            </li>
                                        );
                                    })}
                                </ul>
                                :
                                <p className="no-data">暂无数据</p>
                            }
                            <p className="text-danger">{this.state.error}</p>
                            <div className="area-btns">
                                <button type="submit" disabled={!this.canSubmit() || (work && work.checker_id)} className="btn btn-primary" >{this.isSubmitLoading() ? '保存中...' : (work && work.checker_id) ? '已批改' : '提交'}</button>
                                <span className="help-info">&emsp;&emsp;在获老师批改之前，可以多次提交，将以最后一次提交为准</span>
                                {work ?
                                    !work.checker_id ?
                                    <p className="help">已于 {work.created_time} 提交，等待批改中</p>
                                    :
                                    <div className="play-paper-check">
                                        <h4>已获批改 <small>批改于{work.check_date}</small></h4>
                                        <div className="play-paper-check-item"><b>评分：</b>{work.score}</div>
                                        <div className="play-paper-check-item">
                                            <b>评语：</b>
                                            <div className="edit_html" dangerouslySetInnerHTML={{__html:work.check_comments}}></div>
                                        </div>
                                    </div>
                                    : null
                                }
                            </div>
                        </Formsy.Form>

                    </div>
                </div>
            </div>
        );
    }
}

module.exports = ChapterWork;
