(function($){
    function buildMenu(target){
        var state = $(target).data('datagrid');
        if (!state.columnMenu){
            state.columnMenu = $('<div></div>').appendTo('body');
            state.columnMenu.menu({
                onClick: function(item){
                    if (item.iconCls == 'tree-checkbox1'){
                        $(target).datagrid('hideColumn', item.name);
                        $(this).menu('setIcon', {
                            target: item.target,
                            iconCls: 'tree-checkbox0'
                        });
                    } else {
                        $(target).datagrid('showColumn', item.name);
                        $(this).menu('setIcon', {
                            target: item.target,
                            iconCls: 'tree-checkbox1'
                        });
                    }
                }
            })
            var fields = $(target).datagrid('getColumnFields',true).concat($(target).datagrid('getColumnFields',false));
            for(var i=0; i<fields.length; i++){
                var field = fields[i];
                var col = $(target).datagrid('getColumnOption', field);
                state.columnMenu.menu('appendItem', {
                    text: col.title,
                    name: field,
                    iconCls: 'tree-checkbox1'
                });
            }
        }
        return state.columnMenu;
    }
    $.extend($.fn.datagrid.methods, {
        columnMenu: function(jq){
            return buildMenu(jq[0]);
        }
    });
})(jQuery);
//日历插件的修改
$.fn.datebox.defaults.formatter = function(date){
    var y = date.getFullYear();
    var m = (date.getMonth()+1 >= 10) ? (date.getMonth()+1) : ('0'+(date.getMonth()+1));
    var d = date.getDate() >= 10 ? date.getDate() : '0'+date.getDate();
    return y+'-'+m+'-'+d;
}
$.fn.datebox.defaults.parser = function(s){
    var t = Date.parse(s);
    if (!isNaN(t)){
        return new Date(t);
    } else {
        return new Date();
    }
}
var dmWidth = parseInt(localStorage.getItem('dm')) || 100,
    rqWidth = parseInt(localStorage.getItem('rq')) || 100,
    ywlbWidth = parseInt(localStorage.getItem('ywlb')) || 100,
    czmcWidth = parseInt(localStorage.getItem('czmc')) || 100,
    jeWidth = parseInt(localStorage.getItem('je')) || 100,
    shbzWidth = parseInt(localStorage.getItem('shbz')) || 50,
    shrqWidth = parseInt(localStorage.getItem('shrq')) || 100,
    shyWidth = parseInt(localStorage.getItem('shy')) || 100,
    thbzWidth = parseInt(localStorage.getItem('thbz')) || 50,
    thjeWidth = parseInt(localStorage.getItem('thje')) || 100,
    thrqWidth = parseInt(localStorage.getItem('thrq')) || 100,
    noteWidth = parseInt(localStorage.getItem('note')) || 100,
    dragEvent = [],nextEIndex = 0,wrapFlag = localStorage.getItem('wrapFlag') == 1 ? true : false,
    editIndex = undefined
    th = localStorage.getItem('th') ? JSON.parse(localStorage.getItem('th')) : [
        {field:'dm',title:'单号',resizable:true,width:dmWidth,sortable:true,},
        {field:'rq',title:'日期',resizable:true,width:rqWidth,sortable:true,},
        {field:'ywlb',title:'类别',resizable:true,width:ywlbWidth,sortable:true,editor:{type:'text',options:{}}},
        {field:'czmc',title:'车主',resizable:true,width:czmcWidth,sortable:true,editor:{type:'text',options:{}}},
        {field:'je',title:'金额',resizable:true,width:jeWidth,sortable:true,
            formatter:function(value,a,b){
                if(value !== '.00'){
                    return value
                }else{
                    return '0.00'
                }
            },editor:{type:'text',options:{}}},
        {field:'shbz',title:'审核',resizable:true,width:shbzWidth,align:'center',sortable:true,
            formatter:function(value,row,index){
                if(value == 0){
                    return `<input type="checkbox" class="easyui-checkbox" name="shbz" disabled>`
                }else{
                    return `<input type="checkbox" class="easyui-checkbox" name="shbz" disabled checked>`
                }
            },editor:{type:'text',options:{}}},
        {field:'shrq',title:'审核日期',resizable:true,width:shrqWidth,sortable:true,editor:{type:'text',options:{}}},
        {field:'shy',title:'审核员',resizable:true,width:shyWidth,sortable:true,editor:{type:'text',options:{}}},
        {field:'thbz',title:'退还',resizable:true,width:thbzWidth,align:'center',sortable:true,
            formatter:function(value,row,index){
                if(value == 0){
                    return `<input type="checkbox" class="easyui-checkbox" name="thbz" disabled>`
                }else{
                    return `<input type="checkbox" class="easyui-checkbox" name="thbz" disabled checked>`
                }
            },editor:{type:'text',options:{}}},
        {field:'thje',title:'退还金额',resizable:true,width:thjeWidth,sortable:true,
            formatter:function(value,a,b){
                if(value !== '.00'){
                    return value
                }else{
                    return '0.00'
                }
            },editor:{type:'text',options:{}}},
        {field:'thrq',title:'退还日期',resizable:true,width:thrqWidth,sortable:true,editor:{type:'text',options:{}}},
        {field:'note',title:'备注',resizable:true,width:noteWidth,sortable:true,editor:{type:'text',options:{}}},
    ]
$(function(){
    $('#datebox1').datebox({
        label:'时间',
        labelAlign:'right',
        width:250,
        height:30,
        value:'today'
    })
    $('#datebox2').datebox({
        label:'至',
        labelAlign:'center',
        editable:false,
        width:250,
        height:30,
        value:'today',
    })
    var dg = $("#table").datagrid({
        fit:true,
        // fitColumns:true,
        columns:[th],
        autoRowHeight:false,
        method:'get',
        idField:'dm',
        toolbar:'#ts',
        url:'/car/clgk.carsales/cheliangyajinchaxun',
        pagination:true,
        rownumbers:true,
        singleSelect:true,
        pageNumber:1,
        pageSize:30,
        nowrap:wrapFlag,
        sortName:'rq',
        sortOrder:'desc',
        showHeader:true,
        width:'100%',
        height:'auto',
        showFooter:true,
        filterBtnIconCls:'icon-filter',
        queryParams:{rq1:$("#datebox1").datebox('getText').replace(/-/g, ""),rq2:$("#datebox2").datebox('getText').replace(/-/g, "")},
        remoteFilter:true,
        showFilterBar:true,
        clickToEdit:false,
        dblclickToEdit:true,
        onBeforeLoad:function (param) {
            var firstLoad = $(this).attr("firstLoad");
            if (firstLoad == "false" || typeof (firstLoad) == "undefined"){
                $(this).attr("firstLoad","true");
                return false;
            }
            return true;
        },
        onHeaderContextMenu: function(e, field){
            e.preventDefault();
            $(this).datagrid('columnMenu').menu('show', {
                left:e.pageX,
                top:e.pageY
            });
        },
        onResizeColumn:function(a,b){
            if(!localStorage.getItem('th')){
                localStorage.setItem(a,b)
            }else{
                var th = JSON.parse(localStorage.getItem('th'))
                for(var i in th){
                    if(th[i].field == a){
                        th[i].width = b
                        break;
                    }
                }
                localStorage.setItem('th',JSON.stringify(th))
            }
        },
        onRowContextMenu:onRowContextMenu,
        onBeforeDragColumn:function(a,b,c){
            // console.log(a,b,c,'拖动之前')?\
            // dragEvent = a
        },
        onStartDragColumn:function(a,b,c){
            // console.log(a,b,c,'开始拖动时')
        },
        onStopDragColumn:function(a,b,c){
            // console.log(a,b,c,'停止拖动时')
        },
        onBeforeDropColumn:function(a,b,c){
            // console.log(a,b,c,'在删除列之前触发')
        },
        onDropColumn:function(a,b,c,d){
            // console.log(a,b,c)
            for(var i=0;i<th.length;i++){
                if(th[i].field == b){
                    dragEvent = th[i]
                    th.splice(i,1)
                    break
                }
            }
            if(c == 'before'){
                for(var j=0;j<th.length;j++){
                    if(th[j].field == a){
                        nextEIndex = j - 1
                        break;
                    }
                }
            }else{
                for(var j=0;j<th.length;j++){
                    if(th[j].field == a){
                        nextEIndex = j
                        break;
                    }
                }
            }
            var handle = []
            if(nextEIndex == -1){
                handle.push(dragEvent)
                for(var k=0;k<th.length;k++){
                    handle.push(th[k])
                }
            }else{
                for(var k=0;k<th.length;k++){
                    handle.push(th[k])
                    if(k == nextEIndex){
                        handle.push(dragEvent)
                    }
                }
            }
            th = handle
            localStorage.setItem('th',JSON.stringify(th))
        },
        onDblClickRow:function(rowIndex,rowData){
            // console.log(rowIndex,rowData)
            $("#box").datagrid('beginEdit',rowIndex)
        },onAfterEdit : function(rowIndex,rowDate,changes){
            console.log(rowIndex,rowDate,changes)
        },
        onDblClickCell:function(index,field,value){
            $(this).datagrid('beginEdit', index);
            var ed = $(this).datagrid('getEditor', {index:index,field:field});
            $(ed.target).focus();
        }
    }).datagrid('columnMoving')
    dg.datagrid('enableFilter', [
         {
             field:'dm',
             type:'textbox',
             options:{precision:0},
             op:['equal','contains']
         },
         {
             field:'rq',
             type:'numberbox',
             options:{precision:0},
             op:['equal','notequal','less','lessorequal','greater','greaterorequal']
         },
         {
             field:'ywlb',
             type:'combobox',
             limitToList:true,
             options:{
                 panelHeight:'auto',
                 url:'/car/clgk.carsales/qufenzu?mk=ywlb',
                 // data:[{value:'',text:'待定'},{value:'1',text:'是'},{value:'0',text:'否'}],
                 onChange:function(value){
                     if (value == ''){
                         dg.datagrid('removeFilterRule', 'ywlb');
                     } else {
                         dg.datagrid('addFilterRule', {
                             field: 'ywlb',
                             op: 'equal',
                             value: value
                         });
                     }
                     dg.datagrid('doFilter');
                     // console.log(value)
                 }
             }
         },
         {
             field:'czmc',
             type:'textbox',
             op:['equal','notequal','less','lessorequal','greater','greaterorequal']
         },
         {
             field:'je',
             type:'numberbox',
             options:{precision:2},
             op:['equal','notequal','less','lessorequal','greater','greaterorequal']
         },
         {
             field:'shbz',
             type:'combobox',
             options:{
                 panelHeight:'auto',
                 data:[{value:'',text:'全部'},{value:'1',text:'已审核'},{value:'0',text:'未审核'}],
                 onChange:function(value){
                     if (value == ''){
                         dg.datagrid('removeFilterRule', 'shbz');
                     } else {
                         dg.datagrid('addFilterRule', {
                             field: 'shbz',
                             op: 'equal',
                             value: value
                         });
                     }
                     dg.datagrid('doFilter');
                     // console.log(value)
                 }
             }
         },
         {
             field:'shrq',
             type:'numberbox',
             op:['equal','notequal','less','lessorequal','greater','greaterorequal']
         },
         {
             field:'shy',
             type:'combobox',
             options:{
                panelHeight:'auto',
                 // data:[{value:'',text:'待定'},{value:'1',text:'是'},{value:'0',text:'否'}],
                 url:'/car/clgk.carsales/qufenzu?mk=shy',
                 onChange:function(value){
                     if (value == ''){
                         dg.datagrid('removeFilterRule', 'je');
                     } else {
                         dg.datagrid('addFilterRule', {
                             field: 'je',
                             op: 'equal',
                             value: value
                         });
                     }
                     dg.datagrid('doFilter');
                     // console.log(value)
                 }
             }
         },
         {
             field:'thbz',
             type:'combobox',
             options:{
                 panelHeight:'auto',
                 data:[{value:'',text:'全部'},{value:'1',text:'已退还'},{value:'0',text:'未退还'}],
                 onChange:function(value){
                     if (value == ''){
                         dg.datagrid('removeFilterRule', 'thbz');
                     } else {
                         dg.datagrid('addFilterRule', {
                             field: 'thbz',
                             op: 'equal',
                             value: value
                         });
                     }
                     dg.datagrid('doFilter');
                 }
             }
         },
         {
             field:'thje',
             type:'numberbox',
             options:{precision:2},
             op:['equal','notequal','less','lessorequal','greater','greaterorequal']
         },
         {
             field:'thrq',
             type:'numberbox',
             op:['equal','notequal','less','lessorequal','greater','greaterorequal']
         },
         {
             field:'note',
             type:'textbox',
             op:['equal','contains']
         },
     ])
    //查询数据
    $(".search").click(function(){
        var queryParams = $('#table').datagrid('options').queryParams;
        // console.log(queryParams)
        queryParams.rq1 = $("#datebox1").datebox('getText').replace(/-/g, "")
        queryParams.rq2 = $("#datebox2").datebox('getText').replace(/-/g, "")
        $("#table").datagrid('load')
    })
    //编辑一行
    $("#editrow").click(function(){
        if(editIndex == undefined){var row = $("#table").datagrid('getSelections')
            var rowIndex = $("#table").datagrid("getRowIndex",row[0])
            $("#table").datagrid('beginEdit',rowIndex)
            editIndex = rowIndex
            var row = $("#table").datagrid('getSelections')
            var rowIndex = $("#table").datagrid("getRowIndex",row[0])
            $("#table").datagrid('beginEdit',rowIndex)
            editIndex = rowIndex
        }else{
            $("#table").datagrid("endEdit",editIndex)
            var row = $("#table").datagrid('getSelections')
            var rowIndex = $("#table").datagrid("getRowIndex",row[0])
            $("#table").datagrid('beginEdit',rowIndex)
            editIndex = rowIndex
        }
    })
    //保存编辑的行
    $("#saveRow").click(function(){
    })
    //自动行高
    $("#autoHeight").click(function(){
        if($("#table").datagrid("options").nowrap){
            localStorage.setItem('wrapFlag','0')
        }else{
            localStorage.setItem('wrapFlag','1')
        }
        $('#table').datagrid('options').nowrap = !$('#table').datagrid('options').nowrap
        $("#table").datagrid('reload')
    })
    $("#initial").click(function(){
        localStorage.clear()
        $("#table").datagrid('getColumnOption', 'dm').width = 100
        $("#table").datagrid('getColumnOption', 'rq').width = 100
        $("#table").datagrid('getColumnOption', 'ywlb').width = 100
        $("#table").datagrid('getColumnOption', 'czmc').width = 100
        $("#table").datagrid('getColumnOption', 'je').width = 100
        $("#table").datagrid('getColumnOption', 'shbz').width = 50
        $("#table").datagrid('getColumnOption', 'shrq').width = 100
        $("#table").datagrid('getColumnOption', 'shy').width = 100
        $("#table").datagrid('getColumnOption', 'thbz').width = 50
        $("#table").datagrid('getColumnOption', 'thje').width = 100
        $("#table").datagrid('getColumnOption', 'thrq').width = 100
        $("#table").datagrid('getColumnOption', 'note').width = 100
        $("#table").datagrid('options').nowrap = true
        $("#table").datagrid()
    })
})
function onRowContextMenu(e, rowIndex, rowData) {
    e.preventDefault();
    $(this).datagrid('selectRow', rowIndex); //选中当前行
    $('#mm').menu('show', {
        left: e.pageX,
        top: e.pageY
    });
}