var gridManager = null;

$(document).ready(function () {
    initialize();
    loadStatsIndicatorsDetailListGrid();
    bindEvent();
});
function initialize(){
    UICtrl.layout("#layout", {leftWidth: 3});
}

function bindEvent(){
    var code = $("#submitForm #billCode").val();
    $("#bltxt").val(code);

    //所属系统选择
    // $('#kokrs').orgTree({
    //     searchType: 'bsn', searchName: 'pmHierarchy',
    //
    //     onChange: function (value,data) {
    //         $('#kokrs').val(data.code);
    //     }
    // });
    $('#kokrs').treebox({
        name:'sapOrgDpt',
        searchName:'sapOrgDpt',
        searchType:'bsn',
        hasSearch :true,
        minWidth:500,
        param:{
            treeViewMappingType:"bsn",
            parentId:'ogn'
        },
        back:{
            //text:$('#queryDataManageName')
        },
        onChange:function(node,data){
            $('#kokrs').val(data.id);
        }
    });
}

function loadStatsIndicatorsDetailListGrid() {
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: function () {
            UICtrl.addGridRow(gridManager,{ zlenr: gridManager.getData().length + 1 });
        },
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#maingrid');
            DataUtil.delSelectedRows({
                action: 'sapStatsIndicators/deleteStatsIndicatorDetails.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'statsIndicatorsDetailId',
                onSuccess: function () {
                    reloadGrid();
                }
            });
        },
        impExcelDataHandler:{id:'impExcelData',img:'fa-table',text:'导入数据',click:impExcelDataHandler},
    });
    gridManager = UICtrl.grid("#maingrid", {
        columns: [
            {
                display: "行号", name: "zlenr", width: 140, minWidth: 60, type: "string", align: "left",
                editor: { type: 'spinner', min: 1, max: 100, mask: 'nnn'}
            },
            {
                display: "成本中心", name: "kostl", width: 140, minWidth: 60, type: "string", align: "left",
                editor: {
                    required: false, type: "select",
                    data: {
                        type: 'system',
                        name: "dictionary",
                        getParam: function (item) {
                            return {fieldName: "KOSTL"}
                        },
                        back: {
                            KOSTL: "kostl",
                            null:"aufnr"
                        }
                    },
                }
            },
            {
                display: "订单", name: "aufnr", width: 120, minWidth: 60, type: "string", align: "left",
                editor: {
                    required: false, type: "text",
                    /*data: {
                        type: 'system',
                        name: "sapMaterialSelect",
                        back: {
                             null:"kostl",
                            materialId:"aufnr"
                        }
                    },*/
                }
            },
            {
                display: "统计指标", name: "stagr", width: 120, minWidth: 60, type: "string", align: "left",
                editor: {
                    required: true, type: "select",
                    data: {
                        type: 'system',
                        name: "dictionary",
                        getParam: function (item) {
                            return {fieldName: "STAGR"}
                        },
                        back: {
                            STAGR: "stagr"
                        }
                    },
                }
            },
            {
                display: "统计指标数量", name: "mbgbtr", width: 140, minWidth: 60, type: "string", align: "left",
                editor: {
                    required: true,
                    type: 'text',
                    mask: 'nnnnnnnn'
                }
            },
            {
                display: "行文本", name: "sgtxt", width: 140, minWidth: 60, type: "string", align: "left",
                editor: {
                    required: false,
                    type: 'text'
                }
            }
        ],
        dataAction: "server",
        url: web_app.name + '/sapStatsIndicators/slicedStatsIndicatorsDetailList.ajax',
        pageSize: 100,
        usePager: true,
        parms:{statsIndicatorsId:getId()},
        toolbar: toolbarOptions,
        enabledEdit: true,
        width: "100%",
        height: "100%",
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true
    });
    UICtrl.setSearchAreaToggle(gridManager);
}

/**
 * 流程引擎回调设置打样的id
 * @param value 打样申请的id
 */
function setId(id) {
    $("#id").val(id);
    var _grid=UICtrl.getGridManager('#maingrid');
    _grid.options.parms.statsIndicatorsId = id;
}

/**
 * 流程引擎获取打样申请id的回掉方法。
 * @return 打样申请的id
 */
function getId() {
    return $("#id").val() || "";
}

function reloadGrid() {
    gridManager.loadData();
}

function getExtendedData(processAction) {
//回退、打回、转交时，不需要验证必填项是否已经填写；
    if (processAction == ProcessAction.BACK
        || processAction == ProcessAction.REPLENISH
        || processAction == ProcessAction.TRANSMIT) {
//不验证
        $('#submitForm').attr('check', false);
    }
    var extendedData = {};
    var _grid = UICtrl.getGridManager('#maingrid');
    if (_grid) {
        var datas = DataUtil.getGridData({
            gridManager: _grid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }else if (datas.some(item => item.kostl === "" && item.aufnr === "")){
            const nullItems = datas.filter(item => item.kostl === "" && item.aufnr === "").map(item => item.zlenr);
            Public.tip("行号[" + nullItems.join(",") + "]成本中心or订单只能选择一栏填写");
            return false;
        }else if (datas.some(item => item.kostl != "" && item.aufnr != "")){
            const nullItems = datas.filter(item => item.kostl != "" && item.aufnr != "").map(item => item.zlenr);
            Public.tip("行号[" + nullItems.join(",") + "]成本中心or订单只能选择一栏填写");
            return false;
        }

        extendedData.statsIndicatorsDetail = Public.encodeJSONURI(datas);
    }
    return extendedData;
}


//从EXCEL导入数据
function impExcelDataHandler(){
    ExcelImpManager.showImpDialog('导入', 'sapStatsIndicatorsDetail', Public.getUUID(), saveUpLoadGrid);
}

function saveUpLoadGrid() {
    var batchNumber=$('#batchNumber').val();
    Public.ajax(web_app.name + '/sapStatsIndicators/importExcelData.ajax'
        , {batchNumber: batchNumber}, function (data) {
            for (var row=0;row<data.length;row++) {
                UICtrl.addGridRow(gridManager,{
                    zlenr:data[row].zlenr,
                    kostl:data[row].kostl,
                    aufnr:data[row].aufnr,
                    stagr:data[row].stagr,
                    mbgbtr:data[row].mbgbtr,
                    sgtxt:data[row].sgtxt,
                });
            }
        });
}