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 = detailGridManager.getSelectedRows();
                    for (var i = 0 ;i<rows.length;i++){
                        var row = rows[i];
                        UICtrl.addGridRow(orderItemGridManager,{
                            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,
                            bedat: Public.formatDate(new Date(),'%Y-%M-%D'),
                            // 行号加一
                            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();
                },
            });
            amountChange();
        }
    });

    // 表格
    orderItemGridManager = UICtrl.grid("#orderItemGrid", {
        columns: getOrderColumns(),
        dataAction: "server",
        _tableKey: 'processOutsourceItem',
        _local: true,
        url: web_app.name + '/processOutsource/queryProcessOutsourceOrderItems.ajax',
        parms: {processOutsourceId: getId()},
        pageSize: 200,
        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.replace(/^0+/, '')+
                    "&outProcess="+item.record.wempf+
                    "&number="+getMengs(item.record)+
                    "&lifnr="+item.record.lifnr,
                    {
                    },function (data){
                        var _grid = UICtrl.getGridManager('#orderItemGrid');
                        if (_grid != null ){
                            var datas = _grid.rows;
                            if (datas.length > 0 ){
                                $.each(datas, function (i, row) {
                                    //统计同产品，同工序的数量
                                    if (row.productCode == item.record.productCode && row.wempf == item.record.wempf){
                                        orderItemGridManager.updateRow(row,{
                                            kbetr:data.unitPrice,
                                            purchaseMwskzTextView:data.purchaseMwskzTextView,
                                            purchaseMwskz:data.purchaseMwskz,
                                            amount: MathUtil.mul(data.unitPrice , row.menge).div(data.kpein),
                                            kpein: data.kpein,
                                            lifnr:item.record.lifnr,
                                            lifnrName:item.record.lifnrName,
                                            //printLoss: MathUtil.mul(row.menge, data.lossNumber)
                                        })
                                        amountChange();
                                    }
                                });
                            }
                        }

                })
            }
            if(item.column.name == "kbetr" || item.column.name == "menge"){
                orderItemGridManager.updateRow(item.record,{
                    amount: item.record.kbetr * item.record.menge
                })
                amountChange();
            }
            if (item.column.name == "eeind"){
                var _grid = UICtrl.getGridManager('#orderItemGrid');
                if (_grid != null ){
                    var datas = _grid.rows;
                    if (datas.length > 0 ){
                        $.each(datas, function (i, row) {
                            orderItemGridManager.updateRow(row,{
                                eeind:item.value,
                            })
                        });
                    }
                }

            }
        },
        onAfterShowData:function (item) {
            amountChange();
        }
    });
    UICtrl.setSearchAreaToggle(orderItemGridManager);
}

/**
 * 计算数量和金额
 */
function amountChange(){
    var _grid = UICtrl.getGridManager('#orderItemGrid');
    if (_grid != null ){
        var datas = _grid.rows;
        if (datas.length > 0 ){
            var mengs = 0,//总数量
                amount = 0;//总价合计
            $.each(datas, function (i, data) {
                mengs = MathUtil.add(mengs,data.menge);
                amount = MathUtil.add(amount,data.amount);
            });
            $("#mengs").val(mengs);
            $("#amount").val(amount);
        }
    }
}

function getMengs(record){
    var mengs = 0;//总数量
    var _grid = UICtrl.getGridManager('#orderItemGrid');
    if (_grid != null ){
        var datas = _grid.rows;
        if (datas.length > 0 ){
            var mengs = 0;//总数量
            $.each(datas, function (i, data) {
                //统计同产品，同工序的数量
                if (data.productCode == record.productCode && data.wempf == record.wempf){
                    mengs = MathUtil.add(mengs,data.menge);
                }
            });
        }
    }
    return mengs;
}


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",
        render:function(item){
            return item.productCode.replace(/^0+/, '');
        }
    },);
    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: "bedat", 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: "eeind", width: 140, minWidth: 60, type: "date", align: "left",
            editor: {
                type: "date", required: true
            }
        },);
        columns.push({
            display: "单价", name: "kbetr", width: 140, minWidth: 60, type: "string", align: "left",
            editor: {
                type: "text", mask: '9999999.9999', required: true
            }
        },);
        columns.push({
            display: "总价", name: "amount", width: 140, minWidth: 60, type: "money", align: "left",
        },);
        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.replace(/^0+/, ''),
                            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;
            //     }
            // },
        });
        columns.push({
            display: "备注", name: "remark", width: 200, minWidth: 60, type: "string", align: "left",
            editor: {
                type: "text", required: false
            }
        });
    }else {
        columns.push({
            display: "交货日期", name: "eeind", width: 140, minWidth: 60, type: "date", align: "left",
        },);
        columns.push({
            display: "单价", name: "kbetr", width: 140, minWidth: 60, type: "string", align: "left",
        },);
        columns.push({
            display: "总价", name: "amount", width: 140, minWidth: 60, type: "money", 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",
        });
        columns.push({
            display: "备注", name: "remark", width: 200, 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", {
        columns: [
            {
                display: "供给物品名称", name: "materialName", width: 500, 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 orderItemdatas = DataUtil.getGridData({
            gridManager: orderItem_grid,
            isAllData: true
        });
        if (!orderItemdatas) {
            return false;
        }
        if (isApplyProcUnit() && orderItemdatas.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();
}