Exercises.js 18.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
/**
 * Created by mac on 2017/5/8.
 */
import React, {Component} from "react";
import {Alert, AsyncStorage, Image, Platform, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import {action, observable} from "mobx";
import NavBar from "../NavBar/NavBar";
import {getDataById, items, loadData, subList, getCorrect, getScore} from "../../utils/excer";
import {observer} from 'mobx-react/native';
import {width} from "../../utils/getSize";
import SubItem from "./SubItem";
import CircleBox from "./CircleBox";
import ResultModal from "./ResultModal";
import {xnToast,isIphoneX} from "../../utils/utils";
import AppService from "../../service/AppService";
import PropTypes from 'prop-types';
const select = require('../../img/datiSelect.png');
const shangyiti = require("../../img/shangyiti-02.png");
const xiayiti = require('../../img/xiayiti-02.png');
const shangyiti_red = require('../../img/shangyiti-01.png');
const xiayiti_red = require('../../img/xiayiti-01.png');
const __IOS__ = Platform.OS == "ios";


@observer
export default class Exercises extends Component {
    // static contextTypes = {
    //     navigator: PropTypes.object,
    // };

    static navigationOptions = ({navigation, screenProps}) => ({
        header: null,
        gesturesEnabled:false
    });

    @observable
    id = 1;//记录当前是第几题

    questionIds = [];
    optionSet = new Set();

    //点击了下一题后触发
    @action
    inc = () => {
        let item = getDataById(this.id);//根据id获取question
        if (this.id < subList.length) {
            this.id++;
        }
        item.setLoading();
    };

    //点击了上一题后触发
    @action
    dec = () => {
        let item = getDataById(this.id);
        if (this.id > 1) {
            this.id--;
        }
    };



    componentWillMount() {
        // console.warn("type = " + this.props.type);
        if (this.props.navigation.state.params.type == 'allLoad') {
            this.getQuestions2(this.getQuestionsAndMakeUp);
        }
        else if (this.props.navigation.state.params.type == 'resultModal') {
            this.setPage(this.props.navigation.state.params.CurrentId);
        }
        else {
            this.getQuestions();//从后台加载习题数据
        }
    }

    async componentDidMount() {

    }

    onUpdated = () => {
        if (subList.length == 0) {
            // this.context.navigator.pop();
            // Toast.show("该课次下没有习题!");
        } else {
            this.forceUpdate();
        }
    }

    //上一页面会将课次ID传过来
    getQuestions = () => {
        let that = this;
        //初始化默认数据
        // loadData(items.result);
        // let id = "873078041528897536";
        // let type = "COURSE_LESSON";
        let id = this.props.navigation.state.params.objectId;
        let type = this.props.navigation.state.params.objectType;
        //加载习题信息
        AppService.findTestingQuestion({objectType:type,objectId:id}).then((data) => {
            if (data.message) {
                xnToast(data.message);
                return;
            }
            if (data.errors.length > 0) {
                xnToast(data.errors[0].message);
            } else {
                loadData(data.result, () => this.onUpdated());//加载数据,获取questions
            }
        }).catch(error => {
            xnToast(error);
        });
    };

    getQuestions2 = (callback) => {
        let that = this;
        // loadData(items.result);
        let id = this.props.navigation.state.params.objectId;
        let type = this.props.navigation.state.params.objectType;
        //加载习题信息
        AppService.findTestingQuestion({objectType:type,objectId:id}).then((data) => {
            if (data.message) {
                xnToast(data.message);
                return;
            }
            if (data.errors.length > 0) {
                xnToast(data.errors[0].message);
            } else {
                loadData(data.result, () => this.onUpdated());
                callback();
            }
        }).catch(error => {
            xnToast(error);
        });
    };

    //从服务器获取习题详情,并解析数据并组合
    getQuestionsAndMakeUp = () => {
        subList.map((v, i) => {
            this.questionIds.push(v.questionId);
        });

        AppService.getTestingAnswerOptionIdsByQIds({ids:this.questionIds}).then((data) => {
            if (data.message) {
                xnToast(data.message);
                return;
            }
            if (data.errors.length > 0) {
                xnToast(data.errors[0].message);
            } else {
                // console.warn("datadata====ids = " + JSON.stringify(data.ids));
                //将获取到的OptionIds放到optionSet中
                data.ids.map((v, i) => {
                    this.optionSet.add(v.optionId);
                });

                if (this.props.navigation.state.params.type == 'allLoad') { //如果是显示结果,就跳转到结果页面,前提是已经获取到值了
                    // this.props.navigation.replace('ResultModal',{
                    //     setPage: (id) => this.setPage(id),
                    //     do: this.props.navigation.state.params.do,
                    //     optionSet: this.optionSet,
                    //     testTitle: this.props.navigation.state.params.testTitle
                    // });
                    this.props.navigation.navigate('ResultModal',{
                        setPage: (id) => this.setPage(id),
                        do: this.props.navigation.state.params.do,
                        optionSet: this.optionSet,
                        testTitle: this.props.navigation.state.params.testTitle
                    });
                }
                // 遍历subList,将Sub的selected赋值
                let subListCopy = subList.slice(0);
                for (let i = 0; i < subList.length; i++) {
                    let sub = subList[i];
                    for (let j = 0; j < sub.optionArr.length; j++) {
                        let subItem = sub.optionArr[j];
                        if (this.optionSet.has(subItem.optionId)) {
                            subListCopy[i].setValue(j + 1);
                            subListCopy[i].selectId = (j + 1);
                            subListCopy[i].value_correct = subItem.is_correct;
                        }
                    }
                }

                subList.replace(subListCopy);
            }
        }).catch(error => {
            xnToast(error);
        });

    };

    submitAnswers = (answers) => {

        //提交题目请求
        AppService.judgeTestingQuestionAnswer({id:this.props.navigation.state.params.objectId,userId:global.userId,userName:global.userName,unionId:global.unionId,answers:answers}).then((data) => {
            if (data.message) {
                xnToast(data.message);
                return;
            }
            if (data.errors.length > 0) {
                xnToast(data.errors[0].message);
            } else {
                this.props.navigation.state.params.setScore(data.score);
                if (getScore() != 0) {
                    this.addScore(getScore());
                }
            }
        }).catch(error => {
            xnToast(error);
        });


    };

    addScore = (score) => {

        // let request = {};
        // request.method = "member.point.add";
        // request.memberId = global.cache.member.id;
        // request.point = score;
        // request.sourceId = this.props.navigation.state.params.objectId;
        // request.sourceType = "ANSWER_QUESTION";
        // request.summary = "from exercise";
        // post(request).then(data => {
        //     // console.warn(JSON.stringify(data));
        //     if (!!data.errors == true && data.errors.length > 0) {
        //         Toast.show(data.errors[0].message);
        //     }
        //     else {
        //         Toast.show("增加了" + score + "荷磅");
        //     }
        // });
    };

    sleep = (time) => {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                // 返回 ‘ok’
                resolve('ok');
            }, time);
        })
    };

    //上一题 第几题 下一题
    infoTime = () => {
        let item = getDataById(this.id);

        return (
            <View style={styles.infoTime}>
                <TouchableOpacity style={[styles.btnSelect, styles.start]} onPress={() => this.dec()}>
                    {
                        this.id == 1 ?
                            <Image
                                source={shangyiti}
                                style={[styles.icon, {marginRight: 5}]}
                                resizeMode="contain"
                            /> :
                            <Image
                                source={shangyiti_red}
                                style={[styles.icon, {marginRight: 5}]}
                                resizeMode="contain"
                            />
                    }
                    {
                        this.id > 1 ? <Text style={[styles.fontYiti, {color: "#e52d43"}]}>上一题</Text>
                            : <Text style={styles.fontYiti}>上一题</Text>
                    }

                </TouchableOpacity>
                <View style={styles.centerText}>
                    <Text style={[styles.fontYiti]}>{item.id + "/" + subList.length}</Text>
                </View>
                <TouchableOpacity style={[styles.btnSelect, styles.end]} onPress={() => this.inc()}
                                  disabled={this.id >= subList.length}>
                    {
                        this.id < subList.length ?
                            <Text style={[styles.fontYiti, {color: "#e52d43"}]}>下一题</Text>
                            : <Text style={styles.fontYiti}>下一题</Text>
                    }
                    {
                        this.id < subList.length ? <Image
                            source={xiayiti_red}
                            style={[styles.icon, {marginLeft: 5}]}
                            resizeMode="contain"
                        />
                            :
                            <Image
                                source={xiayiti}
                                style={[styles.icon, {marginLeft: 5}]}
                                resizeMode="contain"
                            />
                    }

                </TouchableOpacity>
            </View>
        )
    };
    setPage = (id) => {
        this.id = id;
    };
    add = () => {
        if (this.id < subList.length) {
            this.id++;
        } else {
            this.props.navigation.navigate('ResultModal',{
                setPage: (id) => this.setPage(id),
                do: this.props.navigation.state.params.do,
                testTitle: this.props.navigation.state.params.testTitle
            });
            // this.props.navigation.replace('ResultModal',{
            //     setPage: (id) => this.setPage(id),
            //     do: this.props.navigation.state.params.do,
            //     testTitle: this.props.navigation.state.params.testTitle
            // });
        }
    };
    subLast = () => {

        //遍历subList,生成answers
        let answers = [];

        subList.map((v, i) => {
            let questionId = v.questionId;
            let options = v.optionArr;
            options.map((v, i) => {
                if (v.select) {//如果选中,则存到answers中
                    let answer = {
                        questionId:questionId,
                        optionId:v.optionId,
                        userId:global.userId,
                        userName:global.userName,
                        unionId:global.unionId
                    };

                    answers.push(answer);
                }
            })
        });

        if (answers.length<subList.length){
            xnToast('当前有习题尚未完成,请检查!');
            return;
        }

        Alert.alert(
            '注意',
            "提交后将不能更改,确定提交答题吗?",
            [
                {text: '取消', onPress: () => console.log('OK Pressed!')},
                {text: '确定', onPress: () => {

                        let item = getDataById(this.id);
                        item.setLoading();
                        this.submitAnswers(answers);
                        // this.props.navigation.replace('ResultModal',{
                        //     setPage: (id) => this.setPage(id),
                        //     do: this.props.navigation.state.params.do,
                        //     testTitle: this.props.navigation.state.params.testTitle
                        // });
                        this.props.navigation.navigate('ResultModal',{
                            setPage: (id) => this.setPage(id),
                            do: this.props.navigation.state.params.do,
                            testTitle: this.props.navigation.state.params.testTitle
                        });
                    }},
            ]
        )


    };

    submitButton = (item) => {
        if (this.id == subList.length) {  //如果是最后一道题就显示提交按钮
            if (this.props.navigation.state.params.type != 'allLoad' && this.props.navigation.state.params.type != 'resultModal') {
                return <View style={styles.lastBlock}>
                    <TouchableOpacity style={styles.subBtn} onPress={() => {
                        this.subLast();
                        }
                    }>
                        <Text style={styles.font15}>提交答题</Text>
                    </TouchableOpacity>
                </View>
            }
        }
    }

    circleBox = (item) => {
        if (this.props.navigation.state.params.type != 'allLoad' && this.props.navigation.state.params.type != 'resultModal') {
            return <CircleBox/>
        }
    }

    render() {
        let item = getDataById(this.id);
        if (item == undefined || item == null) {
            return (
                <View style={styles.container}>
                    <Text style={{fontSize: 40,
                        fontWeight: 'bold'}}>
                        该课次下没有习题
                    </Text>
                </View>
            )
        }

        return (
            <View style={styles.container}>
                <NavBar renderBack messageBack={'答题尚未完成,是否退出?'}
                        style={styles.navShadow} nav={this.props.navigation}>
                    <Text style={styles.fontTitle} numberOfLines={1}>{this.props.navigation.state.params.testTitle}-课后习题</Text>
                </NavBar>

                <SubItem data={item} add={this.add} type={this.props.navigation.state.params.type}/>

                {this.infoTime()}
                {this.submitButton(item)}
                {this.circleBox(item)}
            </View>
        )
    }
}
const styles = StyleSheet.create({
    subBtn: {
        width: 120,
        height: 30,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 15,
        backgroundColor: '#e52d43'
    },
    font15: {
        fontSize: 15,
        color: 'white'
    },
    fontTitle: {
        fontSize: 16,
        fontWeight: 'bold'
    },
    lastBlock: {
        alignItems: 'center',
    },
    container: {
        flex: 1,
        backgroundColor: 'rgb(241,242,243)',
        alignItems: 'center',
        marginTop: __IOS__ ?isIphoneX?44: 20 : 0
    },
    navShadow: {
        shadowColor: '#999999',
        shadowOffset: {height: 0, width: 2},
        shadowRadius: 3,
        shadowOpacity: 0.6,
    },
    content: {
        marginLeft: 30,
        marginRight: 30,
        paddingTop: 20
    },
    exceBlock: {
        width: width - 60,
        borderRadius: 15,
        overflow: 'hidden',
        shadowColor: '#999999',
        shadowOffset: {height: 0, width: 2},
        shadowRadius: 3,
        shadowOpacity: 1,
    },
    titleBlock: {
        height: 85,
        width: width - 60,
        backgroundColor: "rgb(225,49,72)",
        alignItems: 'center',
    },
    fontTitleBar: {
        position: 'absolute',
        marginTop: 5,
        marginLeft: 25,
        color: "rgba(255,255,255,0.2)",
        fontSize: 60,
        backgroundColor: 'transparent'
    },
    fontTitleCon: {
        position: 'absolute',
        marginTop: 25,
        marginLeft: 25,
        marginRight: 15,
        fontSize: 15,
        fontWeight: 'bold',
        color: '#fff',
        backgroundColor: 'transparent'
    },
    option: {
        backgroundColor: '#ffffff',
        paddingTop: 15,
        paddingBottom: 10
    },
    optionBlock: {
        width: width - 60,
        paddingLeft: 25,
        flexDirection: 'row'
    },
    fontText: {
        fontSize: 14,
        color: "#333333",
        marginTop: 15,
        marginBottom: 10,
    },
    circle: {
        borderWidth: 1,
        borderColor: '#999999',
        width: 16,
        height: 16,
        borderRadius: 16,
        marginTop: 15,
        marginBottom: 20,
        marginRight: 10
    },
    infoTime: {
        width: width - 60,
        marginTop: 20,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingLeft: 15,
        paddingRight: 15,
    },
    btnSelect: {
        flexDirection: 'row',
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        height: 50,
        paddingBottom: 30,
    },
    icon: {
        width: 14,
        height: 14,

    },
    fontYiti: {
        fontSize: 14,
        color: "#bbbbbb"
    },
    centerText: {
        flex: 1,
        alignItems: 'center',
        height: 50,
    },
    end: {
        justifyContent: 'flex-end'
    },
    start: {
        justifyContent: 'flex-start'
    },
    reasonInfo: {
        flex: 1,
        width: width - 60,
        marginTop: 25
    },
    jxTitle: {},
    fontJx: {
        fontSize: 14,
        color: '#333'
    },
    jxCon: {
        flex: 1
    },
    fontJxCon: {
        fontSize: 12,
        color: '#999999',
        lineHeight: 20
    },
    progress: {
        marginTop: 80
    },
    font: {
        fontSize: 35,
        color: '#999999',
        textAlign: 'center',
        marginTop: -75,
        backgroundColor: 'transparent'
    }
});