define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template'], function ($, undefined, Backend, Table, Form, Template) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'posts/modelx/index',
                    add_url: 'posts/modelx/add',
                    edit_url: 'posts/modelx/edit',
                    del_url: 'posts/modelx/del',
                    multi_url: 'posts/modelx/multi',
                    table: 'postsmodelx',
                }
            });

            var table = $("#table");
            

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                search: false,
                pagination: false,
                columns: [
                    [
                        {field: 'name', title: __('Name')},
                        {field: 'title', title: __('Title')},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, 
                        	buttons: [
                                {name: 'fieldset', extend: 'title="'+ __('Fieldset')+'"', classname: 'btn btn-xs btn-success btn-dialog', icon: 'fa fa-pencil', url: $.fn.bootstrapTable.defaults.extend.edit_url}
                            ],
                        	formatter: function(value,row,index){
	                        	$btns = $('<div></div>').html(Table.api.formatter.operate.call(this, value, row, index));
	                        	$('.btn-editone', $btns).remove();
								return $btns.html();
	                        }
                        }
                    ]
                ]
            });
            
            
            $(document).on('click', '.btn-update', function (e) {
                e.preventDefault();
                var inx = $(this).data('row'), status=$(this).data('status');
                var fun=function(ret,data){
                	if(data!='success') return false;
					table.bootstrapTable('updateRow', {
						index:inx,
						row:{'status': status}
					});
				}
				
                Backend.api.ajax({url : 'posts/modelx/chgstatus',
                	data:{ids: $(this).data('updateid'), 'status':status } ,
                	complete: fun
                });
           });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
        	$(document).on('click', '.btn-param', function(e){
                e.preventDefault();

                var fid = $(this).data('fieldid');
                var opennerLayer = parent.Layer.getFrameIndex(window.name);
                var params = fid?'&params='+fid:'';
                //编辑窗口layer的index
                parent.Backend.api.open('posts/modelx/fieldset?zl='+opennerLayer+params, $(this).attr('title'), {callback: Controller.api.saveParams});
                
                return false;
        	});
        	$(document).on('click', '.btn-change', function(e){
        		var that=this;
        		Backend.api.ajax({
        			url: 'posts/modelx/chgstatus',
        			data: {"ids": $(that).data('ids'), "field": $(that).data('field')}
            	}, function(ret,data){
            		if(data.code==1){
            			if ($(that).find('i').hasClass('fa-toggle-on')){
            				$(that).find('i').removeClass('fa-toggle-on').addClass('fa-toggle-off');
            			}else{
            				$(that).find('i').removeClass('fa-toggle-off').addClass('fa-toggle-on');
            			}
            		}
        		})
        	});
        	$(document).on('click', '.btn-delparam', function(e){
                e.preventDefault();
                $(this).closest('li').off().remove();
        	});
        	$(document).on('click', '.btn-submit', function(e){
                e.preventDefault();
                //var data={fieldset: []};
                var data=[];
                if($('#fieldset li').size()>0){
                	$('#fieldset li').each(function(i){
            			//data.fieldset.push( $(this).data() );
            			data.push($(this).data());
                	});
            		//$('input[name="row[extra]"]').val(JSON.stringify(data));

            		Backend.api.ajax({
            			url: 'posts/modelx/fieldset',
            			data: {ids: $('input[name="ids"]').val(), fieldset: JSON.stringify(data)}
            		}, function(){
            			var index = parent.Layer.getFrameIndex(window.name);
                        parent.Layer.close(index);
            		});
                }
                //$('#edit-form').submit();
        	});
            Controller.api.bindevent();
        },
        fieldset: function(){
			var fieldid =  Fast.api.query('params'),
				opennerLayer = Fast.api.query('zl');
				
            $.validator.config({
                rules: {
                    fieldname: function (element) {
                    	_value = $.trim(element.value.toString());
                    	if($(element).attr('name')=='field'){
                    		_old=$('[name="field-old"]').val();
                    		if(_value==_old) return '';
                    	}
                        if (_value.match(/^\d+$/)) {
                            return __('Can not be digital');
                        }
                        if (_value.length<3 || _value.length>30) {
                            return __('Please enter a value between %d and %d characters long',3,30);
                        }
                        
                        let exists = false;
                        var c = parent.Layer.getChildFrame('body', opennerLayer);
                        $('#fieldset li',c).each(function(){
	            			if(_value == $(this).data('field')){
	            				exists=true;
	            				return false;
	            			}
	            		});
	            		if(exists) return  __('Field already exist');
                        
                        return $.ajax({
                            url: 'posts/modelx/check_element_available',
                            type: 'POST',
                            data: {"id": $("[name='ids']", c).val(), "value": _value},
                            dataType: 'json'
                        });
                    }
                }
            });
            
        	$('select#c-type').on('change', function(e){
        		$('.tf').addClass("hidden");
        		$('.tf.tf-' + $('option:selected', this).val()).removeClass("hidden");
        	});

        	$(document).on('click', '.btn-reset', function(e){
        		e.preventDefault();
	        	if(fieldid!=undefined){
	                var c = parent.Layer.getChildFrame('body', opennerLayer);
	                $('input[name="fieldid"]').val(fieldid);
	            	var arr = ['field','fieldname','type','value','rule','tip','extend','length','vars','float','min','max','length','success','error','status'];
	            	$.each(arr, function(index,item){
	            		let val = $('#fieldset li#'+fieldid, c).attr('data-'+item+'');
	            		val = val!=undefined ? val.indexOf('||') ? val.replace(/(\|\|)/g, '\r\n') : val : '';
	            		if(item=='status'){
	            			$('[name="'+item+'"][value="'+val+'"]').prop('checked',true);
	            		}else{
	            			$('[name="'+item+'"]').val( val );
	            		}
					});
					$('[name="field-old"]').val($('[name="field"]').val());
				}
        	});
        	$('.btn-reset').trigger('click');
        	$('select#c-type').trigger('change');
        	
        	Form.api.submit = function(){
        		var data={};
            	$('select:visible,input:visible,textarea:visible,input[name="fieldid"],input[name="rule"]').each(function(){
                	data[$(this).attr('name')]=$(this).val().replace(/([\r\n])/g, '||');
            	});
            	data['status']=$('input[name="status"]:checked').val();
        		Backend.api.close(data); 
        		return false;
        	}
            Controller.api.bindevent();
        },
        api: {
        	formatter: {
        		status: function(value,row,index){
        			var texts=['<span class="label label-success">' + __('Enabled') + '</span> &nbsp;',
        					'<span class="label label-danger">' + __('Disabled') + '</span> &nbsp;'];
        			var btns = ['<a href="javascript:;" data-updateid="'+row.id+'" data-status="1" data-row="'+index+'" class="btn-update" title="' + __('Enable') + '"><i class="fa fa-check"></i>' + __('Enable') + '</a>',
       						'<a href="javascript:;" data-updateid="'+row.id+'" data-status="0" data-row="'+index+'" class="btn-update" title="' + __('Disable') + '"><i class="fa fa-ban"></i>' + __('Disable') + '</a>'];
        			return (value==1)? texts[0]+btns[1] : texts[1]+btns[0];
        		}
        	},
        	saveParams: function(res){
        		var lidata='', newli=false;
            	if(res.fieldid==''){
        			res.fieldid = 'p'+new Date().getTime();
        			newli=true;
    			}
            	$.each(res, function(key,value){
                	lidata+= (key!='fieldid')? ' data-'+key+ (value==''?'':'='+value) :'';
            	});

        		var li = Template('fieldTpl', {
        			fieldid: res.fieldid,
        			field: res.field,
        			title: res.fieldname,
        			type: __(res.type),
        			status: __(res.status),
        			datapart: lidata
        		});
        		
        		if(newli){
        			$('#fieldset div#btnAddParam').before($(li));
        		}else{
        			$('#fieldset li#'+res.fieldid).off().before($(li)).remove();
        		}
        		
        		Controller.api.bindevent();
        	},
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});