var gridManager = null;
var orderItemGridManager = null;
var materialGridManager = null;
var gridManager = null;
var  canEdit=true;

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

/**
 * 流程引擎回调设置打样的id
 * @param value 打样申请的id
 */
function setId(bizId) {
    $("#id").val(bizId);
    var _grid = UICtrl.getGridManager('#orderItemGrid');
    _grid.options.parms.processOutsourceId = bizId;
    var _grid3 = UICtrl.getGridManager('#materialGrid');
    _grid3.options.parms.processOutsourceId = bizId;
    orderItemGridManager.loadData();
    materialGridManager.loadData();
}

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

// 加载订单行项目表格
function loadOrderItemGrid() {
    var toolbarOptions = null;
    toolbarOptions = UICtrl.getDefaultToolbarOptions({
        // 添加一行表格
        addHandler: function () {
            UICtrl.showAjaxDialog({
                title: '选择工单',
                height: 400,
                width: 1600,
                url: web_app.name + '/processOutsource/showAddAufnrDetail.load',
                ok: function(d){
                    var _self = this;
                    var rows = gridManager.getSelectedRows();
                    for (var i = 0 ;i<rows.length;i++){
                        var row = rows[i];
                        var dates = orderItemGridManager.getData();
                        if (dates != null && dates.length > 0){
                            for (let j = 0; j < dates.length; j++) {
                                var data = dates[j];
                                if (data.aufnr == row.AUFNR){
                                    Public.tip("生产单号："+row.AUFNR+" 已选择，请取消勾选！");
                                    return false;
                                }
                            }
                        }
                        orderItemGridManager.addRow({
                            aufnr: row.AUFNR,
                            wempf: row.VORNR,
                            txz01: row.LTXA1,
                            productCode: row.PLNBEZ,
                            productName: row.MAKTX,
                            productType: row.MTART,
                            productTypeName: row.MTBEZ,
                            meins: row.MSEH3,
                            //meinsName: row.MSEHL,
                            meinsName: row.MSEH3,
                            menge: row.GAMNG,
                            printLoss: row.ZLOSSC,
                            // 行号加一
                            sequence: (orderItemGridManager.getData().length + 1),
                            kpein: 1,
                            waersTextView: "人民币",
                            waers: "CNY"
                        });
                    }
                    _self.close();
                },
            });
            // UICtrl.addGridRow(orderItemGridManager,
            //     {
            //         // 行号加一
            //         sequence: (orderItemGridManager.getData().length + 1),
            //         kpein: 1,
            //         waersTextView: "人民币",
            //         waers: "CNY"
            //
            //     }
            // );
        },
        // 删除
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#orderItemGrid');
            DataUtil.delSelectedRows({
                action: 'processOutsource/deleteProcessOutsourceOrderItem.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    orderItemGridManager.loadData();
                }
            });
        }
    });

    // 表格
    orderItemGridManager = UICtrl.grid("#orderItemGrid", {
        columns: getOrderColumns(),
        dataAction: "server",
        _tableKey: 'processOutsourceItem',
        _local: true,
        url: web_app.name + '/processOutsource/queryProcessOutsourceOrderItems.ajax',
        parms: {processOutsourceId: getId()},
        pageSize: 20,
        usePager: true,
        toolbar: toolbarOptions,
        enabledEdit: true,
        width: "98%",
        height: "300px",
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        onAfterEdit:function (item) {
            if(item.column.name == "lifnrName"){
                Public.ajax(web_app.name + "/processQuotedPrice/findPriceByProductAndProcess.ajax?" +
                    "productCode="+item.record.productCode+
                    "&outProcess="+item.record.wempf+
                    "&number="+item.record.menge+
                    "&lifnr="+item.record.lifnr,
                    {
                    },function (data){
                        orderItemGridManager.updateRow(item.record,{
                            kbetr:data.unitPrice,
                            purchaseMwskzTextView:data.purchaseMwskzTextView,
                            purchaseMwskz:data.purchaseMwskz
                        })
                })
            }
        }
    });
    UICtrl.setSearchAreaToggle(orderItemGridManager);
}

function getOrderColumns(){
    var columns = [];
    columns.push({display: "采购订单", name: "ebeln", width: 120, minWidth: 60, type: "string", align: "left"});
    columns.push({display: "订单行项目号", name: "ebelp", width: 120, minWidth: 60, type: "string", align: "left"});
    columns.push({display: "序号", name: "sequence", width: 50, minWidth: 60, type: "string", align: "left"},);
    columns.push({
        display: "原工单", name: "aufnr", width: 200, minWidth: 60, type: "string", align: "left",
        // editor: {
        //     required: true, type: "select",
        //     data: {
        //         type: 'system',
        //         name: "dictionary",
        //         getParam: function (item) {
        //             return {fieldName: "AUFNR"}
        //         },
        //         back: {
        //             AUFNR: "aufnr",
        //             VORNR: "wempf",
        //             LTXA1: "txz01",
        //             PLNBEZ: "productCode",
        //             MAKTX: "productName",
        //             MTART: "productType",
        //             MTBEZ: "productTypeName",
        //             MSEH3: "meins",
        //             MSEHL: "meinsName",
        //             GAMNG: "menge",
        //             ZLOSSC: "printLoss",
        //         }
        //     }
        // }
    });
    columns.push({
        display: "产品类别", name: "productTypeName", width: 140, minWidth: 60, type: "string", align: "left",
    },);
    columns.push({
        display: "产品编码", name: "productCode", width: 140, minWidth: 60, type: "string", align: "left",
    },);
    columns.push({
        display: "产品名称", name: "productName", width: 200, minWidth: 60, type: "string", align: "left",
    },);
    columns.push({
        display: "工序号", name: "wempf", width: 140, minWidth: 60, type: "string", align: "left",
        editor: {
            required: true, type: "select",
            data: {
                type: 'system',
                name: "selectAufnr",
                getParam: function (item) {
                    return {
                        fieldName: "AUFNR",
                        paramValue: item.aufnr
                    }
                },
                back: {
                    VORNR: "wempf",
                    LTXA1: "txz01",
                    NEXTVORNR: "txz02",
                    MSEHL: "meinsName"
                }
            }
        }
    },);
    columns.push({
        display: "工序描述", name: "txz01", width: 200, minWidth: 60, type: "string", align: "left",
        editor: {
            type: "text", required: true
        }
    },);
    columns.push({
        display: "下道工序", name: "txz02", width: 200, minWidth: 60, type: "string", align: "left",
        editor: {
            type: "text", required: true
        }
    },);
    columns.push({
        display: "补数工单", name: "ablad", width: 140, minWidth: 60, type: "string", align: "left",
        editor: {
            type: "text", required: false
        }
    },);
    columns.push({
        display: "数量", name: "menge", width: 140, minWidth: 60, type: "string", align: "left",
        editor: {
            type: "text", mask: '9999999.999', required: true
        }
    },);
    columns.push({
        display: "LOSS数", name: "printLoss", width: 140, minWidth: 60, type: "string", align: "left",
        editor: {
            type: "text", mask: '9999999.999', required: true
        }
    },);
    columns.push({
        display: "单位", name: "meinsName", width: 140, minWidth: 60, type: "string", align: "left",
        editor: {
            required: true, type: "select",
            data: {
                type: 'system',
                name: "dictionary",
                getParam: function (item) {
                    return {fieldName: "MEINS"}
                },
                back: {
                    MSEH3: "meins",
                    MSEHL: "meinsName",
                }
            }
        }
    },);
    columns.push({
        display: "需求日期", name: "eeind", width: 140, minWidth: 60, type: "date", align: "left",
        editor: {
            type: "date", required: true
        }
    },);
    columns.push({
        display: "存储地点", name: "lgortName", width: 200, minWidth: 60, type: "string", align: "left",
        editor: {
            required: false, type: "select",
            data: {
                type: 'system',
                name: "dictionary",
                getParam: function (item) {
                    return {
                        fieldName: "LGORT",
                        filterValue: $("#werks").val()
                    }
                },
                back: {
                    LGORT: "lgort",
                    LGOBE: "lgortName"
                }
            },
        }
    },);
    if (typeof(getSubProcUnitId) =='function'&&"outer" == getSubProcUnitId()){
        columns.push({
            display: "单价", name: "kbetr", width: 140, minWidth: 60, type: "string", align: "left",
            editor: {
                type: "text", mask: '9999999.999', required: true
            }
        },);
        columns.push({
            display: "定价基数", name: "kpein", width: 140, minWidth: 60, type: "string", align: "left",
            editor: {
                type: "text", mask: '9999999.999', required: true
            }
        },);
        columns.push({
            display: "供应商", name: "lifnrName", width: 200, minWidth: 60, type: "string", align: "left",
            editor: {
                required: true, type: "select",
                data: {
                    type: 'suppliers',
                    name: "selectQuotedSuppliers",
                    getParam: function (item) {
                        return {
                            productCode: item.productCode,
                            outProcess: item.wempf
                        }
                    },
                    back: {
                        supplier: "lifnr",
                        supplierName: "lifnrName",
                    }
                }
            }
        },);
        columns.push({
            display: "币别", name: "waersTextView", width: 140, minWidth: 60, type: "string", align: "left",
            editor: {
                type: 'dictionary',
                data: {name: 'waers'},
                textField: 'waersTextView',
                valueField: 'waers',
                required: true,
                render: function (item) {
                    return item.waersTextView;
                }
            },
        },);
        columns.push({
            display: "税码", name: "purchaseMwskzTextView", width: 140, minWidth: 60, type: "string", align: "left",
            editor: {
                type: 'dictionary',
                data: {name: 'purchaseMwskz'},
                textField: 'purchaseMwskzTextView',
                valueField: 'purchaseMwskz',
                required: true,
                render: function (item) {
                    return item.purchaseMwskzTextView;
                }
            },
        });
    }else {
        columns.push({
            display: "单价", name: "kbetr", width: 140, minWidth: 60, type: "string", align: "left",
        },);
        columns.push({
            display: "定价基数", name: "kpein", width: 140, minWidth: 60, type: "string", align: "left",
        },);
        columns.push({
            display: "供应商", name: "lifnrName", width: 200, minWidth: 60, type: "string", align: "left",
        },);
        columns.push({
            display: "币别", name: "waersTextView", width: 140, minWidth: 60, type: "string", align: "left",
        },);
        columns.push({
            display: "税码", name: "purchaseMwskzTextView", width: 140, minWidth: 60, type: "string", align: "left",
        });
    }
    return columns;
}

// 加载组件信息表格
function loadMaterialGrid() {
    var toolbarOptions = null;
    toolbarOptions = UICtrl.getDefaultToolbarOptions({
        // 添加一行表格
        addHandler: function () {UICtrl.addGridRow(materialGridManager)},
        // 删除
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#materialGrid');
            DataUtil.delSelectedRows({
                action: 'processOutsource/deleteProcessOutsourceMaterial.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    materialGridManager.loadData();
                }
            });
        }
    });
    // 表格
    materialGridManager = UICtrl.grid("#materialGrid", {
        gridManager: null,
        columns: [
            {
                display: "供给物品名称", name: "materialName", width: 300, minWidth: 60, type: "String", align: "left",
                editor: {type: 'text', required: true}
            },
            {
                display: "数量", name: "num", width: 150, minWidth: 60, type: "String", align: "left",
                editor: {
                    required: true, type: "text",mask: '9999999.999'
                }
            },
            {
                display: "计量单位", name: "unitName", width: 100, minWidth: 60, type: "String", align: "left",
                editor: {
                    required: true, type: "select",
                    data: {
                        type: 'system',
                        name: "dictionary",
                        getParam: function (item) {
                            return {fieldName: "MEINS"}
                        },
                        back: {
                            MSEH3: "unit",
                            MSEHL: "unitName",
                        }
                    }
                }
            },
            {
                display: "运输方式", name: "deliveryMethodOutTextView", width: 200, minWidth: 60, type: "String", align: "left",
                editor: {
                    type: 'dictionary',
                    data: {name: 'deliveryMethodOut'},
                    textField: 'deliveryMethodOutTextView',
                    valueField: 'deliveryMethodOut',
                    required: true,
                    render: function (item) {
                        return item.deliveryMethodOutTextView;
                    }
                }
            },
        ],
        dataAction: "server",
        url: web_app.name + '/processOutsource/queryProcessOutsourceMaterials.ajax',
        parms: {processOutsourceId: getId()},
        pageSize: 20,
        usePager: true,
        toolbar: toolbarOptions,
        enabledEdit: canEdit,
        width: "98%",
        height: "300px",
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
    });
    UICtrl.setSearchAreaToggle(materialGridManager);
}

//获取数据保存的参数
function getExtendedData(processAction) {
    //回退、打回、转交时，不需要验证必填项是否已经填写；
    if (processAction == ProcessAction.BACK
        || processAction == ProcessAction.REPLENISH
        || processAction == ProcessAction.TRANSMIT) {
        //不验证
        $('#submitForm').attr('check', false);
    }
    var extendedData = {};
    var _grid = UICtrl.getGridManager('#orderItemGrid');
    if (_grid) {
        var datas = DataUtil.getGridData({
            gridManager: _grid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        if ("outer" ==  getSubProcUnitId()){
            for (let i = 0; i < datas.length; i++) {
                var data = datas[i];
                if (MathUtil.compare(data.kbetr,0) <= 0){
                    Public.tip("序号为："+data.sequence+" 的行项目单价必须大于0");
                    return false;
                }
            }
        }
        extendedData.orderItems = Public.encodeJSONURI(datas);
    }

    var material_grid = UICtrl.getGridManager('#materialGrid');
    if (material_grid) {
        var datas = DataUtil.getGridData({
            gridManager: material_grid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        extendedData.materialItems = Public.encodeJSONURI(datas);
    }
    return extendedData;
}


function checkConstraints(){
    //物料组件信息
    var material_grid = UICtrl.getGridManager('#materialGrid');
    if (material_grid) {
        var datas = DataUtil.getGridData({
            gridManager: material_grid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        if (isApplyProcUnit() && datas.length == 0 ){
            Public.tip("物料组件信息必填");
            return false;
        }
    }
    //订单行项目信息
    var orderItem_grid = UICtrl.getGridManager('#orderItemGrid');
    if (orderItem_grid) {
        var datas = DataUtil.getGridData({
            gridManager: orderItem_grid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        if (isApplyProcUnit() && datas.length == 0){
            Public.tip("订单行项目信息必填");
            return false;
        }
    }
    return true;
}


function bindEvent(){
    $('#werksName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "WERKS"}
        },
        onChange: function (value, data) {
            $('#werks').val(data.WERKS);
            $('#werksName').val(data.NAME1);
        }
    });
}

function reloadGrid() {
    orderItemGridManager.loadData();
    materialGridManager.loadData();
}