/**
 * Created by Administrator on 2016/7/29.
 */
myAdminApp.controller('roleManageCtrl', ['$scope', '$http', 'RoleManageService', function($scope, $http, RoleManageService) {

    var roleMenuList, roleCreateMenuList, createOrUpdate;
    // 下拉框显示隐藏
    $('[name="nice-select"]').click(function(e){
        $('[name="nice-select"]').find('ul').hide();
        $(this).find('ul').show();
        e.stopPropagation();
    });
    $('[name="nice-select"] li').hover(function(e){
        $(this).toggleClass('on');
        e.stopPropagation();
    });
    $('[name="nice-select"] li').click(function(e){
        var val = $(this).text();
        $(this).parents('[name="nice-select"]').find('input').val(val);
        $(this).parents('[name="nice-select"]').find('input').attr('roleType', $(this).val());
        $scope.$apply(function () {
            if (createOrUpdate == 'update') {
                var updateRole = $('#modalUpdateRoleType').attr('roleType');
                $scope.showMenuItem = updateRole;
                $scope.roleDetailList = roleMenuList;
            } else {
                var createRole = $('#modalRoleType').attr('roleType');
                $scope.showCreateMenu = createRole;
                $scope.createMenuList = roleCreateMenuList;
            }

        });
        $('[name="nice-select"] ul').hide();
        e.stopPropagation();
    });
    $(document).click(function(){
        $('[name="nice-select"] ul').hide();
    });

    $scope.openRoleModal = function (id, name, desc, type) {
        createOrUpdate = 'update';
        $scope.modalUpdateRoleId = id;
        $scope.modalUpdateRoleName = name;
        $scope.modalUpdateRoleDesc = desc;
        $('#modalUpdateRoleType').attr('roleType', type);
        switch (parseInt(type)) {
            case 1:
                $scope.modalUpdateRoleType = '客户';
                $('#modalUpdateRoleType').val('客户');
                $scope.showMenuItem = '1';
                $scope.modalUpdateRoleTypeList = true;
                break;
            case 2:
                $scope.modalUpdateRoleType = '员工';
                $('#modalUpdateRoleType').val('员工');
                $scope.showMenuItem = '2';
                $scope.modalUpdateRoleTypeList = true;
                break;
            case 3:
                $scope.modalUpdateRoleType = '管理员';
                $('#modalUpdateRoleType').val('管理员');
                $scope.showMenuItem = '3';
                $scope.modalUpdateRoleTypeList = false;
                break;
        }
        var url = '/trans/base/role/'+id;
        $http({
            url: url,
            method: 'GET',
            headers: {
                "adminCode": $.cookie("adminCode"),
                "token": $.cookie("token"),
                "authType": $.cookie("authType")}
        }).success(function (data) {
            if (data.success) {
                $scope.modalRoleName = data.role.roleName;
                $scope.roleDetailList = data.role.menuList;
                roleMenuList = data.role.menuList;
            } else {
                errorAdminMsgHint(data.errorCode, data.errorMsg);
            }
        });
    }

    $scope.updateRoleInfo = function () {
        var authorityList = new Array();
        $('#roleDetailInfo div').each(function (i) {
            var isSelected = $(this).find('.first-menu-check').prop('checked');
            if (isSelected) {
                var operationList = new Array();
                /*$(this).find('.menu-operate').each(function (j) {
                    var isOperateSelected = $(this).find('.role-check').prop('checked');
                    if (isOperateSelected) {
                        operationList.push($(this).find('.mo-id').text());
                    }
                });*/
                var authority = new Authority($(this).find('.menu-id').text(), operationList);
                authorityList.push(authority);
            }
        });
        var updateRoleReq = {
            "roleName" : $scope.modalUpdateRoleName,
            "roleDesc" : $scope.modalUpdateRoleDesc,
            "roleType": $('#modalUpdateRoleType').attr('roleType'),
            "authorityList":authorityList
        };
        updateRoleReq = JSON.stringify(updateRoleReq);

        var url = "/trans/base/role/" + $scope.modalUpdateRoleId;
        $http.post(url, updateRoleReq, {
            headers: {
                "adminCode": $.cookie("adminCode"),
                "token": $.cookie("token"),
                "authType": $.cookie("authType")}
        }).success(function(data) {
            if (typeof data == "string") {
                data = $.parseJSON(data);
            }
            if (data.success) {
                $('#setRoleModal').modal('hide');
                showAlertDialog(0, "修改成功！");
                getAllRoleInfoList();
            }else{
                errorAdminMsgHint(data.errorCode, data.errorMsg);
            }
        });
    }
    
    $scope.openCreateRoleModal = function () {
        createOrUpdate = 'create';
        $('#modalRoleName').val("");
        $('#modalRoleDesc').val("");
        $('#modalRoleType').val("客户");
        $('#modalRoleType').attr('roleType', '1');
        $scope.showCreateMenu = '1';
        var url = '/trans/base/role/authorities';
        $http({
            url: url,
            method: 'GET',
            headers: {
                "adminCode": $.cookie("adminCode"),
                "token": $.cookie("token"),
                "authType": $.cookie("authType")}
        }).success(function (data) {
            if (data.success) {
                $scope.createMenuList = data.menuList;
                roleCreateMenuList = data.menuList;
            } else {
                errorAdminMsgHint(data.errorCode, data.errorMsg);
            }
        });
    }

    $scope.createRole = function () {
        var authorityList = new Array();
        $('#createRoleMenu div').each(function (i) {
            var isSelected = $(this).find('.first-menu-check').prop('checked');
            if (isSelected) {
                var operationList = new Array();
                /*$(this).find('.menu-operate').each(function (j) {
                    var isOperateSelected = $(this).find('.role-check').prop('checked');
                    if (isOperateSelected) {
                        operationList.push($(this).find('.mo-id').text());
                    }
                });*/
                var authority = new Authority($(this).find('.menu-id').text(), operationList);
                authorityList.push(authority);
            }
        });
        var createRoleReq = {
            "roleName" : $('#modalRoleName').val(),
            "roleDesc" : $('#modalRoleDesc').val(),
            "roleType": $('#modalRoleType').attr('roleType'),
            "authorityList":authorityList
        };
        createRoleReq = JSON.stringify(createRoleReq);

        var url = "/trans/base/role";
        $http.put(url, createRoleReq, {
            headers: {
                "adminCode": $.cookie("adminCode"),
                "token": $.cookie("token"),
                "authType": $.cookie("authType")}
        }).success(function(data) {
            if (typeof data == "string") {
                data = $.parseJSON(data);
            }
            if (data.success) {
                $('#createRoleModal').modal('hide');
                showAlertDialog(0, "创建成功！");
                getAllRoleInfoList();
            }else{
                errorAdminMsgHint(data.errorCode, data.errorMsg);
            }
        });
    }

    $scope.delRole = function (id) {
        $('#del-dialogBox').dialogBox({
            type: 'normal',  //three type:'normal'(default),'correct','error',
            width: 300,
            height: 200,
            status: 2,
            hasMask: true,
            hasClose: true,
            hasBtn: true,
            confirmValue: "删除",
            cancelValue: "取消",
            confirm: function () {
                var url = "/trans/base/role/" + id;

                $http({
                    url: url,
                    method: 'DELETE',
                    headers: {
                        "adminCode": $.cookie("adminCode"),
                        "token": $.cookie("token"),
                        "authType": $.cookie("authType")}
                }).success(function (data) {
                    if (data.success) {
                        showAlertDialog(0, '删除成功！');
                        getAllRoleInfoList();
                    } else {
                        errorAdminMsgHint(data.errorCode, data.errorMsg);
                    }
                });
            },
            effect: 'sign',
            title: '提示',
            content: '是否删除该角色？'
        });
    }

    /** 查询 */
    $scope.userListSearch = function () {
        getAllRoleInfoList();
    }

    /** 重置 */
    $scope.userListReset = function () {
        $scope.roleName = "";
        $scope.roleType = "";
        $('#_roleType').attr('roleType', '0');
        getAllRoleInfoList();
    }

    /** 角色信息列表并分页 */
    var getAllRoleInfoList = function () {

        var roleData = {
            roleName: $scope.roleName,
            roleType: $('#_roleType').attr('roleType'),
            currentPage: $scope.paginationConf.currentPage,
            pageSize: $scope.paginationConf.itemsPerPage
        }
        RoleManageService.list(roleData).success(function (data) {
            if (typeof data == "string") {
                data = $.parseJSON(data);
            }
            if (data.success) {
                $scope.paginationConf.totalItems = data.pagingInfo.totalRows;
                $scope.roleList = data.data;
            } else {
                errorAdminMsgHint(data.errorCode, data.errorMsg);
            }

        });

    }

    //配置分页基本参数
    $scope.paginationConf = {
        currentPage: 1,
        itemsPerPage: 10,
        perPageOptions: [10, 20, 50, 100]
    };

    /***************************************************************
     当页码和页面记录数发生变化时监控后台查询
     如果把currentPage和itemsPerPage分开监控的话则会触发两次后台事件。
     ***************************************************************/
    $scope.$watch('paginationConf.currentPage + paginationConf.itemsPerPage', getAllRoleInfoList);

}]);

//业务类
myAdminApp.factory('RoleManageService', ['$http', function ($http) {
    var list = function (roleData) {
        return $http({
            url:'/trans/base/role',
            method:'GET',
            params: roleData,
            headers: {
                "adminCode": $.cookie("adminCode"),
                "token": $.cookie("token"),
                "authType": $.cookie("authType")}
        });
    }

    return {
        list: function (roleData) {
            return list(roleData);
        }
    }
}]);

function Authority(menuId,operationIdList){
    this.menuId = menuId;
    this.operationIdList = operationIdList;
}