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

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

            var table = $("#table");
            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
                Form.events.cxselect($("form", table.$commonsearch));
            });

            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone", this)
                        .off("click")
                        .removeClass("btn-editone")
                        .addClass("btn-addtabs")
                        .prop("title", __('Edit'));
            });
            
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                sortOrder: 'desc',
                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: 'channel_id', title: __('Channel_id'),searchList: $.getJSON('posts/channel/getlist'),
                            formatter: function (value, row, index) {
                                return row.channel==null?'':'<a href="javascript:;" class="searchit" data-field="channel_id" data-value="' + value + '">' + row.channel.name + '</a>';
                            }
                        },
                        {field: 'type', title: __('type'), formatter: function (value,row,index){
                            return '<span class="label label-info">'+value+'</span>';
                        }, operate:false },
                        {field: 'title', align:'left', title: __('title'), operate: 'LIKE %...%',placeholder: '关键字，模糊搜索',
                            formatter: function(value,row, index){
                                return value + (row.cover==''?'' : ' <span><i class="fa fa-file-image-o text-danger"></i></span>');
                            }},
                        {field: 'status', title: __('status'), searchList: {normal: __('Normal'), hidden: __('Hidden')}, formatter: Table.api.formatter.status},
                        {field: 'updatetime', title: __('updatetime'),operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'views', title: __('Views'), operate:false},
                        {field: 'weigh', title: __('Weigh'), operate:false},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            //buttons: [
                            //    {name: 'edit', extend: 'title="'+ __('Edit')+'"', classname: 'btn btn-xs btn-success btn-addtabs', icon: 'fa fa-pencil', url: $.fn.bootstrapTable.defaults.extend.edit_url}
                            //],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            $(document).on('click', '.btn-move', function () {
                var ids = Table.api.selectedids(table);
                Layer.open({
                    title: __('Move'),
                    content: Template("channeltpl", {}),
                    btn: [__('Move')],
                    yes: function (index, layero) {
                        var channel_id = $("select[name='channel']", layero).val();
                        if (channel_id == 0) {
                            Toastr.error(__('Please select channel'));
                            return;
                        }
                        Fast.api.ajax({
                            url: "posts/archives/move/ids/" + ids.join(","),
                            type: "post",
                            data: {channel_id: channel_id},
                        }, function () {
                            table.bootstrapTable('refresh', {});
                            Layer.close(index);
                        });
                    },
                    success: function (layero, index) {
                    }
                });
            });


        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    multi_url: 'posts/archives/multi',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'posts/archives/recyclebin',
                pk: 'id',
                sortName: 'weigh',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('id'), operate: false},
                        {field: 'site_id', title: __('Site_id'), operate: false, formatter:function(value,row,index){
                            return row.sites==null? __('Main site') : row.sites.name + ' (' + row.sites.domain + ')';
                        }},
                        {field: 'channel_id', title: __('channel'),
                            formatter: function(value,row,index){return row.channel.name;},
                            searchList: $.getJSON('posts/channel/getlist')
                        },
                        {field: 'title', title: __('title'), operate: 'LIKE %...%'},
                        {field: 'deletetime', title: __('deletetime'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', width: '130px', title: __('Operate'), table: table, events: Table.api.events.operate,
                            buttons: [
                                {name: 'Restore', text: __('Restore'), classname: 'btn btn-xs btn-info btn-restoreit', icon: 'fa fa-rotate-left', url: 'posts/archives/restore'},
                                {name: 'Destroy', text: __('Destroy'), classname: 'btn btn-xs btn-danger btn-destroyit', icon: 'fa fa-times', url: 'posts/archives/destroy'}
                            ],
                            formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

			//清空回收站、批量/单个销毁
            $(document).on('click', '.btn-destroyall,.btn-destroy,.btn-destroyit', function (e) {
                var that = this;
                var top = $(that).offset().top - $(window).scrollTop();
                var left = $(that).offset().left - $(window).scrollLeft();
                //顶部按钮显示下按钮下方
                if(!$(that).hasClass('btn-destroyit')) top += $(that).height();
                //表格中的删除，显示于左侧
                if($(that).hasClass('btn-destroyit')) left -= 260;
                if (top + 154 > $(window).height()) {
                    top = top - 154;
                }
                if ($(window).width() < 480) {
                    top = left = undefined;
                }
                var index=Layer.confirm(__('Are you sure you want to delete this item?'),
                    {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true},
                    function () {
                    	var options = $(that).attr("href");
                    	if($(that).hasClass('btn-destroy')){ //批量销毁
                    		var ids = Table.api.selectedids(table);
			            	options = {url: $(this).attr("href"), data: { ids: ids}};
                    	}
                        Fast.api.ajax($(that).attr("href"), function () {
                            Layer.close(index);
                            table.bootstrapTable('refresh');
                        });
                    });
                return false;
            });
            //全部恢复、批量/单个恢复
            $(document).on('click', '.btn-restoreall,.btn-restoreit,.btn-restore', function (e) {
            	var options = $(this).attr("href");
                if($(that).hasClass('btn-restore')){ //批量恢复
            		var ids = Table.api.selectedids(table);
                	options = {url: $(this).attr("href"), data: {ids: ids}};
                }
                Fast.api.ajax($(this).attr("href"), function () {
                    table.bootstrapTable('refresh');
                });
                return false;
            });
        },
        add: function () {
            //$("form#add-form").data("validator-options", {ignore: ':hidden'});
            
            $(document).on("change", "select[name='row[site_id]']", function () {
                siteid=$(this).val();
                /*
                $("#c-channel_id option:selected").prop("selected", false);
                $("#c-channel_id option").addClass("hide");
                $("#c-channel_id option[data-siteid='" + $(that).val() + "']").removeClass("hide");

                try{
                    $("#c-channel_id").selectpicker("refresh");
                }catch(e){}
                $('#c-channel_id').trigger('change');

                Fast.api.ajax({url: 'posts/sites/get_site_langs', data: {"lang": $(that).val()}}, function (data) {
                    $("#language_choose").html(data.html);
                    Form.api.bindevent($("#language_choose"));
                    return false;
                });
                */
               
                $pid = $('#c-channel_id');

                Fast.api.ajax({url: 'posts/sites/get_site_info', data: {"site_id": siteid}}, function (x,ret) {
                	if(ret.code=="1"){
                		$pid.empty();
                		$.each(ret.data.list, function(i,k){
                			$pid.append("<option value='" + ret.data.list[i].id + "' "+(ret.data.list[i].disabled==1?'disabled':'')+">"+ 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;
                });

                /*
                var ml = $('option:selected', this).data('lang');
                if(ml==undefined) {
                    $('input[name="row[lang]"]').prop('disabled', false).closest('label').show();
                    return false;
                }

                $('input[name="row[lang]"]').prop('disabled', true).closest('label').hide();
                $.each(ml.split(','), function(key,value){
                    $('input[name="row[lang]"][value="'+value+'"]').prop('disabled', false).closest('label').show();
                });
                */
            });
            
            $(document).on("change", "select[name='row[channel_id]']", function () {
                var model = $('option:selected',this).data('model');
                if($('input[name="row[type]"]').val()!=model) {
                    Fast.api.ajax({url: 'posts/archives/get_model_fields', data: {model: model}}, function (data) {
                        $("#extra").html(data.html);
                        Form.api.bindevent($("#extra"));
                        return false;
                    });
                }
                $('input[name="row[type]"]').val(model);
            });
            
            Controller.edit();
            //if($('#c-site_id').size()>0) $('#c-site_id').trigger('change');
            $("select[name='row[channel_id]']").trigger('change');
        },
        edit: function () {
        	$("form").data("validator-options", {ignore: ':hidden'});

            $.validator.config({
                rules: {
                    diyname: function (element) {
                        if (element.value.toString().match(/^\d+$/)) {
                            return __('Can not be digital');
                        }
                        return $.ajax({
                            url: 'posts/archives/check_element_available',
                            type: 'POST',
                            data: {name: element.name, value: element.value},
                            dataType: 'json'
                        });
                    }
                }
            });
            
            
            $(document).on("click", ".fieldlist .btn-append", function () {
                var rel = parseInt($(this).closest("dl").attr("rel")) + 1;
                var name = $(this).closest("dl").data("name");
                var objID = name.replace('[', '_').replace(']','_') +  rel;
                $(this).closest("dl").attr("rel", rel);
                var appendHtml = '<dd class="form-inline">';
                appendHtml += '<input type="hidden" name="' + name + '['+rel+'][id]" id="pa-' + objID + 'i' + '" value="" />';
                appendHtml += '<input type="text" name="' + name + '['+rel+'][title]" id="pa-' + objID + 't'+ '"  class="form-control" value="" size="23" /> ';
                appendHtml += '<input type="text" name="' + name + '['+rel+'][url]" id="pa-' + objID  + '" class="form-control" size="10"  /> ';
                appendHtml += '<span><button type="button" id="plupload-' + objID  + '" class="btn btn-danger plupload" data-input-id="pa-' + objID  + '" data-attach-id="pa-' + objID + 'i'  + '" data-title-id="pa-' + objID + 't'+ '" data-mimetype="*/*" data-multiple="false" data-upload-success="productattachcallback"><i class="fa fa-upload"></i> ' + __('Upload') + '</button></span> ';
                appendHtml += '<span><button type="button" id="fachoose-' + objID  + '" class="btn btn-primary fachoose" data-input-id="pa-' + objID  + '" data-attach-id="pa-' + objID + 'i'  + '" data-title-id="pa-' + objID + 't'+ '" data-mimetype="*/*" data-multiple="false"><i class="fa fa-list"></i> ' + __('Choose') + '</button></span> ';
                appendHtml += '<span class="btn btn-sm btn-danger btn-remove"><i class="fa fa-times"></i></span></dd>';
                $(appendHtml).insertBefore($(this).parent());
                Controller.api.bindevent();
            });
            $(document).on("click", ".fieldlist dd .btn-remove", function () {
                var rel = parseInt($(this).closest("dl").attr("rel"));
                rel = rel>1? rel-1: 0;
                $(this).closest("dl").attr("rel", rel);
                $(this).parent().off().remove();
            });
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"), function () {
                    var obj = top.window.$("#nav ul li.active");
                    top.window.Toastr.success(__('Operation completed'));
                    top.window.$(".sidebar-menu a[url$='/posts/archives'][addtabs]").click();
                    top.window.$(".sidebar-menu a[url$='/posts/archives'][addtabs]").dblclick();
                    obj.find(".fa-remove").trigger("click");
                });
            }
        }
    };
    return Controller;
});