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

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

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                escape: false,
                pk: 'id',
                sortName: 'weigh',
                pagination: false,
                escape: false,
                commonSearch: true,
                search: false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),operate:false},
                        {field: 'site_id', title: __('Site_id'), visible:Config.show_sitename,
                            formatter: function (value, row, index) {
                                return row.sites==null?'':'<a href="javascript:;" class="searchit" data-field="site_id" data-value="' + row.site_id + '">' + row.sites.name + '</a>';
                            }
                        },
                        {field: 'type', title: __('Type'), searchList: {channel: __('Channel'), list: __('list'), redirect: __('Redirect')},custom: {channel: 'info', list: 'success', redirect: 'primary'}, formatter: Table.api.formatter.flag},
                        {field: 'name', title: __('Name'), align: 'left', operate: 'LIKE %...%',placeholder: '关键字，模糊搜索', formatter: Controller.api.formatter.catename},
                        {field: 'diyname', title: __('Redirect'), operate:false,
                            formatter:function(value,row,index){
                                diyname = row['type']=='redirect' ? row['redirect'] : value==''? '': '/list/'+value+'.html';
                                return diyname==''? '' : '<a href="' + diyname + '" title="'+diyname+'" target="_blank" class="btn btn-default btn-sm"><i class="fa fa-link"></i></a>';
                            }
                        },
                        {field: 'flag', title: __('Flag'), operate: false, formatter: Table.api.formatter.flag},
                        {field: 'weigh', title: __('Weigh'), visible:true,operate:false},
                        {field: 'archives.items', title: __('Items'),operate:false,
                            formatter:function(value,row,index){
                                return (typeof value === 'number') ? '<span class="label label-info">'+ value +'</span>' : 0;
                            }},
                        {field: 'status', title: __('Status'), searchList: {normal: __('Normal'), hidden: __('Hidden')}, formatter: Table.api.formatter.status},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            $(document).on('change','#c-site_id', function(){
                var self = this;
                if($(self).val()==0) return false;
                var options = table.bootstrapTable('getOptions');
                options.pageNumber = 1;
                options.queryParams = function (params) {
                    return {
                        sort: params.sort,
                        order: params.order,
                        filter: JSON.stringify({site_id: $(self).val()}),
                        op: JSON.stringify({site_id: '='}),
                        offset: params.offset,
                        limit: params.limit,
                    };
                };
                //Toastr.info("数据加载中,请稍候...");
                table.bootstrapTable('refresh');
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            Form.api.bindevent($("#formg"));
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            formatter: {
                catename: function(value,row,index){
                    imgtag = row.image ? '<img src="' + Fast.api.cdnurl('/assets/img/Format_icon_16.png') + '" width="16" height="16" />' : '';
                    return value + '&nbsp;' + imgtag;
                }
            },
            bindevent: function () {
	            $.validator.config({
	                rules: {
	                    diyname: function (element) {
	                        if (element.value.toString().match(/^\d+$/)) {
	                            return __('Can not be digital');
	                        }
	                        return $.ajax({
	                            url: 'posts/channel/check_element_available',
	                            type: 'POST',
	                            data: {id: $("#channel-id").val(), name: element.name, value: element.value},
	                            dataType: 'json'
	                        });
	                    }
	                }
	            });
	            $(document).on("click", "input[name='row[type]']", function () {
	                $(".tf").addClass("hidden");
	                $(".tf.tf-" + $(this).val()).removeClass("hidden");
	                $("select[name='row[model]']").trigger("change");
	                $('#c-template').val($("input[name='row[model]']:checked").data($(this).val()+'tpl'));
	            });
	
	            $(document).on("change", "select[name='row[site_id]']", function () {
	                siteid=$(this).val();
	                //$("#c-pid option:first").prop("selected", true);
	                //$("#c-pid option").addClass("hide");
	                //$("#c-pid option[data-siteid='" + $(that).val() + "']").removeClass("hide");
	                $pid = $('#c-pid');
	
	                Fast.api.ajax({url: 'posts/sites/get_site_info', data: {"site_id": siteid}}, function (x,ret) {
	                	if(ret.code=="1"){
	                		$pid.empty();
	                		$pid.append("<option value='0'>"+ __('None') + "</option>");
	                		$.each(ret.data.list, function(i,k){
	                			$pid.append("<option value='" + ret.data.list[i].id + "'>"+ ret.data.list[i].name + "</option>");
	                		});
	                		$pid.selectpicker("refresh");
	                		$pid.trigger('change');
	                    	$("#language_choose").html(ret.data.lang);
	                	}
	                    Form.api.bindevent($("#language_choose"));
	                    return false;
	                });
	
	            });
	            $(document).on("change", "#c-pid", function () {
	                $("#c-model_"+$('option:selected', this).data('model')).prop("checked", true);
	            });
	            
	            $(document).on("click", "input[name='row[model]']", function () {
	            	type = $("input[name='row[type]']:checked").val();
	                $('#c-template').val($(this).data(type+'tpl'));
	            });
	
	            $("select[name='row[model]']").trigger("change");
	        	$("input[name='row[type]']:checked").trigger("click");
	            
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});