/**
 * 租户管理
 * @author yaodd
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery', 'horizonTable', 'jqueryValidateAll', 'jqueryForm','bootstrapDatepicker', 'gritter'], factory);
    }else {
        factory(jQuery);
    }
}(function($) {
    var $dialog=$('#systemList-dialog');
    var table = {
        //初始化视图数据
        init: function() {
            table.mytable = $('#myDatatable').horizonTable({
                settings: {
                    title: horizon.lang["tenant-grant"]["infoList"],
                    multipleSearchable : true,
                    height: function() {
                        var _height = horizon.tools.getPageContentHeight(),
                            $pageHeader = $('.page-header');
                        if($pageHeader.css('display') != 'none') {
                            _height -= $pageHeader.outerHeight(true);
                        }
                        return _height;
                    },
                    checkbox: 0,
                    columns: [
                        {
                            dataProp : 'id'
                        },
                        {
                            name : 'tenantCode',
                            title : horizon.lang["tenant-grant"]["tenantCode"],
                            width : '200px',
                            searchable : true,
                            multipleSearchable : true,
                            orderable : false,
                            fnClick:operate.tenantGrantInfo
                        },
                        {
                            name : 'tenantName',
                            title : horizon.lang["tenant-grant"]["tenantName"],
                            width : '200px',
                            searchable : true,
                            orderable : false,
                            multipleSearchable:true
                        },
                        {
                            name : 'tenantUser',
                            title : horizon.lang["tenant-grant"]["user"],
                            width : '100px',
                            orderable : false,
                            columnClass :'center'
                        },
                        {
                            name : 'unit',
                            title : horizon.lang["tenant-grant"]["unit"],
                            orderable : false,
                            columnClass :'center'
                        },
                        {
                            name : 'flow',
                            title : horizon.lang["tenant-grant"]["flow"],
                            orderable : false,
                            columnClass :'center'
                        },
                        {
                            name : 'work',
                            title : horizon.lang["tenant-grant"]["work"],
                            orderable : false,
                            columnClass :'center'
                        },
                        {
                            name : 'form',
                            title : horizon.lang["tenant-grant"]["form"],
                            orderable : false,
                            columnClass :'center'
                        },
                        {
                            name : 'expiration',
                            title : horizon.lang["tenant-grant"]["expiration"],
                            width : '150px',
                            orderable : false,
                            columnClass :'center'
                        }
                    ],
                    buttons : [
                        {
                            id: 'resetGrant',
                            text: horizon.lang["tenant-grant"]["resetGrant"],
                            icon: 'fa fa-times red2',
                            fnClick: function(){
                                var ids = table.mytable.checkRowKeyArray;
                                if(!ids.length){
                                    if($('.gritter-item-wrapper').length > 0){
                                            	horizon.notice.error(horizon.lang["tenant-grant"]["resetSelect"]);
                                    }else {
                                    	horizon.notice.error(horizon.lang["tenant-grant"]["resetSelect"]);
                                    }
                                }else{
                                    $dialog.dialog({
                                        title:horizon.lang["message"]["title"],
                                        dialogText:horizon.lang["tenant-grant"]["resetConfirm"],
                                        dialogTextType:'alert-danger',
                                        closeText:horizon.lang["base"]["close"],
                                        buttons:[
                                            {
                                                html: horizon.lang["base"]["ok"],
                                                "class" : "btn btn-primary btn-xs",
                                                click: function() {
                                                    operate.resetTenantGrant(ids.join(";"));
                                                    $(this).dialog('close');
                                                }
                                            }
                                        ]
                                    });
                                }
                            }
                        }
                    ]
                },
                ajaxDataSource: horizon.tools.formatUrl('/system/tenant/grantPage')
            });
        }
    };
    var operate={
        initTenantGrantForm:function() {
            operate.initDatepicker();
            //验证表单
            operate.checkForm();
            $('input[name="expiration"]').change(function () {
                $("#tenantGrantForm").validate().element($(this))
            })
        },
        initDatepicker:function() {
            $('input[name="expiration"]').datepicker({
                format: 'yyyy-mm-dd',
                language: horizon.vars.lang,
                autoclose: true,
                startDate: new Date()
            });
        },
        checkForm:function(){
            return $("#tenantGrantForm").validate({
                ignore: '.ignore',
                errorClass: 'help-block no-margin-bottom',
                focusInvalid: false,
                rules: {
                    tenantUser: {
                        digits:true,
                        remote:{
                            url:horizon.tools.formatUrl('/system/tenant/check/tenantGrant'),
                            cache: false,
                            data:{
                                user : function() {
                                    return $('#tenantGrantForm').find('input[name="tenantUser"]').val();
                                },
                                tenantCode : function() {
                                    return $('#tenantGrantForm').find('input[name="tenantCode"]').val();
                                }
                            }
                        }
                    },
                    unit: {
                        digits:true,
                        remote:{
                            url:horizon.tools.formatUrl('/system/tenant/check/tenantGrant'),
                            cache: false,
                            data:{
                                unit : function() {
                                    return $('#tenantGrantForm').find('input[name="unit"]').val();
                                },
                                tenantCode : function() {
                                    return $('#tenantGrantForm').find('input[name="tenantCode"]').val();
                                }
                            }
                        }
                    },
                    flow:{
                        digits:true,
                        remote:{
                            url:horizon.tools.formatUrl('/system/tenant/check/tenantGrant'),
                            cache: false,
                            data:{
                                flow : function() {
                                    return $('#tenantGrantForm').find('input[name="flow"]').val();
                                },
                                tenantCode : function() {
                                    return $('#tenantGrantForm').find('input[name="tenantCode"]').val();
                                }
                            }
                        }
                    },
                    work:{
                        digits:true,
                        remote:{
                            url:horizon.tools.formatUrl('/system/tenant/check/tenantGrant'),
                            cache: false,
                            data:{
                                work : function() {
                                    return $('#tenantGrantForm').find('input[name="work"]').val();
                                },
                                tenantCode : function() {
                                    return $('#tenantGrantForm').find('input[name="tenantCode"]').val();
                                }
                            }
                        }
                    },
                    form:{
                        digits:true,
                        remote:{
                            url:horizon.tools.formatUrl('/system/tenant/check/tenantGrant'),
                            cache: false,
                            data:{
                                form : function() {
                                    return $('#tenantGrantForm').find('input[name="form"]').val();
                                },
                                tenantCode : function() {
                                    return $('#tenantGrantForm').find('input[name="tenantCode"]').val();
                                }
                            }
                        }
                    },
                    expiration:{
                        remote:{
                            url:horizon.tools.formatUrl('/system/tenant/check/tenantGrant'),
                            cache: false,
                            data:{
                                expiration : function() {
                                    return $('#tenantGrantForm').find('input[name="expiration"]').val();
                                },
                                tenantCode : function() {
                                    return $('#tenantGrantForm').find('input[name="tenantCode"]').val();
                                }
                            }
                        }
                    }
                },
                messages: {
                    tenantUser: {
                        remote:horizon.lang["tenant-grant"]["checkUser"]
                    },
                    unit: {
                        remote:horizon.lang["tenant-grant"]["checkUnit"]
                    },
                    flow: {
                        remote:horizon.lang["tenant-grant"]["checkFlow"]
                    },
                    work:{
                        remote:horizon.lang["tenant-grant"]["checkWork"]
                    },
                    form:{
                        remote:horizon.lang["tenant-grant"]["checkForm"]
                    },
                    expiration:{
                        remote:horizon.lang["tenant-grant"]["checkExpiration"]
                    }
                },
                highlight: function (e) {
                    $(e).closest('.form-group').addClass('has-error');
                },
                success: function (e) {
                    $(e).closest('.form-group').removeClass('has-error');
                    $(e).remove();
                },
                errorPlacement: function(error, element) {
                    if(element.next().attr("class")=='input-group-addon'){
                        error.appendTo(element.parent().parent());
                    }else{
                        error.appendTo(element.parent());
                    }
                },
                submitHandler: function (form){
                	horizon.notice.loading(horizon.lang['tenant-grant']['operating']);
                    var url='/system/tenant/grant';
                    table.mytable.showProcessing();
                    $(form).ajaxSubmit({
                        url: horizon.tools.formatUrl(url),
                        dataType: 'json',
                        type: 'post',
                        cache: false,
                        error: function() {
                            table.mytable.hideProcessing();
                            horizon.notice.error(horizon.lang["tenant-grant"]["grantFail"]);
                        },
                        success: function(data) {
                            table.mytable.hideProcessing();
                            if(data.restype == 'success'){
                                horizon.notice.success(horizon.lang["tenant-grant"]["grantSuccess"]);
                                $('#tenantGrantInfo').dialog('close')
                                table.mytable.reload();
                            }else{
                                var msg = data.msg[0]? data.msg[0]:horizon.lang["tenant-grant"]["grantFail"]
                                horizon.notice.error(msg);
                            }
                        }
                    });
                }
            });
        },

        //删除租户
        resetTenantGrant:function(ids){
            table.mytable.showProcessing();
            $.ajax({
                url:horizon.tools.formatUrl('/system/tenant/resetGrant'),
                cache: false,
                data:{
                    ids:ids
                },
                error:function(){
                    table.mytable.hideProcessing();
                    horizon.notice.error(horizon.lang.message['operateError']);
                },
                success:function(data){
                    table.mytable.hideProcessing();
                    if(data.restype != 'err'){
                    	horizon.notice.success(horizon.lang["tenant-grant"]["resetSuccess"]);
                        table.mytable.reload();
                    }else{
                    	horizon.notice.error(horizon.lang["tenant-grant"]["resetFail"]);
                    }
                }
            });
        },
        tenantGrantInfo:function() {
            var $validate = operate.checkForm();
            $validate.resetForm();
            var rowData = arguments[2];
            $.each(rowData,function(key,value){
                $('#tenantGrantForm').find('input[name="' + key + '"]').val(value);
            });
            operate.openTenantGrant();
        },
        openTenantGrant:function() {
            $('.form-group').removeClass('has-error');
            $('label[id*="-error"]').html('');
            $('#tenantGrantInfo').dialog({
                width: $(window).width() > 900?'900':'auto',
                height: 'auto',
                maxHeight: $(window).height(),
                title:horizon.lang["tenant-grant"]["grantInfo"],
                closeText:horizon.lang["base"]["close"],
                buttons:[
                    {
                        html: horizon.lang["base"]["save"],
                        "class" : "btn btn-primary btn-xs",
                        click: function() {
                            $('#tenantGrantForm').submit();
                        }
                    }
                ]
            });
        }
    };
    return horizon.engine['tenantgrant'] = {
        init:function () {
            table.init();
            operate.initTenantGrantForm();
        }
    };
}));