define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template'], function ($, undefined, Backend, Table, Form, Template) {
    var Page=1;
    var Controller = {
        index: function () {
            require(['bootstrap-select', 'bootstrap-select-lang']);
            var maintable = [];
            var renderselect = function (select, data, subtext) {
                var html = [];
                var multiple = $(select).attr('id');
                if( multiple === "field_del"){
                    html.push("<option data-subtext='若使用软删除，请选择标识字段' value='-1'>硬删除</option>");
                }
                for (var i = 0; i < data.length; i++) {
                    html.push("<option data-subtext='" + subtext[i] + "' value='" + data[i] + "'>" + data[i] + "</option>");
                }
                $(select).html(html.join(""));
                select.trigger("change");
                if (select.data("selectpicker")) {
                    select.selectpicker('refresh');
                }
                return select;
            };

            renderselect($("#table"), Config.tableList, Config.tableComment);


            $("select[name=table] option").each(function () {
                maintable.push($(this).val());
            });

            $(document).on('change', "select[name='table']", function () {
                var that = this;
                Fast.api.ajax({
                    url: "distinct/index/get_field_list",
                    data: { table: $(that).val() },
                }, function (data, ret) {
                    renderselect($("#fields"), data.fieldlist, data.comment);
                    renderselect($("#field_del"), data.fieldlist, data.comment);
                    return false;
                });
                return false;
            });

            $(document).on('click', ".btn-select,.btn-refresh", function () {
                var form = $("form[role='form']");
                var f =  $('#fields').find('option:selected');
                if(f.length===0) return;
                Fast.api.ajax({
                    url: "distinct/index/select",
                    data: form.serialize()
                }, function (res, ret) {
                    var data = res.data;
                    var showcolums = res.fields;
                    var col = [                        
                        {
                            title:'序号',
                            filed:'id',
                            formatter:function(value,row,index){
                                return index+1;
                            }
                    }];
                    for (var key in showcolums) {
                        tmp = {
                            field: key,
                            title: res.fields[key],
                        }
                        col.push(tmp);
                    }

                    var table = document.createElement("table");
                    table.id = "table_r";
                    table.className = "table table-striped table-bordered table-hover table-nowrap";
                    $('#toolbar').show();
                    var toolbar = document.getElementById('toolbar').cloneNode(true);
                    toolbar.className = "toolbar";
                    var div = $('#pre_tb')[0];
                    div.innerHTML = "";
                    div.appendChild(toolbar);
                    div.appendChild(table);
                    $('#toolbar').hide();

                    Table.api.init();
                    table = $('#table_r');

                    var operate = {
                        field: 'operate', title: __('Operate'), table: table, events: Controller.api.events.operate,
                        formatter: Table.api.formatter.operate,
                        buttons: [{
                            name: 'del_min',
                            text: '保小',
                            icon: 'fa fa-trash',
                            classname: 'btn btn-warning btn-xs del_min'
                        },
                        {
                            name: 'del_max',
                            text: '保大',
                            icon: 'fa fa-trash',
                            classname: 'btn btn-warning btn-xs del_max',
                        }
                        ]
                    };
                    col.push(operate);
                    table.bootstrapTable({
                        columns: [col],
                        sidePagination: 'client',
                        pageNumber:Page,
                        data: data,
                    });
                    Table.api.bindevent(table);
                    $('.prebox').show();
                    Page =1;
                    return false;
                });
            });
            $(document).on('click', ".btn-del-min", function () {
                var form = $("form[role='form']");
                layer.confirm('即将对全部数据执行去重操作，保留id最小的数据，执行后无法恢复，确认操作吗？', function () {
                    layer.closeAll();
                    Fast.api.ajax({
                        url: "distinct/index/delete?type=MIN",
                        data: form.serialize(),
                    }, function (data, ret) {
                        $('.prebox').hide();
                    });
                })

            });
            $(document).on('click', ".btn-del-max", function () {
                var form = $("form[role='form']");
                layer.confirm('即将对全部数据执行去重操作，保留id最大的数据，执行后无法恢复，确认操作吗？', function () {
                    layer.closeAll();
                    Fast.api.ajax({
                        url: "distinct/index/delete?type=MAX",
                        data: form.serialize(),
                    }, function (data, ret) {
                        $('.prebox').hide();
                    });
                });
            });

            $("select[name='table']").trigger("change");

            var tips;
            $('i.tooltip-icon').on({
                mouseenter:function(){
                    var that = this;
                    tips =layer.tips("<span style='color:#000;'>说明：<br>默认为硬删除<br>当选择软删除后，查重结果将会排除已被软删除的数据<br>之后的删除操作将会对软删除字段赋值删除时的时间戳<br>软删除字段类型为int且默认值为null</span>",that,{tips:[2,'#fff'],time:0,area: 'auto',maxWidth:500});
                },
                mouseleave:function(){
                    layer.close(tips);
                }
            });
            
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            events: {
                operate: {
                    'click .del_min': function (e, value, row, index) {
                        e.stopPropagation();
                        layer.confirm('即将对该条数据执行去重操作，保留id最小的数据，执行后无法恢复，确认操作吗？', function () {
                            layer.closeAll();
                            Fast.api.ajax({
                                url: "distinct/index/delsinger?type=MIN",
                                data: {
                                    table:$('#table').val(),
                                    row:row,
                                    field_del:$("#field_del").val()
                                },
                            }, function (data, ret) {
                                $("tr[data-index="+index+"]").remove();
                                Page = $("#table_r").bootstrapTable("getOptions").pageNumber;
                                $('.btn-select').trigger('click');
                            });
                        })
                    },
                    'click .del_max': function (e, value, row, index) {
                        e.stopPropagation();
                        layer.confirm('即将对该条数据执行去重操作，保留id最大的数据，执行后无法恢复，确认操作吗？', function () {
                            layer.closeAll();
                            Fast.api.ajax({
                                url: "distinct/index/delsinger?type=MAX",
                                data: {
                                    table:$('#table').val(),
                                    row:row,
                                    field_del:$("#field_del").val()
                                },
                            }, function (data, ret) {
                                $("tr[data-index="+index+"]").remove();
                                Page = $("#table_r").bootstrapTable("getOptions").pageNumber;
                                $('.btn-select').trigger('click');
                            });
                        })
                    }
                }
            }
        }
    };
    return Controller;
});
