app.controller('SendClassListController', ['$scope', '$http','$routeParams', 'config','auth','alertService', 'rms','common', function($scope, $http, $routeParams, config, auth, alertService,rms,common){
//    common.checkLogin();

    var vm = $scope;
    var send_id = $routeParams.id;
    vm.course_id = $routeParams.course_id;

    //发送类别 1课件 2作业 3测验
    vm.myresource_sendIndex = rms.get('myresource_sendIndex') || 1;

    vm.alertService = alertService.create();
    vm.syllabuses = [];

    var loadClassList = function () {
        $http.get(config.apiUrl + "syllabuses?token=" + auth.token()).then(
            function (response) {
                console.log(response.data);
                vm.syllabuses = response.data.data;
//                rms.save('syllabuses', vm.syllabuses);
            }
        );
    };

    loadClassList();

    vm.selectCourse = function(course){
        if( typeof course.checked !== 'boolean' ) course.checked = false;
        course.checked = !course.checked;
    }

    vm.sendToCourses = function(){
        var course_ids = [];

        for(var i in vm.syllabuses) {
            for (var j in vm.syllabuses[i].courses) {
                if (vm.syllabuses[i].courses[j].checked) {
                    course_ids.push(vm.syllabuses[i].courses[j].id);
                }
            }
        }

        if(course_ids.length <= 0){
            vm.alertService.showMessage('提醒', '请先选择班级');
            return;
        }
        
        $http.post(config.apiUrl + "resources/send", {
            token: auth.token(), course_ids: course_ids, send_id: send_id,send_type:vm.myresource_sendIndex
        }).then(function(response){
            console.log(response.data);
            if(response.data.status == 0){
                var tip = "";
                if (vm.myresource_sendIndex == 1){
                    tip = "课件已发送到目标班级。";
                    vm.alertService.showMessage('发送成功', tip, function () {
                        rms.save('page',0);
                        rms.save("resources",[]);
                        rms.save("has_more",false);
                        window.history.back();
                    });
                }
                else if(vm.myresource_sendIndex == 2){
                    tip = "题目已发送到目标班级的作业列表，但需要您访问Trustie网站设置发布和截止时间，以激活相应作业，谢谢。";
                    vm.alertService.showMessage('发送成功', tip, function () {
                        window.history.back();
                    });
                }

            } else {
                vm.alertService.showMessage('发送出错', response.data.message);
            }
        })
    }

}]);
