var app = angular.module('wechat', ['ngRoute','ngCookies']);
var apiUrl = '/api/v1/';
var debug = false; //调试标志,如果在本地请置为true

if(debug===true){
    //apiUrl = 'http://localhost:3000/api/v1/';
    apiUrl = 'https://www.trustie.net/api/v1/';
}

app.factory('auth', function($http,$routeParams, $cookies, $q){
    var _openid = '';

    if(debug===true){
        _openid = "1";
    }

    var getOpenId = function() {
        var deferred = $q.defer();
        if (typeof _openid !== 'undefined' && _openid.length > 0){
            deferred.resolve(_openid);
        } else {
            var code = $routeParams.code;
            $http({
                url: '/wechat/get_open_id',
                data: {code: code},
                method: 'POST'
            }).then(function successCallback(response) {
                _openid = response.data.openid;
                if(typeof _openid !== 'undefined' && _openid.length>0){
                    if(debug !== true){ //如果是生产环境,就存到cookies中
                        $cookies.put("openid", _openid);
                    }
                } else {
                    if(debug!==true){//考虑从cookies中取出
                        _openid = $cookies.get('openid');
                    }
                }
                deferred.resolve(_openid);
            }, function errorCallback(response) {
                deferred.reject(response);
            });
        }
        return deferred.promise;
    };
    var openid = function(){
        return _openid;
    };
    return {getOpenId: getOpenId, openid: openid};
});


app.factory('rms', function(){
    var _saveStorage = {};
    var save = function(key, value){
        _saveStorage[key] = value;
    };

    var get = function(key){
        return _saveStorage[key];
    };

    return {save: save, get: get};
});

app.controller('ActivityController',function($scope, $http, auth, rms, common){
    $scope.replaceUrl = function(url){
        return url;
    };

    console.log("ActivityController load");
    $scope.activities = rms.get("activities") || [];
    $scope.page = 0;

    var loadActData = function(page){
        $scope.page = page;
        $http({
            method: 'POST',
            url: apiUrl+ "activities",
            data: {openid: auth.openid(), page: page}
        }).then(function successCallback(response) {
            $scope.current_page = 0;
            console.log($scope.current_page);
            console.log(response.data.page);
            if($scope.current_page < response.data.page) {
                $scope.activities = $scope.activities.concat(response.data.data);
            } else {
                $scope.activities = response.data.data;
            }
            $scope.current_page = response.data.page;
            $scope.all_count = response.data.all_count;
            $scope.count = response.data.count;
            console.log(response.data);
            rms.save('activities', $scope.activities);
        }, function errorCallback(response) {
        });
    };
    auth.getOpenId().then(
        function successCallback(response){
            loadActData($scope.page);
        }, function errorCallback(response) {
            alert("获取openid出错:"+response);
        }
    );


    $scope.loadActData = loadActData;

    $scope.addPraise = function(act){
        common.addCommonPraise(act);
    };

    $scope.decreasePraise = function(act){
        common.decreaseCommonPraise(act);
    };

});

app.factory('common', function($http, auth, $routeParams){
    var addCommonReply = function(id, type, data, cb){

        if(!data.comment || data.comment.length<=0){
            return;
        }

        var userInfo = {
            type: type,
            content: data.comment,
            openid: auth.openid()
        };

        //回复按钮禁用
        data.disabled = true;

        $http({
            method: 'POST',
            url: apiUrl+ "new_comment/"+id,
            data: userInfo
        }).then(function successCallback(response) {
            //alert("提交成功");
            //数据提交完成,回复按钮启用
            data.disabled = false;
            if(typeof cb === 'function'){
                cb();
            }
        }, function errorCallback(response) {
        });
    };

    var loadCommonData = function(id, type){
        return $http({
            method: 'GET',
            url: apiUrl+ type + "/" + id+"?openid="+auth.openid()
        })
    };

    var addCommonPraise = function(act){
        act.praise_count += 1;
        act.has_praise = true;

        $http({
            method: 'POST',
            url: apiUrl + "praise/" + act.act_id,
            data:{openid:auth.openid(),type:act.act_type}
        }).then(function successCallback(response) {
            console.log(response.data);
        }, function errorCallback(response) {
        });

    };

    var decreaseCommonPraise = function(act){
        act.praise_count -= 1;
        act.has_praise = false;

        $http({
            method: 'POST',
            url: apiUrl + "praise/" + act.act_id,
            data:{openid:auth.openid(),type:act.act_type}
        }).then(function successCallback(response) {
            console.log(response.data);
        }, function errorCallback(response) {
        });
    };

    return {addCommonReply: addCommonReply, loadCommonData: loadCommonData, addCommonPraise: addCommonPraise, decreaseCommonPraise: decreaseCommonPraise};
});

app.controller('IssueController', function($scope, $http, $routeParams, auth, common){
    $scope.formData = {comment: ''};

    var loadData = function(id){
        common.loadCommonData(id, 'issues').then(function successCallback(response) {
            console.log(response.data);
            $scope.issue = response.data.data;
        }, function errorCallback(response) {
        });
    };

    auth.getOpenId().then(
        function successCallback(response){
            loadData($routeParams.id);
        }, function errorCallback(response) {
            alert("获取openid出错:"+response);
        }
    );

    $scope.addIssueReply = function(data){
        console.log(data.comment);
        common.addCommonReply($routeParams.id, 'Issue', data, function(){
            $scope.formData = {comment: ''};
            loadData($routeParams.id);
        });

    };

    $scope.addPraise = function(act){
        common.addCommonPraise(act);
    };

    $scope.decreasePraise = function(act){
        common.decreaseCommonPraise(act);
    };
});

app.controller('HomeworkController', function($scope, $http, $routeParams, auth, common){
    $scope.formData = {comment: ''};

    var loadData = function(id){
        common.loadCommonData(id, 'whomeworks').then(function successCallback(response) {
            console.log(response.data);
            $scope.homework = response.data.data;
        }, function errorCallback(response) {
        });
    };

    auth.getOpenId().then(
        function successCallback(response){
            loadData($routeParams.id);
        }, function errorCallback(response) {
            alert("获取openid出错:"+response);
        }
    );

    $scope.addHomeworkReply = function(data){
        console.log(data.comment);
        common.addCommonReply($routeParams.id, 'HomeworkCommon', data, function(){
            $scope.formData = {comment: ''};
            loadData($routeParams.id);
        });
    };

    $scope.addPraise = function(act){
        common.addCommonPraise(act);
    };

    $scope.decreasePraise = function(act){
        common.decreaseCommonPraise(act);
    };
});

app.controller('CourseNoticeController', function($scope, $http, $routeParams, auth, common){
    $scope.formData = {comment: ''};

    var loadData = function(id){
        common.loadCommonData(id, 'newss').then(function successCallback(response) {
            console.log(response.data);
            $scope.news = response.data.data;
        }, function errorCallback(response) {
        });
    };

    auth.getOpenId().then(
        function successCallback(response){
            loadData($routeParams.id);
        }, function errorCallback(response) {
            alert("获取openid出错:"+response);
        }
    );

    $scope.addNoticeReply = function(data){
        console.log(data.comment);
        common.addCommonReply($routeParams.id, 'News', data, function(){
            $scope.formData = {comment: ''};
            loadData($routeParams.id);
        });
    };

    $scope.addPraise = function(act){
        common.addCommonPraise(act);
    };

    $scope.decreasePraise = function(act){
        common.decreaseCommonPraise(act);
    };
});

app.controller('DiscussionController', function($scope, $http, $routeParams, auth, common){
    $scope.formData = {comment: ''};

    var loadData = function(id){
        common.loadCommonData(id, 'messages').then(function successCallback(response) {
            console.log(response.data);
            $scope.discussion = response.data.data;
        }, function errorCallback(response) {
        });
    };

    auth.getOpenId().then(
        function successCallback(response){
            loadData($routeParams.id);
        }, function errorCallback(response) {
            alert("获取openid出错:"+response);
        }
    );

    $scope.addDiscussionReply = function(data){
        console.log(data.comment);
        common.addCommonReply($routeParams.id, 'Message', data, function(){
            $scope.formData = {comment: ''};
            loadData($routeParams.id);
        });
    };

    $scope.addPraise = function(act){
        common.addCommonPraise(act);
    };

    $scope.decreasePraise = function(act){
        common.decreaseCommonPraise(act);
    };
});

app.controller('JournalsController', function($scope, $http, $routeParams, auth, common){
    $scope.formData = {comment: ''};

    var loadData = function(id){
        common.loadCommonData(id, 'journal_for_messages').then(function successCallback(response) {
            console.log(response.data);
            $scope.message = response.data.data;
        }, function errorCallback(response) {
        });
    };

    auth.getOpenId().then(
        function successCallback(response){
            loadData($routeParams.id);
        }, function errorCallback(response) {
            alert("获取openid出错:"+response);
        }
    );

    $scope.addJournalReply = function(data){
        console.log(data.comment);
        common.addCommonReply($routeParams.id, 'JournalsForMessage', data, function(){
            $scope.formData = {comment: ''};
            loadData($routeParams.id);
        });
    };

    $scope.addPraise = function(act){
        console.log(act);
        common.addCommonPraise(act);
    };

    $scope.decreasePraise = function(act){
        console.log(act);
        common.decreaseCommonPraise(act);
    };
});

app.controller('BlogController', function($scope, $http, $routeParams, auth, common){
    $scope.formData = {comment: ''};

    var loadData = function(id){
        common.loadCommonData(id, 'blog_comments').then(function successCallback(response) {
            console.log(response.data);
            $scope.blog = response.data.data;
        }, function errorCallback(response) {
        });
    };

    auth.getOpenId().then(
        function successCallback(response){
            loadData($routeParams.id);
        }, function errorCallback(response) {
            alert("获取openid出错:"+response);
        }
    );

    $scope.addBlogReply = function(data){
        console.log(data.comment);
        common.addCommonReply($routeParams.id, 'BlogComment', data, function(){
            $scope.formData = {comment: ''};
            loadData($routeParams.id);
        });
    };

    $scope.addPraise = function(act){
        console.log(act);
        common.addCommonPraise(act);
    };

    $scope.decreasePraise = function(act){
        console.log(act);
        common.decreaseCommonPraise(act);
    };
});

app.filter('safeHtml', function ($sce) {
    return function (input) {
        return $sce.trustAsHtml(input);
    }
});

//app.directive('textAutoHeight', function($timeout){
//    return {
//        restrict: 'A',
//        scope: {},
//        link: function(scope, element, attr){
//            scope.text = '点击展开';
//            $timeout(function(){
//                var e = element.parent().children().eq(5);
//                var height = e[0].scrollHeight;
//                if(height>90){
//                    element.css('display', 'block');
//                    element.on('click', function(){
//                        if(element.text() == "点击展开"){
//                            e.css("height", height+'px');
//                            element.text("点击隐藏");
//                        } else {
//                            e.css("height", '90px');
//                            element.text("点击展开");
//                        }
//
//                    });
//                }
//            }, false);
//
//        }
//    }
//});

app.directive('inputAuto',function(){
    return{
        restrict: 'A',
        scope: {},
        link: function(scope, element){
                var copyContainer = element.parent().children().eq(0);
                var sendButton = element.parent().next();
                element.on('input',function(){
                    console.log(sendButton);
                    copyContainer.html(element[0].value);
                    var textHeight = copyContainer[0].scrollHeight;
                    element.css('height', textHeight + 'px');
                });
                sendButton.on('click',function(){
                    element.css('height','28px');
                });
            }
    }
});

app.directive('loadingSpinner', function ($http) {
    return {
        restrict: 'A',
        replace: true,
        template: '<div class="loading-bg"><div class="loading-box"><img src="/images/loading.gif" alt=""/><span>加载中...</span></div></div>',
        link: function (scope, element, attrs) {

            scope.$watch('activeCalls', function (newVal, oldVal) {
                if (newVal == 0) {
                    $(element).hide();
                }
                else {
                    $(element).show();
                }
            });
        }
    };
});

app.config(['$routeProvider',"$httpProvider",function ($routeProvider, $httpProvider) {
    $routeProvider
        .when('/activities', {
            templateUrl: 'activities.html',
            controller: 'ActivityController'
        })
        .when('/issues/:id', {
            templateUrl: 'issue_detail.html',
            controller: 'IssueController'
        })
        .when('/project_discussion/:id', {
            templateUrl: 'project_discussion.html',
            controller: 'DiscussionController'
        })
        .when('/homework/:id', {
            templateUrl: 'homework_detail.html',
            controller: 'HomeworkController'
        })
        .when('/course_notice/:id', {
            templateUrl: 'course_notice.html',
            controller: 'CourseNoticeController'
        })
        .when('/course_discussion/:id', {
            templateUrl: 'course_discussion.html',
            controller: 'DiscussionController'
        })
        .when('/journal_for_message/:id', {
            templateUrl: 'jour_message_detail.html',
            controller: 'JournalsController'
        })
        .when('/blog_comment/:id', {
            templateUrl: 'blog_detail.html',
            controller: 'BlogController'
        })
        .otherwise({
            redirectTo: '/activities'
        });

        //监听异步请求,实现加载中显隐标记
        $httpProvider.interceptors.push(function ($q, $rootScope) {
            if ($rootScope.activeCalls == undefined) {
                $rootScope.activeCalls = 0;
            }

            return {
                request: function (config) {
                    $rootScope.activeCalls += 1;
                    return config;
                },
                requestError: function (rejection) {
                    $rootScope.activeCalls -= 1;
                    return rejection;
                },
                response: function (response) {
                    $rootScope.activeCalls -= 1;
                    return response;
                },
                responseError: function (rejection) {
                    $rootScope.activeCalls -= 1;
                    return rejection;
                }
            };
        });
}]);
