adminHomePageModule
    .controller('AdminHomePageController', ['$scope', '$log', 'SweetAlert', '$translate', 'menuService', '$timeout', 'userService', 'loginContext', 'Upload', 'apiInterceptor', 'dataInitService',
        function ($scope, $log, SweetAlert, $translate, menuService, $timeout, userService, loginContext, Upload, apiInterceptor, dataInitService) {
            'use strict';

            var imageUrl = [
                '../../../app-resources/images/admin_hover__1__03.png',
                '../../../app-resources/images/admin_hover__1__05.png',
                '../../../app-resources/images/admin_hover__1__07.png'
            ];

            var uploadUrl = apiInterceptor.webApiHostUrl + '/init/Upload';
            var fileUploadModalSelector = "#importBasicData";
            var resumable = true;
            $scope.hasAdminPermission = false;

            var getMenusByServiceTypeId = function (serviceTypeId) {

                userService.getUserPermissionNew(loginContext.userName, function (data) {
                    if (data && data.isAdmin) {
                        $scope.hasAdminPermission = true;
                    }

                    $timeout(function () {
                        menuService.getMenusNew(serviceTypeId, function (menuData) {
                            $scope.menuData = menuData;

                            if ($scope.menuData && $scope.menuData.length > 0) {
                                for (var i = 0; i < $scope.menuData.length; i++) {
                                    var r = i % imageUrl.length;
                                    var row = $scope.menuData[i];

                                    if (r === 0) {
                                        row.popoverPlacement = 'bottom-left';
                                        row.firstMenuClass = "menu-wrapper";
                                    } else if (r == imageUrl.length - 1) {
                                        row.popoverPlacement = 'bottom';
                                        row.firstMenuClass = "menu-wrapper";
                                    } else {
                                        row.popoverPlacement = 'bottom';
                                        row.firstMenuClass = "menu-wrapper";
                                    }
                                    row.imageUrl = imageUrl[r];
                                    row.templateUrl = 'myPopoverTemplate.html';

                                    if (row.subMenus) {
                                        row.subMenus = _.filter(row.subMenus, function (sub) {
                                            return sub.isVisible;
                                        });
                                    }
                                }
                            }
                        });
                    }, 1000);

                });
            };

            var getMenuItem = function (row, isAdmin, navigationUrlList) {
                if (!row.isVisible) {
                    return null;
                }
                if (row.subMenus && row.subMenus.length > 0) {
                    // 基础数据维护菜单特殊处理
                    if (row.id === constant.BasicDataManageMenuID) {

                        if (!isAdmin) {
                            var subMenus = _.find(row.subMenus, function (num) {
                                return navigationUrlList.indexOf(num.navigationUrl) > -1;
                            });

                            if (subMenus && navigationUrlList.indexOf(row.navigationUrl) === -1) {

                                // 设置基础数据菜单 默认url地址

                                if (navigationUrlList.indexOf(constant.basicDataUrl.businessUnit) > -1) {
                                    row.navigationUrl = constant.basicDataUrl.businessUnit;
                                } else if (navigationUrlList.indexOf(constant.basicDataUrl.regionManage) > -1) {
                                    row.navigationUrl = constant.basicDataUrl.regionManage;
                                } else if (navigationUrlList.indexOf(constant.basicDataUrl.enterpriseAccountManage) > -1) {
                                    row.navigationUrl = constant.basicDataUrl.enterpriseAccountManage;
                                } else if (navigationUrlList.indexOf(constant.basicDataUrl.customerListManage) > -1) {
                                    row.navigationUrl = constant.basicDataUrl.customerListManage;
                                }
                            }

                        }

                        row.subMenus = [];

                    } else {
                        var menuList = [];
                        row.subMenus.forEach(function (menu) {
                            var temp = getMenuItem(menu, isAdmin, navigationUrlList);
                            if (temp) {
                                menuList.push(temp);
                            }
                        });

                        row.subMenus = menuList;

                    }
                }

                // 系统管理就没有地址
                if (!row.navigationUrl && row.subMenus && row.subMenus.length > 0) {
                    return row;
                }

                if (isAdmin || (navigationUrlList && navigationUrlList.indexOf(row.navigationUrl) > -1)) {
                    return row;
                }
                return null;
            };

            // 选中大菜单
            $scope.selectMenu = function (x) {

            };

            $scope.menuMouseOver = function (x) {

                if (x.isOpen) {
                    return;
                }

                if ($scope.menuData && $scope.menuData.length > 0) {
                    for (var i = 0; i < $scope.menuData.length; i++) {
                        var row = $scope.menuData[i];
                        if (x.id === row.id) {
                            row.isOpen = true;
                        } else {
                            row.isOpen = false;
                        }
                    }
                }
            };

            // 页面跳转
            $scope.GoPage = function (x) {

            };

            $scope.showUploadModal = function () {
                $scope.triggered = false;
                $scope.completed = false;
                $scope.importMsgList = '';
                if ($scope.file) $scope.file = null;
                $(fileUploadModalSelector).modal('show');
            }

            var ImportCustomer = function (action) {

                if (!$scope.file || !$scope.file.name) {

                    SweetAlert.warning($translate.instant('SelectCustomerFileRequired'));
                    return;
                }

                var tempFileName = PWC.newGuid() + '.dat';

                var token = $('input[name="__RequestVerificationToken"]').val();
                // updateProgressToZero();
                Upload.upload({
                    url: uploadUrl,
                    data: {
                        cancel: false,
                        enterpriseAccountID: $scope.accountSetID,
                        filename: $scope.file.name,
                        tempFileName: tempFileName,
                        action: action
                    },
                    file: $scope.file,
                    resumeChunkSize: resumable ? $scope.chunkSize : null,
                    headers: {
                        'Access-Control-Allow-Origin': '*',
                        Authorization: apiInterceptor.tokenType + ' ' + apiInterceptor.apiToken,
                        __RequestVerificationToken: token,
                        withCredentials: true
                    }, withCredentials: true
                }).then(function (resp) {

                    $scope.importMsgList = resp.data.validMsg;
                    $scope.completed = true;
                    //var msgInfo = '<table style="font-size:13px;width:800px">';
                    //var validMsgList = resp.data.validMsg;
                    //validMsgList.forEach(function (row) {
                    //    msgInfo +='<tr><td>' +row+'</td></tr>' ;
                    //});

                    //msgInfo+='</table>'

                    //var errorMsg = resp.data.errorMsg;
                    //SweetAlert.swal({
                    //    title: $translate.instant('ImportBasicData'),
                    //    text: msgInfo,
                    //    type: "warning",
                    //    showCancelButton: false,
                    //    closeOnConfirm: false,
                    //    closeOnCancel: true,
                    //    html: true
                    //});

                    //if (resp.data.length == 0) {
                    //    SweetAlert.success($translate.instant('ImportSuccess'));
                    //}
                    //else {
                    //    SweetAlert.warning($translate.instant('ImportPartialSuccess'));
                    //}
                    //$(fileUploadModalSelector).modal('hide');
                }, function (resp) {
                    console.log('Error status: ' + resp.status);
                }, function (evt) {
                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                    $log.debug('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
                });

            };

            $scope.ImportData = function () {
                ImportCustomer(constant.import.overwrite);
                $scope.triggered = true;
            };

            $scope.downloadTemplate = function () {
                dataInitService.downloadTemplate();
            };

            (function initialize() {
                $scope.open = false;
                getMenusByServiceTypeId('1');

                //var glyph_opts = {
                //    map: {
                //        doc: "glyphicon glyphicon-file",
                //        docOpen: "glyphicon glyphicon-file",
                //        checkbox: "glyphicon glyphicon-unchecked",
                //        checkboxSelected: "glyphicon glyphicon-check",
                //        checkboxUnknown: "glyphicon glyphicon-share",
                //        dragHelper: "glyphicon glyphicon-play",
                //        dropMarker: "glyphicon glyphicon-arrow-right",
                //        error: "glyphicon glyphicon-warning-sign",
                //        expanderClosed: "fa fa-plus",
                //        expanderLazy: "glyphicon glyphicon-menu-right",  // glyphicon-plus-sign
                //        expanderOpen: "fa fa-minus",  // glyphicon-collapse-down
                //        folder: "glyphicon glyphicon-folder-close",
                //        folderOpen: "glyphicon glyphicon-folder-open",
                //        loading: "glyphicon glyphicon-refresh glyphicon-spin"
                //    }
                //};

                //$("#tree").fancytree({
                //    extensions: ["glyph"],
                //    checkbox: true,
                //    selectMode: 3,
                //    glyph: glyph_opts,
                //    source: [  // Typically we would load using ajax instead...
                //      { title: "Node 1" },
                //      { title: "Node 2" },
                //      {
                //          title: "Folder 3", folder: true, expanded: true, children: [
                //           { title: "Node 3.1", key: "id3.1" },
                //           { title: "Node 3.2", selected: true }
                //          ]
                //      },
                //      {
                //          title: "Folder 4", folder: true, children: [
                //           { title: "Node 4.1" },
                //           { title: "Node 4.2" }
                //          ]
                //      }
                //    ],
                //    activate: function (event, data) {
                //        $("#statusLine").text(event.type + ": " + data.node);
                //    },
                //    select: function (event, data) {
                //        $("#statusLine").text(event.type + ": " + data.node.isSelected() +
                //                              " " + data.node);
                //    }
                //});


            })();
        }
    ]);

adminHomePageModule.directive('adminHomePage', ['$log',
    function ($log) {
        'use strict';
        $log.debug('adminHomePage.ctor()...');
        console.log('adminHomePagector');
        return {
            restrict: 'E',
            templateUrl: '/app/admin/homePage/admin-home-page.html' + '?_=' + Math.random(),
            replace: true,
            scope: {
            },
            controller: 'AdminHomePageController',
            link: function (scope, element) {
                //$log.info(scope.state);
            }
        };
    }
]);