var gridManager = null;

$(document).ready(function () {
    initialize();
    loadStatsIndicatorsDetailListGrid();
    bindEvent();
});
function initialize(){
    let isDetailPage = ($("#isDetailPage").val() === "true");
    if (isDetailPage) {
        $("#jobPageTop").hide();
    }
}

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('#statsIndicatorsDetailGrid');
            DataUtil.delSelectedRows({
                action: 'sapStatsIndicators/deleteStatsIndicatorDetails.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'statsIndicatorsDetailId',
                onSuccess: function () {
                    reloadGrid();
                }
            });
        }
    });
    gridManager = UICtrl.grid("#statsIndicatorsDetailGrid", {
        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: 10,
        usePager: true,
        parms:{statsIndicatorsId:getId()},
        toolbar: toolbarOptions,
        enabledEdit: true,
        width: "100%",
        height: "100%",
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        onDblClickRow: function (data, rowindex, rowobj) {
            doView(data.statsIndicatorsDetailId);
        }
    });
    UICtrl.setSearchAreaToggle(gridManager);
}

/**
 * 流程引擎回调设置打样的id
 * @param value 打样申请的id
 */
function setId(id) {
    $("#id").val(id);
    var _grid=UICtrl.getGridManager('#statsIndicatorsDetailGrid');
    _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('#statsIndicatorsDetailGrid');
    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;
}

//获取最新子序号（维护实体的标识）
function getZlenr(){
    let result =gridManager.getData();
    let zlenr="1";
    if(result.length>0){
        //获取上一个节点的子序值
        let wornNo= parseInt(result[result.length-1]["zlenr"], 10);
        zlenr=((wornNo + 1)).slice(-3);
    }
    return zlenr;
}