/// <reference path="../../../Scripts/underscore.js" />
/// <reference path="../../common/utils/enums.js" />
/// <reference path="../nav-bar-util.js" />

// AppNavBarController controller for the navigation bar of the application. This controller is responsible for 
// manage the different types of the tabs and corresponding menus.
frameworkModule.controller('AppModalController', ['$scope', '$log', '$rootScope', '$translate', '$timeout', 'commonWebService', 'loginContext', 'dashboardService', '$interval',
    function ($scope, $log, $rootScope, $translate, $timeout, commonWebService, loginContext, dashboardService, $interval) {
        'use strict';
        $log.debug('AppModalController.ctor()...');

        $scope.init = function () {
            $scope.verifyIsSame = true;
            $scope.oldNewIsSame = false;
            $scope.isSubmited = false;
            $scope.operationStatus = 0;
            $scope.operationFailInfo = "";

            $scope.oldpassword = '';
            $scope.newpassword = '';
            $scope.newpassword_verify = '';

            $scope.disableUpdate = false;
        };

        $scope.init();

        $scope.changePassword = function () {
            var num = 0;
            var number = 0;
            var letter = 0;
            var bigLetter = 0;
            var chars = 0;

            $scope.isSubmited = true;

            if ($scope.form.$invalid) {
                $scope.operationStatus = -1;
                $scope.operationFailInfo = $translate.instant('FollowTips');

                return;
            }

            if ($scope.oldpassword === '' || $scope.newpassword === '' || $scope.newpassword_verify === '') {
                $scope.operationStatus = -1;
                $scope.operationFailInfo = $translate.instant('AnyPasswordCanNotEmpty');
                return;
            }

            if ($scope.newpassword === $scope.oldpassword) {
                $scope.operationStatus = -1;
                $scope.operationFailInfo = $translate.instant('PasswordNotChanged');

                return;
            }

            if ($scope.newpassword !== $scope.newpassword_verify) {
                $scope.operationStatus = -1;
                $scope.operationFailInfo = $translate.instant('ConfirmTheSameInfo');

                return;
            }

            if ($scope.newpassword !== '') {
                if ($scope.newpassword.length < 6) {
                    $scope.operationStatus = -1;
                    $scope.operationFailInfo = '密码长度必须大于等于6位!';
                    return;
                }
                var reg = new RegExp('^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,20}');
                if (!reg.test($scope.newpassword)) {
                    $scope.operationStatus = -1;
                    $scope.operationFailInfo = '密码格式不正确,必须为数字和字母组合!';
                    return;
                }
            }

            $scope.disableUpdate = true;
            var passwordList = { oldPassword: $scope.oldpassword, newPassword: $scope.newpassword };
            commonWebService.changePassword(passwordList).success(function (returnData) {
                if (returnData.result) {
                    $scope.operationStatus = 1;
                    $timeout(function () {
                        $("#changePasswordModal").modal("hide");
                    }, 3000);
                }
                else {
                    $scope.operationStatus = -1;
                    $scope.operationFailInfo = $translate.instant('Msg' + returnData.resultMsg);
                    $scope.disableUpdate = false;
                }
            });

            //Hide Error Message
            $scope.operationStatus = 0;

        };

        $rootScope.$on('event:showChangePasswordModal', function (e, d) {
            $log.debug("event:showChangePasswordModal from:" + d);

            $("#changePasswordModal").modal("show");
        });

        $rootScope.$on('event:comfirmRemove', function (e, d) {
            $log.debug("event:comfirmRemove id:" + d);

            $("#comfirmRemove").data('id', d);

            $("#comfirmRemove").modal("show");
        });

        $rootScope.$on('event:addChart', function (e, d) {
            $log.debug("event:addChart id:" + d);
            $("#addChart").modal("show");
        });

        $scope.comfirmClick = function () {
            var id = $("#comfirmRemove").data('id');
            $scope.$emit('event:comfirmRemoveResult', id);
        };

        //the success callback of getSystemChartList from dashbaord service at ln 101
        var renderTreeMenu = function (systemchartDic) {
            if (typeof (systemchartDic) === "undefined") {
                return;
            }
            var systemchartList = [];
            for (var key in systemchartDic) {
                if (systemchartDic.haOwnProperty(key)) {
                    for (var val in systemchartDic[key]) {
                        if (systemchartDic[key].haOwnProperty(val)) {
                            var chartDto = systemchartDic[key][val];
                            if (!angular.isFunction(chartDto)) {
                                systemchartList.push(chartDto);
                            }
                        }
                    }
                }
            }
            $scope.systemchartDic = systemchartDic;
            $scope.systemchartList4filter = systemchartList;
            $scope.systemchartList = systemchartList;

            $(document).on('click', '.tree-toggle', function () {
                $(this).parent().children('ul.tree').toggle(200);
            });

            $scope.chartName = "自定义仪表盘";
            $scope.chartDescription = "你可以添加新图表,通过拖拽来改变图表放置的位置,也可以删除不需要的图表。<br/>你可以在添加图表功能中选择数据源,系统会为你添加所选择图表在你的仪表盘中。<br/>你可以在编辑图表功能中修改分析维度以及图表样式。";
            $scope.imgUrl = "../../../app-resources/images/addchart/u6.png";
            $scope.systemchartId = "000000";
            $scope.showAddButton = false;
        };

        $scope.initSystemChart = function () {
            $log.debug('AppModalController.initSystemChart()...');
            dashboardService.getSystemChartList().success(renderTreeMenu);
        };

        $scope.showDetail = function (item) {
            if ($scope.noClick) {
                return false;
            }
            $scope.chartName = item.systemChartName;
            $scope.chartDescription = item.description;
            $scope.imgUrl = item.imgUrl;
            $scope.systemchartId = item.systemChartID;
            $scope.showAddButton = true;
        };

        var getUserchartId = function (data) {
            $log.debug('user chart id:' + data);
            $scope.$emit('event:addUserChart', data);
        };

        $scope.confirmAdd = function () {
            dashboardService.addUserChart($scope.systemchartId).success(getUserchartId);
        };


        $scope.showStyle = { display: 'block' };
        $scope.hideStyle = { display: 'none' };

        (function initialize() {
            $log.debug('AppModalController.initialize()...');

            $("#changePasswordModal").on('show.bs.modal', function () {
                $log.debug('The modal is about to be shown.');

                $scope.init();
            });

            //$scope.initSystemChart();

            $('#filter').bind('focus', function () {
                $(this).val('');/*清除数据*/
                var time = $interval(function () {
                    var filter_str = $('#filter').val();

                    var filterArray = [];
                    angular.forEach($scope.systemchartList4filter, function (item) {
                        if (item.systemChartName.indexOf(filter_str) >= 0) {
                            filterArray.push(item);
                        }
                    });

                    $scope.noClick = false;
                    if (filterArray.length == 0) {
                        filterArray.push({ "systemChartName": "NoSearchContent" });
                        $scope.noClick = true;
                    }

                    $scope.queryResult = filterArray;
                    if (filter_str.length > 0) {
                        $scope.showSearch = true;
                    }
                    else {
                        $scope.showSearch = false;
                    }

                }, 300);/*每300毫秒秒执行一次搜索,time是停止本方法的参数*/
                $(this).bind('blur', function () {
                    $interval.cancel(time); /*停止setInterval*/
                });
            });
        })();
    }]);