var App = angular.module('App', ['ngSanitize', 'ngAnimate','FrameApp', 'PointApp']);

var PointApp = angular.module('PointApp', ['ngSanitize', 'HaiTouFilter']);
var FrameApp = angular.module('FrameApp', ['ngSanitize', 'HaiTouFilter']);

PointApp.controller('PointInfo', ['$scope', function ($scope) {
    var expToLevel = function (exp) {
        return Math.floor((Math.sqrt(2025 + 20 * exp) - 35) / 10);
    };
    var levelToExp = function (level) {
        return 5 * level * level + 35 * level - 40;
    };
    var info = JSON.parse($('#myInfo').html());
    // 貌似没用
    if (typeof(info.resume) == 'undefined') {
        info.resume = 0;
    }

    $scope.level = expToLevel(info.exp);
    $scope.exp = info.exp - levelToExp($scope.level);
    $scope.thisLevelExp = levelToExp($scope.level + 1) - levelToExp($scope.level);
    $scope.expPercentage = Math.floor(100 * $scope.exp / $scope.thisLevelExp);

    $scope.redTint = Math.floor($scope.level / 16);
    $scope.yellowTint = Math.floor($scope.level % 16 / 4);
    $scope.greenTint = Math.floor($scope.level % 4);

}]);

FrameApp.controller('UserManager', ['$scope', '$http', '$location', function ($scope, $http, $location) {
    $scope.email = '';
    $scope.code = '';
    $scope.password = '';
    $scope.rememberPassword = 1;
    $scope.errorMessage = '';
    $scope.refreshVerifyCode = function () {
        var element = $('.verify-code');
        var baseurl = element.data('baseurl');
        var rand = '?' + Math.random().toString().substr(2);
        element.attr('src', baseurl + rand);

    };
    $scope.switchView = function (view) {
        $scope.modalView = view;
        if (view == 'register' || view == 'forgetPassword')
            if (!$('.verify-code').attr('src'))
                $scope.refreshVerifyCode();
    };
    var path = $location.path().slice(1);
    if (['register', 'login', 'forgetPassword'].indexOf(path) != -1) {
        $('#userModal').modal();
        $scope.switchView(path);
    }
    var showLoginModal = window.location.href.search(/\?backurl=/);
    if (showLoginModal != -1) {
        $('#userModal').modal();
        $scope.switchView('login');
    }
    $scope.toggleRememberPassword = function () {
        $scope.rememberPassword = 1 - $scope.rememberPassword;
    };
    $scope.register = function () {  // 注册，先检查注册信息是否正确

        var param = {};

        if($scope.email == "" || $scope.email == undefined){
            $scope.errorMessage = "* 请将信息填写完整";
        }else if($scope.email == parseInt($scope.email)){  //输入的都是数字
            var tel = $scope.email;
            var reg = /^1[3456789]\d{9}$/;

            if(reg.test(tel)){ // 如果确认为手机号
                param.phone = $scope.email;
                goPreRegister();
            }else{
                $scope.errorMessage = "* 请输入正确的手机号码";
            }
        }else{
            var email = $scope.email;
            var reg =  /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

            if(reg.test(email)){ // 如果确认为邮箱地址
                param.email = $scope.email;
                goPreRegister();
            }else{
                $scope.errorMessage = "* 邮箱地址有误";
            }
        }

        function goPreRegister(){ // 注册
            if($scope.code.length == 4){
                $scope.loading = true;
                $scope.errorMessage = '';
                param.captcha = $scope.code;
                var ajaxUrl = '/system/pre-register';

                $http({method: "get", url: ajaxUrl, params: param, withCredentials: true})
                    .success(function (data) {
                        $scope.loading = false;
                        if (data.status == 'error') {
                            $scope.errorMessage = "* " + data.message;
                            $scope.refreshVerifyCode();
                        }
                        else {
                            $scope.errorMessage = '';

                            if(param.email){
                                $scope.modalView = 'registerNotice';
                                $scope.openMailUrl = data.url;
                                $scope.emailIsUnable = $scope.checkIsUnable();
                            }else{
                                $scope.phoneCodeMessage = '';
                                $scope.modalView = 'sendPhoneCode';
                                setPhoneCodeSuccess();
                            }
                        }
                    })
                    .error(function (data) {
                        $scope.loading = false;
                        $scope.errorMessage = "* 服务器错误";
                        console.log(data);
                    });
            }else{
                $scope.errorMessage = "* 验证码有误";
            }
        }

    };
    function setPhoneCodeSuccess(){ // 发送验证码后修改发送按钮样式
        $('.phoneGetCodeBtn').html('60s').attr({'disabled':"true"});
        var setPhoneCodeTime = setInterval(function(){
            if($('.phoneGetCodeBtn').html() != "0s"){
                $('.phoneGetCodeBtn').html(parseInt($('.phoneGetCodeBtn').html()) - 1 + 's');
            }else{
                clearInterval(setPhoneCodeTime);
                $('.phoneGetCodeBtn').html('重新获取').removeAttr('disabled');
                $scope.refreshVerifyCode();
                $scope.code = "";
            }
        },1000);
    }
    $scope.checkPhoneCode = function(){  // 检查验证码是否正确
        var param = {};
        param.phone = $scope.email;
        param.usage = "register";
        param.rc = $scope.phoneCode;
        $scope.loading = true;
        var ajaxUrl = '/system/phone-validation';

        $http({method: "get", url: ajaxUrl, params: param, withCredentials: true})
            .success(function (data) {
                $scope.loading = false;
                if (data.status == 'error') {
                    $scope.phoneCodeMessage = "* " + data.message;
                }
                else {
                    $scope.phoneCodeMessage = '';
                    window.location = '//home.haitou.cc/member?phone=' + param.phone + '&rc=' + param.rc;
                }
            })
            .error(function (data) {
                $scope.loading = false;
                $scope.phoneCodeMessage = "* 服务器错误";
                console.log(data);
            });
    }
    $scope.goBindPage = function(){ //跳转到绑定页面
        console.log(1);
        window.location = '//home.haitou.cc/account';
    }
    $scope.notGoBindPage = function(){ //跳过不去绑定
        console.log(0);
        window.location.reload();
    }
    $scope.login = function () { // 登录
        $scope.$broadcast("autofill:update");

        if ($scope.userLogin.$valid) {
            var param = {};
            var data = {};
            //param.act = 'login';
            if ($scope.email.search('@') != -1) {
                // 如果是邮箱
                param.email = $scope.email;
            } else if($scope.email == parseInt($scope.email) && $scope.email.length == 11){
                // 如果是手机
                param.phone = $scope.email;
            } else {
                // 否则是用户名
                param.username = $scope.email;
            }
            param.rememberPassword = $scope.rememberPassword;
            data.md5_password = hex_md5($scope.password);
            $scope.loading = true;

            var ajaxUrl = '/system/login';
            $scope.errorMessage = '';
            $http({method: "post", url: ajaxUrl, params: param, data: data, withCredentials: true})
                .success(function (data) {
                    if (data.status == 'error') {
                        $scope.loading = false;
                        $scope.errorMessage = "* " + data.message;
                    } else {
                        $.cookie("haitou_uid", data.user_id, {domain: ".haitou.cc", path: "/", expires: 30});
                        $.cookie("haitou_auth", data.auth, {domain: ".haitou.cc", path: "/", expires: 30});
                        $scope.errorMessage = '';

                        // localStorage.setItem('haitou_phone', data.phone);
                        // localStorage.setItem('haitou_isPhoneBind', data.isPhoneBind);
                        // localStorage.setItem('haitou_email', data.email);
                        // localStorage.setItem('haitou_isEmailBind', data.isEmailBind);
                        $.cookie("haitou_phone", data.phone, {domain: ".haitou.cc", path: "/", expires: 30});
                        $.cookie("haitou_isPhoneBind", data.isPhoneBind, {domain: ".haitou.cc", path: "/", expires: 30});
                        $.cookie("haitou_email", data.email, {domain: ".haitou.cc", path: "/", expires: 30});
                        $.cookie("haitou_isEmailBind", data.isEmailBind, {domain: ".haitou.cc", path: "/", expires: 30});


                        var checkUrl = false;
                        if(window.location.search){
                            var query = window.location.search.split("?")[1].split("&");
                            for(var i = 0 ; i < query.length ; i ++){
                                if(query[i].split("=")[0] == "url"){
                                    checkUrl = query[i].split("=")[1];
                                }
                            }
                        }
                        // TODO 登录询问是否绑定
                        if(data.isPhoneBind == false || data.isPhoneBind == "false"){
                            $scope.modalView = 'askBind';
                            $scope.bindWhat = "手机";
                        }else if(data.isEmailBind == false || data.isEmailBind == "false"){
                            $scope.modalView = 'askBind';
                            $scope.bindWhat = "邮箱";
                        }else{
                            if (data.returnUrl) {
                                window.location = data.returnUrl;
                            } else if(checkUrl){
                                window.location = checkUrl;
                            } else {
                                window.location.reload();
                            }
                        }
                    }
                })
                .error(function (data) {
                    $scope.loading = false;
                    $scope.errorMessage = "* 服务器错误";
                    console.log(data);
                });
        } else {
            if ($scope.userLogin.email.$error.required) {
                $scope.errorMessage = "* 邮箱不能为空";
            } else if ($scope.userLogin.password.$error.required) {
                $scope.errorMessage = "* 密码不能为空";
            } else {
                $scope.errorMessage = "qitacuowu ";
            }
            $('input.ng-invalid').first().focus();
        }

    };
    $scope.forgetPassword = function () { // 忘记密码，先验证找回密码凭证是否正确


        var param = {};

        if($scope.email == "" || $scope.email == undefined){
            $scope.errorMessage = "* 请将信息填写完整";
        }else if($scope.email == parseInt($scope.email)){  //输入的都是数字
            var tel = $scope.email;
            var reg = /^1[3456789]\d{9}$/;

            if(reg.test(tel)){ // 如果确认为手机号
                param.phone = $scope.email;
                goFindPas();
            }else{
                $scope.errorMessage = "* 请输入正确的手机号码";
            }
        }else{
            var email = $scope.email;
            var reg =  /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

            if(reg.test(email)){ // 如果确认为邮箱地址
                param.email = $scope.email;
                goFindPas();
            }else{
                $scope.errorMessage = "* 邮箱地址有误";
            }
        }

        function goFindPas(){ // 获取验证码
            if($scope.code.length == 4){
                $scope.loading = true;
                $scope.errorMessage = '';
                param.captcha = $scope.code;
                var ajaxUrl = '/system/find-pass';

                $http({method: "get", url: ajaxUrl, params: param, withCredentials: true})
                    .success(function (data) {
                        $scope.loading = false;
                        if (data.status == 'error') {
                            $scope.errorMessage = "* " + data.message;
                            $scope.refreshVerifyCode();
                        }
                        else {
                            $scope.errorMessage = '';

                            if(param.email){
                                $scope.errorMessage = '';
                                $scope.modalView = 'forgetPasswordNotice';
                                $scope.openMailUrl = data.url;
                            }else{
                                $scope.phoneCodeMessage = '';
                                $scope.modalView = 'forgetPasswordPhoneNotice';
                                setPhoneFindCodeSuccess();
                            }
                        }
                    })
                    .error(function (data) {
                        $scope.loading = false;
                        $scope.errorMessage = "* 服务器错误";
                        console.log(data);
                    });
            }else{
                $scope.errorMessage = "* 验证码有误";
            }
        }
        function setPhoneFindCodeSuccess(){ // 发送验证码后修改发送按钮样式
            $scope.phoneCodeFindMessage = '';
            $('.phoneGetCodeBtn').html('60s').attr({'disabled':"true"});
            var setPhoneCodeTime = setInterval(function(){
                if($('.phoneGetCodeBtn').html() != "0s"){
                    $('.phoneGetCodeBtn').html(parseInt($('.phoneGetCodeBtn').html()) - 1 + 's');
                }else{
                    clearInterval(setPhoneCodeTime);
                    $('.phoneGetCodeBtn').html('重新获取').removeAttr('disabled');
                    $scope.refreshVerifyCode();
                    $scope.code = "";
                }
            },1000);
        }
        $scope.checkPhoneFindCode = function(){ // 检查验证码是否正确
            var param = {};
            var datas = {};
            param.phone = $scope.email;
            param.usage = "find-password";
            param.rc = $scope.phoneCode;
            $scope.loading = true;
            var ajaxUrl = '/system/phone-validation';

            $http({method: "get", url: ajaxUrl, params: param, withCredentials: true})
                .success(function (data) {
                    $scope.loading = false;
                    if (data.status == 'error') {
                        $scope.phoneCodeFindMessage = "* " + data.message;
                    }
                    else {
                        $scope.phoneCodeFindMessage = '';
                        window.location = '//home.haitou.cc/find?phone=' + param.phone + '&rc=' + param.rc;
                    }
                })
                .error(function (data) {
                    $scope.loading = false;
                    $scope.phoneCodeFindMessage = "* 服务器错误";
                    console.log(data);
                });
        }

    };
    $scope.logout = function () { // 登出
        $.removeCookie("haitou_user", {domain: ".haitou.cc", path: "/"});
        $.removeCookie("haitou_uid", {domain: ".haitou.cc", path: "/"});
        $.removeCookie("haitou_session", {domain: ".haitou.cc", path: "/"});
        $.removeCookie("haitou_phone", {domain: ".haitou.cc", path: "/"});
        $.removeCookie("haitou_email", {domain: ".haitou.cc", path: "/"});
        $.removeCookie("haitou_isEmailBind", {domain: ".haitou.cc", path: "/"});
        $.removeCookie("haitou_isPhoneBind", {domain: ".haitou.cc", path: "/"});
        //移除haitou_auth -- MR
        $.removeCookie("haitou_auth", {domain: ".haitou.cc", path: "/"});
        window.location.reload();
    };

    //验证是否是163或126
    $scope.checkIsUnable = function () {
        var arr = $scope.email.split('@');
        var mailType = (arr[1].split('.'))[0];
        var unableType = ['163','126'];
        return unableType.indexOf(mailType) != -1
    }

    $scope.hotKeys = ['机械', '平安', '顺丰', '京东方', '银行', '创维', 'vivo', '材料', '土木', 'TCL', '恒大', '中建', '计算机', '比亚迪', '物流', '美的', '软件', '华为', '会计', '富士康', '顺丰', '银行', '材料', '土木', '建筑', '恒大',
        "机械", "汽车", "银行", "实习", "材料", "土木", "建筑", "恒大", "中建", "京东方", "计算机", "比亚迪", "物流", "美的", "软件", "华为", "会计", "富士康", "顺丰", "化学", "地产", "化工", "微电子", "设计", "海信", "中兴", "格力", "京东", "安全", "东风", "游戏", "TCL", "华润", "中国移动", "电气", "教师", "生物", "中铁", "深信服", "南车", "房地产", "杰瑞", "电力", "电子", "招商银行", "九州"
    ]
}]);

FrameApp.controller('NavAlertList', ['$scope', '$http', function ($scope, $http) {
    $scope.bufferSize = 16;
    $scope.pageSize = 8;
    $scope.requestSize = 24;
    $scope.alertNum = parseInt($('#alertNum').html());
    $scope.alertArr = JSON.parse($('#alertArr').html());
    $scope.alertEmpty = $scope.alertArr.length >= $scope.alertNum;
    $scope.viewArr = [];
    $scope.params = {};
    $scope.markRead = function (index) {
        $scope.alertNum -= 1;
        var id = $scope.alertArr[index].id;
        $scope.alertArr.splice(index, 1);
        $scope.communicate(id);
    };
    $scope.markAllRead = function () {
        if ($scope.alertNum > $scope.pageSize)
            $scope.alertNum -= $scope.pageSize;
        else
            $scope.alertNum = 0;
        var ids = [];
        var loop = Math.min($scope.pageSize, $scope.alertArr.length);
        for (var i = 0; i < loop; i++)
            ids.push($scope.alertArr[i].id);
        $scope.alertArr.splice(0, $scope.pageSize);
        $scope.communicate(ids);
    };
    $scope.communicate = function (viewIds) {
        $scope.viewAlerts(viewIds);
        $scope.params.view = $scope.viewArr.toString();
        if ($scope.alertArr.length < $scope.bufferSize && !$scope.alertEmpty) {
            $scope.getAlerts();
        }

        var ajaxUrl = '/system/get-messages';
        //$scope.params.act = 'alert';

        var info = JSON.parse($('#myInfo').html());
        $scope.params.uid = info.uid;
        $http({method: 'GET', url: ajaxUrl, params: $scope.params, withCredentials: true})
            .success(function (data) {
                console.log("请求数据", data);
                
                if (data.error) {
                    console.log(data.error);
                    return;
                }
                // if (typeof(data.data) != 'undefined')
                //     $scope.alertArr = $scope.alertArr.concat(data.data.alert);
                // if (typeof(data.alertNum) != 'undefined')
                //	$scope.alertNum = data.alertNum;
                if (data.length < $scope.requestSize)
                    $scope.alertEmpty = true;
                $scope.viewArr = [];
                $scope.params = {};
            });
    };
    $scope.viewAlerts = function (id) {
        if (typeof(id) == 'object')
            $scope.viewArr = $scope.viewArr.concat(id);
        else if (typeof(id) == 'string' || typeof(id) == 'number')
            $scope.viewArr.push(id);
    };
    $scope.getAlerts = function () {
        var lastAlert = $scope.alertArr[$scope.alertArr.length - 1];
        var lastAlertTime = 0;
        if (typeof(lastAlert.time) == 'string')
            lastAlertTime = Math.round(Date.parse(lastAlert.time) / 1000);
        else if (typeof(lastAlert.time) == 'number')
            lastAlertTime = lastAlert.time;
        $scope.params.beginId = lastAlert.id;
        $scope.params.beginTime = lastAlertTime;
        $scope.params.limit = $scope.requestSize;
    };
}]);

FrameApp.filter('navAlertIcoFilter', function () {
    return function (index) {
        //系统消息1 职位邀请2 简历信息3 公司留言4 面经回复5 站内信6 测评邀请7
        var iconArr = {0: 'fa-dot-circle-o', 1: 'fa-coffee', 2: 'fa-suitcase', 3: 'fa-file-text', 4: 'fa-comment', 5: 'fa-comments', 6: 'fa-envelope', 7: 'fa-pencil'};
        return iconArr[index];
    };
});

FrameApp.filter('navAlertInfoFilter', ['$sce', function ($sce) {
    return function (info) {
        if(info!=undefined){
            return $sce.trustAsHtml(info.replace(/<s>/g, " <span class='color'>").replace(/<\/s>/g, " </span>"));
        } else {return info;}
    };
}]);


var HaiTouFilter = angular.module('HaiTouFilter', []);
HaiTouFilter.filter('readableTimeFilter', function () {
    return function (timestamp) {
        var before = 0;
        if (typeof(timestamp) == 'string')
            before = Math.round(new Date().getTime() / 1000 - Date.parse(timestamp) / 1000);
        else if (typeof(timestamp) == 'number')
            before = Math.round(new Date().getTime() / 1000 - timestamp);
        var year = Math.floor(before / (12 * 30 * 24 * 60 * 60));
        var month = Math.floor(before % (12 * 30 * 24 * 60 * 60) / (30 * 24 * 60 * 60));
        var day = Math.floor(before % (30 * 24 * 60 * 60) / (24 * 60 * 60));
        var hour = Math.floor(before % (24 * 60 * 60) / ( 60 * 60 ));
        var minu = Math.floor(before % (60 * 60 ) / 60);
        var sec = Math.floor(before % 60);
        var rtnStr;
        if (year)       rtnStr = year + '年前';
        else if (month) rtnStr = month + '月前';
        else if (day)   rtnStr = day + '天前';
        else if (hour)  rtnStr = hour + '小时前';
        else if (minu)  rtnStr = minu + '分钟前';
        else if (sec)   rtnStr = sec + '秒前';
        else rtnStr = '刚刚';
        //console.log(year,month,day,hour,minu,sec,rtnStr);
        return rtnStr;
    };
});

HaiTouFilter.filter('typeListFilter', function () {
    return function (list, typeid) {
        if (typeid === '0' || typeid === '' || typeid === 0)
            return list;
        var listFiler = [];
        list.forEach(function (i) {
            if (i.kind == typeid)
                listFiler.push(i);
        });
        return listFiler;
    };
});

HaiTouFilter.filter('paginationFilter', function () {
    return function (list, page, pageSize) {
        var begin = Math.min(0, (page) * pageSize);
        var end = begin + pageSize;
        return list.slice(begin, end);
    };
});

HaiTouFilter.filter('slice', function () {
    return function (list, begin, end) {
        return list.slice(begin, end);
    };
});

HaiTouFilter.filter('range', function () {
    return function (input, total) {
        total = parseInt(total);
        for (var i = 0; i < total; i++)
            input.push(i);
        return input;
    };
});

FrameApp.directive("btnLoading", function () {
    return function (scope, element, attrs) {
        scope.$watch(function () {
            return scope.$eval(attrs.btnLoading);
        }, function (loading) {
            if (loading) return element.button("loading");
            element.button("reset");
        });
    };
});

FrameApp.directive("autofill", function () {
    return {
        require: "ngModel",
        link: function (scope, element, attrs, ngModel) {
            scope.$on("autofill:update", function () {
                ngModel.$setViewValue(element.val());
            });
        }
    }
});