/**
 * 课程大作业
 * porps:
 *      course
 *      course_work
 *      action
 *      dispatch
 */
import React, { Component } from 'react'
import { Link } from 'react-router';
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 CourseWork extends FormsyComponent {
    constructor(props) {
        super(props);
        this.state = { error: '' };
    }
    componentDidMount () {
        this.courseAction = new CoursesAction();
        this.operateAction = new OperateAction();
        this.courseId = this.props.course.course_id;
        this.semesterId = this.props.semesterId;
        // 加载回答
        this.props.dispatch(this.courseAction.loadCourseWork(this.semesterId, this.courseId));
    }
    componentWillReceiveProps (nextProps) {
        let submitType = getRequestTypes(CoursesAction.SUBMIT_COURSE_WORK);
        switch (nextProps.action.type) {
            case submitType.success:
                this.enableSubmitButton();
                if (nextProps.action.response.data.status == 0) {
                    nextProps.dispatch(this.operateAction.showErrorMessage('账号出错，请联系管理员'));
                    console.log(JSON.stringify(nextProps.action.response.data.error))
                    break;
                }
                // 提交成功，重新获取答案
                nextProps.dispatch(this.courseAction.loadCourseWork(this.semesterId, this.courseId));
                nextProps.handleSubmited('work');
                break;
            case submitType.failure:
                this.enableSubmitButton();
                nextProps.dispatch(this.operateAction.showErrorMessage(nextProps.action.error.message || '提交课程大作业失败'));
                break;
        }
    }

    /**
     * 提交
     */
    onSubmit = model => {
        this.loadingSubmitButton();
        model.course_id = this.props.course.course_id;
        model.semester_id = this.props.semesterId;
        this.props.dispatch(this.courseAction.submitCourseWork(model));
    }

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

    render () {
        const {course, course_work} = this.props;
        const info = course_work.data || {};
        return (
            <div className="play-paper">
                <div className="play-paper-body">
                    <div className="play-paper-title"><div><h3>课程大作业</h3></div></div>
                    <div className="play-paper-content">

                        <div className="play-paper-step">&#9312; 阅读大作业要求</div>
                        <div className="edit_html" dangerouslySetInnerHTML={{__html: course.curriculum && course.curriculum.curriculum_essay || ''}}></div>
                        <p>截止日期：{course.essay_date || ''}</p>


                        <div className="play-paper-step">&#9313; 填写作业主题、摘要，上传附件（点击“提交”保存）</div>
                        <Formsy.Form
                            onValid={this.enableSubmitButton}
                            onInvalid={this.disableSubmitButton}
                            onValidSubmit={this.onSubmit}
                            onChange={this.onFormChange}
                        >
                            <input type="hidden" name="id" value={info.id || ''} />
                            <div>
                                <FormItem
                                    name="essay_name"
                                    value={info.essay_name || ''}
                                    placeholder="主题"
                                    required
                                />

                                <FormItem
                                    name="essay_description"
                                    value={info.essay_description || ''}
                                    label="摘要"
                                    itemType={FormItem.TEXTRICH}
                                    required
                                />
                                <FormItem
                                    name="url"
                                    fileVal="file"
                                    value ={info.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}
                                    required
                                />
                                <p className="help help-file">只支持docx格式的文件，文件小于10M</p>
                                {info.file_url && <a style={{display: 'block', marginBottom: '20px', color: 'blue'}} href={info.file_url} >下载附件</a> }
                            </div>
                            <p className="text-danger">{this.state.error}</p>

                            <div className="area-btns">
                                <div className="play-paper-step">&#9314; 截止日期前提交</div>
                                <button type="submit" disabled={!this.canSubmit() || info.checker_id} className="btn btn-primary" >{this.isSubmitLoading() ? '保存中...' : info.checker_id ? '已批改' : '提交'}</button>
                                <span className="help-info">&emsp;&emsp;在获老师批改之前，可以多次提交，将以最后一次提交为准</span>
                                {info.id ?
                                    !info.checker_id ?
                                    <p className="help">已于 {info.created_time} 提交，等待批改中</p>
                                    :
                                    <div className="play-paper-check">
                                        <h4>已获批改 <small>批改于{info.check_date}</small></h4>
                                        <div className="play-paper-check-item"><b>评分：</b>{info.score}</div>
                                        <div className="play-paper-check-item">
                                            <b>评语：</b>
                                            <div className="edit_html" dangerouslySetInnerHTML={{__html:info.check_comments}}></div>
                                        </div>
                                    </div>
                                    : null
                                }
                            </div>
                        </Formsy.Form>

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

module.exports = CourseWork
