var gridManager = null;


$(document).ready(function () {
    initialize();
    loadGrid();
    bindEvent();
});
function initialize(){
    UICtrl.layout("#layout", {leftWidth: 3});
    var statusId = $("#statusId").val();
    if (statusId === "0"){
        UICtrl.setElHideOrShow("#bktxt",true)
        UICtrl.setElHideOrShow("#budat",true)
        UICtrl.setElHideOrShow("#paymentMethod",true)
        UICtrl.setElHideOrShow("#totalMoney",true)
        UICtrl.setElHideOrShow("#carNo",true)
    }
}

function bindEvent(){
    
}

function loadGrid() {
     var toolbarOptions ={ items: [] };
     var subProcUnitId = getSubProcUnitId();
       if (subProcUnitId !== "purchase" ) {
        toolbarOptions = UICtrl.getDefaultToolbarOptions({
            addHandler: function () {
                UICtrl.addGridRow(gridManager, {sequence: (gridManager.getData().length + 1)});
            },
            deleteHandler: function () {
                var _grid = UICtrl.getGridManager('#maingrid');
                DataUtil.delSelectedRows({
                    action: 'wasteSaleItem/deleteWasteSaleItem.ajax',
                    param: {},
                    gridManager: _grid,
                    idFieldName: 'id',
                    onSuccess: function () {
                        reloadGrid();
                    }
                });
            }
        });
       }

    gridManager = UICtrl.grid("#maingrid", {
        columns: getGridColumns(),
        dataAction: "server",
        url: web_app.name + '/wasteSaleItem/queryWasteSaleItems.ajax',
        pageSize: 10,
        usePager: true,
        parms:{wasteSaleId:getId()},
        toolbar: toolbarOptions,
        enabledEdit: true,
        width: "100%",
        height: "70%",
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
    });
    UICtrl.setSearchAreaToggle(gridManager);
}

function getGridColumns(){
    var columns=[];
    var subProcUnitId = getSubProcUnitId();
    var statusId = $("#statusId").val();
    columns.push({
        display: "序号", name: "sequence", width: 60, minWidth: 60, type: "string", align: "left",
    },)
    columns.push({
        display: "品类", name: "wasteTypeTextView", width: 200, minWidth: 60, type: "string", align: "left",
        editor: {
            type: 'dictionary',
            data: {name: 'wasteType'},
            textField: 'wasteTypeTextView',
            valueField: 'wasteType',
            required: true,
            render: function (item) {
                return item.wasteTypeTextView;
            }
        },
    },)
    columns.push({
        display: "出售物品", name: "saleGoods", width: 300, minWidth: 60, type: "string", align: "left",
        editor: {
            required: true, type: "text",
        }
    },)
    columns.push({
        display: "数量", name: "quantity", width: 100, minWidth: 60, type: "string", align: "left",
        editor: {
            required: true, type: "text",mask: '9999999.99'
        }
    },)
    columns.push({
        display: "计量单位", name: "unitName", width: 160, 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",
                }
            },
        }
    },)
    if (subProcUnitId === "purchase" ) {
        columns.push({
            display: "毛重", name: "grossWeight", width: 120, minWidth: 60, type: "string", align: "left"
        },)
        columns.push({
            display: "车辆皮重", name: "carWeight", width: 120, minWidth: 60, type: "string", align: "left"
        },)
    } else  {
        columns.push({
            display: "毛重", name: "grossWeight", width: 120, minWidth: 60, type: "string", align: "left",
            editor: {
                required: false, type: "text", mask: '9999999.99'
            }
        },)
        columns.push({
            display: "车辆皮重", name: "carWeight", width: 120, minWidth: 60, type: "string", align: "left",
            editor: {
                required: false, type: "text",mask: '9999999.99'
            },
            render: function (item) {
                if (Public.isNotBlank(item.carWeight)) {
                    if (MathUtil.sub(item.grossWeight, item.carWeight) <= 0) {
                        Public.tip("毛重不能小于车辆皮重！");
                        return false;
                    }
                }
                return item.carWeight;
            }
        },)
    }



    if (subProcUnitId === "purchase" || statusId > 0){
        //采购部专员录入回收单价，自动计算出总价，补充收款账户
        columns.push({
            display: "扣减重量", name: "deductWeight", width: 120, minWidth: 60, type: "string", align: "left",
            editor: {
                required: false, type: "text",mask: '9999999.99'
            },
            render: function (item) {
                if (Public.isNotBlank(item.deductWeight)&&MathUtil.sub(item.deductWeight,0)>0) {
                    var amount1 = MathUtil.sub(item.grossWeight, item.carWeight);
                    var amount2 = MathUtil.sub(amount1, item.deductWeight);
                    if (amount2<=0){
                       Public.tip("毛重不能小于车辆皮重与扣减数量之和！");
                       return false;
                    }
                    return  item.quantity=amount2,item.deductWeight;
                    //return item.deductWeight;
                } else {
                    return item.deductWeight;
                }
                if (Public.isNotBlank(item.quantity) && Public.isNotBlank(item.price)) {
                    var amount = MathUtil.mul(item.quantity, item.price)
                    countTotalMoney();
                    return item.amount = amount
                }
            }

        },)
        columns.push({
            display: "单价", name: "price", width: 120, minWidth: 60, type: "string", align: "left",
            editor: {
                required: true, type: "text",mask: '9999999.99'
            }
        },)
        columns.push({
            display: "税率", name: "kbetr", width: 120, minWidth: 60, type: "string", align: "left",
            editor: {
                required: true, type: "text",mask: '9999999.99'
            }
        },)
        columns.push({
            display: "总价", name: "amount", width: 120, minWidth: 60, type: "string", align: "left",
            render: function (item){
                if (Public.isNotBlank(item.quantity) && Public.isNotBlank(item.price)){
                    var amount = MathUtil.mul(item.quantity,item.price)
                    countTotalMoney();
                    return item.amount = amount
                }
            }
        },)

        /*columns.push({
            display: "净重", name: "netWeight", width: 150, minWidth: 60, type: "string", align: "left",
            editor: {
                required: false, type: "text",mask: '9999999.99'
            }
        },)
        columns.push({
            display: "备注", name: "remark", width: 200, minWidth: 60, type: "string", align: "left",
            editor: {
                required: false, type: "text"
            }
        },)*/
    }
    return columns;
}

/**
 * 流程引擎回调设置打样的id
 * @param value 打样申请的id
 */
function setId(id) {
    $("#id").val(id);

    var _grid=UICtrl.getGridManager('#maingrid');
    _grid.options.parms.wasteSaleId = 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;
        }
        extendedData.items = Public.encodeJSONURI(datas);
    }
    return extendedData;
}

//提交前校验
function checkConstraints() {
    var _grid = UICtrl.getGridManager('#maingrid');
    if (_grid) {
        var datas = DataUtil.getGridData({
            gridManager: _grid,
            isAllData: true
        });
        if (datas.length < 1) {
            Public.tip("请添加出售物品");
            return false;
        }
    }
    return true;
}

//UICtrl中校验是否允许编辑
function businessJudgmentUnit() {
    var isApply='';

    if( typeof(isApplyProcUnit) =='function'){
        isApply=isApplyProcUnit();
    }
    if (isApply){
        return true
    }else {
        var subProcUnitId = getSubProcUnitId();
        if (subProcUnitId === "purchase"){
            UICtrl.setEditable($("#submitForm"));
            UICtrl.setElRequiredFlag('#bktxt', true);
            UICtrl.setElRequiredFlag('#budat', true);
            UICtrl.setElRequiredFlag('#paymentMethod', true);
            UICtrl.setElRequiredFlag('#carNo', true);
            UICtrl.disable($("#totalMoney"))
            return true
        }
    }
    return false;
}

function countTotalMoney(){
    var datas = gridManager.getData();
    var totalMoney = 0;
    datas.forEach(data =>{
        var amount = MathUtil.mul(data.quantity,data.price);
        totalMoney = MathUtil.add(totalMoney,amount);
        $("#totalMoney").val(totalMoney);
    })
}
