var clientGridManager,produceGridManager, purchaseGridManager, dutyPersonGridManager,exceptionClientManager = null;var checkbox = true;
$(function () {
    initialize();
    initSerachBox();
    //initProduceGrid();
    initClientGrid();
    initPurchaseGrid();
    initDutyPersonGridGrid();
});

function initialize() {
    var mainFileTable = $('#exceptionStateInfoList').fileList();
    mainFileTable.find('table').css({
        borderTopWidth: 0
    });
    $('#exceptionStateInfoList').fileList({
        bizId: $("#attbizId").val()
    });
    $("#dutyDeptName").orgTree({
        filter: "dpt", excludePos: 0, param: {orgKindId: "ogn,dpt"},
        back: {
            text: "#dutyDeptName",
            value: '#dutyDept'
        },
        //manageType: 'taskQuery',
        onChange: function (value, data) {
            $('#dutyDept').val(data.id);
        }
    });
    $("#checkOperatorName").orgTree({
        filter: "psm", excludePos: 0, param: {orgKindId: "ogn,dpt,pos,psm"},
        back: {
            text: "#checkOperatorName",
            value: '#checkOperator'
        },
        //manageType: 'taskQuery',
        onChange: function (value, data) {
            //  alert(data.id+data.name);  alert(data.deptId+data.deptName);
            $('#checkOperator').val(data.id);
            $('#dutyDeptName').val(data.deptName);
            $('#dutyDept').val(data.deptId);
        }
    });
    if ($('#exceptionReasonType').val() == "1") {
        showPurchaseDiv();
    }
    // else if ($('#exceptionReasonType').val() == "2") {
    //     showProduceDiv();
    // }
    else {
        showClientDiv();
    }
    $('#exceptionReasonType').combox({
        onChange: function (v) {
            $('#customerOrderNo').val("");
            $('#customerName').val("");
            $('#customerNo').val("");
            if (v.value == 1) { //供应商原料问题
                showPurchaseDiv();
            } else {
                if (v.value== "3"){
                    checkbox = true
                    //initSerachBox();
                    //showClientDiv();
                    //UICtrl.setElRequiredFlag("#customerNo", true);
                } else {
                    checkbox = false
                    //initSerachBox();
                    //UICtrl.setElRequiredFlag("#customerNo", false);
                    //showProduceDiv();
                }
                UICtrl.setElRequiredFlag("#customerNo", checkbox);
                initSerachBox();
                showClientDiv();
                UICtrl.setElHideOrShow("#loseMoney",false);
            }
        }
    });

    $('#customerNo').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "KUNNR"}
        },
        onChange: function (value, data) {
            $('#customerNo').val(data.KUNNR);
            $('#customerName').val(data.NAME);
        }
    });

    $('#reasonTypeDetailName').searchbox({
        type: "system", name: "selectExceptionReasonTypeDetail",
        getParam: function (item) {
            return {}
        },
        onChange: function (value, data) {
            $('#reasonTypeName').val(data.reasonTypeName);
            $('#reasonTypeDetail').val(data.reasonTypeDetail);
            $('#reasonTypeDetailName').val(data.reasonTypeDetailName);
        }
    });

}

function clearExceptionType(){
    $('#exceptionType').val("");
    $('#exceptionType_text').val("");
}

function showProduceDiv() {

    $("#purchaseDiv").hide();
    $("#produceDiv").show();
    $("#producegridDiv").show();
    $("#clientgridDiv").hide();
    $("#produceNoDiv").hide();
    $("#customerOrderNo_label").text("生产单号");
    $("#produceNo").val("");
    try {
        produceGridManager.loadData();
    } catch(e){
        // alert(e.error);
    }
    setPurchaseMustInput(false);
    setProduceMustInput(true);
}

function showClientDiv() {

    $("#purchaseDiv").hide();
    $("#produceDiv").show();
    $("#clientgridDiv").show();
    //$("#producegridDiv").hide();
    //$("#produceNoDiv").show();
    $("#customerOrderNo_label").text("客户单号")
    try {
        clientGridManager.loadData();
    } catch(e){
        // alert(e.error);
    }
    setPurchaseMustInput(false);
    setProduceMustInput(true);
    UICtrl.setElHideOrShow("#loseMoney",false);
}

function showPurchaseDiv() {
    $("#produceDiv").hide();
    try {
        purchaseGridManager.loadData();
    } catch(e){
       // alert(e.error);
    }
    $("#purchaseDiv").show();
    setPurchaseMustInput(true);
    setProduceMustInput(false);
}

function setPurchaseMustInput(flag) {
    //UICtrl.setElRequiredFlag("#customerNamePur", flag);
    //UICtrl.setElRequiredFlag("#customerOrderNoPur", flag);
    //UICtrl.setElRequiredFlag("#brandName", flag);

    UICtrl.setElHideOrShow("#loseMoney",true);

}

function setProduceMustInput(flag) {
   if ($('#exceptionReasonType').val() == "3"){
    UICtrl.setElRequiredFlag("#customerNo", flag);
   }
    UICtrl.setElRequiredFlag("#customerOrderNo", false);
    UICtrl.setElHideOrShow("#loseMoney",false);
}

function initSerachBox(){
    //工厂
    $('#werksName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "WERKS"}
        },
        onChange: function (value, data) {
            $('#werks').val(data.WERKS);
            $('#werksName').val(data.NAME1);
        }
    });
    $('input[name="payMoney"]').change(function () {
        if (isNaN(Number($('#payMoney').val()))) {
            Public.errorTip("赔付金额必须输入数字!");
            $('#payMoney').val("");
            countSumChange();
            return false;
        }
        countSumChange();
    })

    $('#customerOrderNo').searchbox({
        type: "system", name: "sapCustomerOrderSelect",
        checkbox:checkbox,
        checkboxIndex:"VBELN",
        textIndex:"NAME1",
        valueIndex:"VBELN",
        getParam: function (item) {
            if (Public.isBlank($('#werksName').val())) {
                Public.tip("请先选择工厂！")
                return false
            }
            if ($('#exceptionReasonType').val()=="3"&&Public.isBlank($('#customerNo').val())) {
                Public.tip("请先输入客户编号！")
                return false
            }
            return {
                werks: $('#werks').val(),
                kunnr: $('#customerNo').val(),
                reasonType:$('#exceptionReasonType').val()
            }
        },
        onChange: function (value, data) {
            // if ($('#exceptionReasonType').val()=="3") { //客户异常
            //     $('#customerName').val(value.text);
            // }
            $('#customerName').val(value.text);
            // if ($('#exceptionReasonType').val()=="2"&&data.VBELN!=undefined) { //生产异常
            //     produceGridManager.addRows({
            //         produceNo:data.VBELN,
            //         productCode: data.MATNR,
            //         productName: data.MAKTX,
            //         unitName: data.MEINS,
            //         number: data.PSMNG
            //     });
            // }
            $('#customerOrderNo').val(value.value);
            if (Public.isBlank($("#customerNo").val())){
                $('#customerNo').val(data.KUNNR);
            }
        }
    });

    $('#produceNo').searchbox({
        type: "system", name: "sapCustomerProduceNoByProduceNo",
        getParam: function (item) {
            if (Public.isBlank($('#werksName').val())) {
                Public.tip("请先选择工厂！")
                return false
            }
            if ($('#exceptionReasonType').val()=="3"&&Public.isBlank($('#customerNo').val())) {
                Public.tip("请先输入客户编号！")
                return false
            }
            return {
                werks: $('#werks').val(),
                kunnr: $('#customerNo').val(),
                bstnk: $('#customerOrderNo').val(),
                reasonType:$('#exceptionReasonType').val(),
            }
        },
        onChange: function (value, row) {
            var dates = clientGridManager.getData();
            if (dates != null && dates.length > 0){
                for (let j = 0; j < dates.length; j++) {
                    var data = dates[j];
                    if (Public.isNotBlank(row.AUFNR) && Public.isNotBlank(data.produceNo) && data.produceNo == row.AUFNR){
                        Public.tip("生产单号："+row.AUFNR+" 已选择，请取消勾选！");
                        return false;
                    }
                }
            }
            UICtrl.addGridRow(clientGridManager, {
                produceNo: row.AUFNR,
                productCode: row.MATNR,
                productName: row.MAKTX,
                number: row.PSMNG,
                unitName: row.MEINS,
                currencyName: row.KOEIN,
                money: row.KWERT,
                price: row.NETWR,
                sendDate: row.LFDAT
            })
            $('#produceNo').val(row.AUFNR);
            $('#customerOrderNo').val(row.BSTNK);
        }
    });
    //产品类别
    $('#productTypeName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "MATKL"}
        },
        onChange: function (value, data) {
            $('#productType').val(data.MATKL);
            $('#productTypeName').val(data.WGBEZ);
        }
    });
}

function initProduceGrid() {

    var produceToolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: function () {
            UICtrl.addGridRow(produceGridManager);
        },
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#producegrid');
            DataUtil.delSelectedRows({
                action: 'exceptionReport/deleteExceptionReportItem.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    countSum(produceGridManager.rows);
                    reloadGrid();
                }
            });
        },
    });
    produceGridManager = UICtrl.grid('#producegrid', {
        columns: getProcduceGridColumns(),
        dataAction: 'server',
        url: web_app.name + '/exceptionReport/slicedExceptionReportItemList.ajax',
        parms: {exceptionReportId: getId(),exceptionReasonType:"2"},
        height:'300', // colRowNum*35+90
        heightDiff: -4,
        sortName: 'id',
        sortOrder: 'asc',
        checkbox: true,
        usePager: true,
        rownumbers: true,
        enabledEdit: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        //autoApplyNextEditor:false,
        toolbar: produceToolbarOptions,
        onAfterEdit: function (item) {
            if (item.column.name == 'rmbMoney') {
                countSum(produceGridManager.rows);
                var money = MathUtil.add(item.record.money, item.value);
                produceGridManager.updateRow(item.record, {totalMoney:money });
            }
        },
        onAfterShowData() {
            countSum(produceGridManager.rows);
            for (var r = 0; r < produceGridManager.rows.length; r++) {
                var money = MathUtil.add(produceGridManager.rows[r].rmbMoney, produceGridManager.rows[r].money);
                produceGridManager.updateRow(produceGridManager.rows[r], {totalMoney:money });
            }
        }
    })
    UICtrl.setSearchAreaToggle(produceGridManager);
}

function initClientGrid() {
    produceToolbarOptions=null;
    var clientToolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: function () {
            //如果生产单号/客户单号 不为空，根据单号弹框查询
            var customerOrderNo = $("#customerOrderNo").val();
            if (Public.isNotBlank(customerOrderNo)){
                UICtrl.showAjaxDialog({
                    title: '新增',
                    width: 1200,
                    height: 400,
                    url: web_app.name + '/exceptionReport/chooseExceptionClientDetail.load',
                    param:{customerOrderNo:customerOrderNo},
                    init: function (){
                        initExceptionClient();
                    },
                    ok: function () {
                        var rows = exceptionClientManager.getSelectedRows();
                        for (var i = 0 ;i<rows.length;i++){
                            var row = rows[i];
                            var dates = clientGridManager.getData();
                            if (dates != null && dates.length > 0){
                                for (let j = 0; j < dates.length; j++) {
                                    var data = dates[j];
                                    if (Public.isNotBlank(row.AUFNR) && Public.isNotBlank(data.produceNo) && data.produceNo === row.AUFNR ){
                                        Public.tip("生产单号："+row.AUFNR+" 已选择，请取消勾选！");
                                        return false;
                                    }
                                }
                            }
                            clientGridManager.addRow({
                                produceNo: row.AUFNR,
                                productCode: row.MATNR,
                                productName: row.MAKTX,
                                number: row.PSMNG,
                                unitName: row.MEINS,
                                currencyName: row.KOEIN,
                                money: row.KWERT,
                                price: row.NETWR,
                                sendDate: row.LFDAT
                            });
                        }
                        this.close();
                    }
                })
            }else {
                UICtrl.addGridRow(clientGridManager);
            }
        },
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#clientgrid');
            DataUtil.delSelectedRows({
                action: 'exceptionReport/deleteExceptionReportItem.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    countSum(clientGridManager.rows);
                    reloadGrid();
                }
            });
        },
    });
    clientGridManager = UICtrl.grid('#clientgrid', {
        columns: getClientGridColumns(),
        dataAction: 'server',
        url: web_app.name + '/exceptionReport/slicedExceptionReportItemList.ajax',
        parms: {exceptionReportId: getId(),exceptionReasonType:"2"},
        height:'300', // colRowNum*35+90
        heightDiff: -4,
        sortName: 'id',
        sortOrder: 'asc',
        checkbox: true,
        usePager: true,
        rownumbers: true,
        enabledEdit: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        //autoApplyNextEditor:false,
        toolbar: clientToolbarOptions,
        onAfterEdit: function (item) {
            // if (item.column.name == 'rmbMoney') {
            //     countSum(clientGridManager.rows);
            //     var money = MathUtil.add(item.record.money, item.value);
            //     clientGridManager.updateRow(item.record, {totalMoney:money });
            // }
            //异常金额 = 异常数量 * 单价
            if (item.column.name == "exceptionNumber"|| item.column.name == "price" ){
                if (Public.isNotBlank(item.record.exceptionNumber)  && Public.isNotBlank(item.record.price)){
                    var money = MathUtil.mul(item.record.exceptionNumber,item.record.price);
                    clientGridManager.updateRow(item.record, {money: money,rmbMoney: MathUtil.mul(money,item.record.exchangeRate) });

                    //损失金额 = 行项目异常金额总和 + 赔付金额
                    countSum(clientGridManager.rows);
                }
            }
            //运输费
            // 返工费
            // 停工待料费
            if (item.column.name == "freight"|| item.column.name == "rework" || item.column.name == "stopWaitMaterial"){
                //损失金额 = 行项目异常金额总和 + 赔付金额
                countSum(clientGridManager.rows);
            }

            //换算金额 = 异常金额 * 汇率
            if (item.column.name == "money"|| item.column.name == "exchangeRate" ){
                if (Public.isNotBlank(item.record.money)  && Public.isNotBlank(item.record.exchangeRate)){
                    clientGridManager.updateRow(item.record, {rmbMoney: MathUtil.mul(item.record.money,item.record.exchangeRate) });
                    countSum(clientGridManager.rows);
                }
            }
        },
        onAfterShowData() {
            countSum(clientGridManager.rows);
            for (var r = 0; r < clientGridManager.rows.length; r++) {
                var money = MathUtil.add(clientGridManager.rows[r].rmbMoney, clientGridManager.rows[r].money)
                    .add(clientGridManager.rows[r].freight)
                    .add(clientGridManager.rows[r].rework)
                    .add(clientGridManager.rows[r].stopWaitMaterial);
                clientGridManager.updateRow(clientGridManager.rows[r], {totalMoney:money });
            }
        }
    })
    UICtrl.setSearchAreaToggle(clientGridManager);
}

function initExceptionClient(){
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({

    });
    exceptionClientManager = UICtrl.grid('#maingrid', {
        columns: getExceptionClientColumns(),
        dataAction: 'server',
        url: web_app.name + '/exceptionReport/slicedExceptionClientList.ajax',
        parms: {
            werks: $("#werks").val(),
            kunnr: $("#customerNo").val(),
            vbeln: $("#customerOrderNo").val(),
            reasonType: $('#exceptionReasonType').val()
        },
        height:'300', // colRowNum*35+90
        heightDiff: -4,
        sortName: 'id',
        sortOrder: 'asc',
        checkbox: true,
        usePager: true,
        rownumbers: true,
        enabledEdit: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        //autoApplyNextEditor:false,
        toolbar: toolbarOptions,
    })
    UICtrl.setSearchAreaToggle(exceptionClientManager);
}

function getExceptionClientColumns(){
    var columns = [];
    columns.push({
        display: "客户单号", name: "BSTNK", width: "160", align: "left", type: "string",
    });
    columns.push({
        display: "生产单号", name: "AUFNR", width: "160", align: "left", type: "string",
    });
    columns.push(
        {display: "产品编码", name: "MATNR", width: "160", align: "left", type: "string"
        } );
    columns.push(
        {display: "产品名称", name: "MAKTX", width: "250", align: "left", type: "string"
        } );
    columns.push(
        {display: "数量", name: "PSMNG", width: "60", align: "left", type: "string"
        } );
    columns.push(
        {display: "单价", name: "NETWR", width: "60", align: "left", type: "string"
        } );
    columns.push(
        {display: "单位", name: "MEINS", width: "60", align: "left", type: "string"
        } );
    columns.push(
        {display: "币别", name: "KOEIN", width: "60", align: "left", type: "string"
        } );
    columns.push(
        {display: "金额", name: "KWERT", width: "60", align: "left", type: "string"
        } );
    columns.push(
        {display: "出货日期", name: "LFDAT", width: "140", align: "left", type: "date"
        } );
    return columns;
}

function query(obj) {
    var param = $(obj).formToJSON();
    UICtrl.gridSearch(exceptionClientManager, param);
}
function reloadExceptionClientGrid() {
    exceptionClientManager.loadData();
}

function resetForm(obj) {
    $(obj).formClean();
}

function countSumChange() {
    if ($('#exceptionReasonType').val() == "1") {
        countSum(purchaseGridManager.rows);
    }
    // else if ($('#exceptionReasonType').val() == "2") {
    //     countSum(produceGridManager.rows);
    // }
    else {
        countSum(clientGridManager.rows);
    }
}

function getClientGridColumns() {
    var columns = [];
     columns.push({
            display: "生产单号", name: "produceNo", width: "160", align: "left", type: "string",
            editor: {
                required: false, type: "select",
                data: {
                    type: 'system',
                    name: "sapCustomerProduceNo",
                    getParam: function (item) {
                        if (Public.isBlank($('#customerOrderNo').val())) {
                            Public.tip("请先输入客户单号！")
                            return false;
                        }
                        return {
                            werks: $("#werks").val(),
                            kunnr: $("#customerNo").val(),
                            vbeln: $("#customerOrderNo").val(),
                            reasonType: $('#exceptionReasonType').val()
                        }
                    },
                    back: {
                        AUFNR: "produceNo",
                        MATNR: "productCode",
                        MAKTX: "productName",
                        PSMNG: "number",
                        MEINS: "unitName",
                        KOEIN: "currencyName",
                        KWERT: "money",
                        LFDAT: "sendDate",
                        NETWR: "price"
                    }
                }
            }
        });

    columns.push(
        {display: "产品编码", name: "productCode", width: "160", align: "left", type: "string"
           ,editor: {type: 'text'}
        } );
    columns.push(
        {display: "产品名称", name: "productName", width: "200", align: "left", type: "string"
           ,editor: {type: 'text'}
        } );
    columns.push(
        {display: "数量", name: "number", width: "100", align: "left", type: "string"
            ,editor: {type: "text",mask: '9999999.999'}
        } );
    columns.push(
        {display: "异常数量", name: "exceptionNumber", width: "100", align: "left", type: "string"
            ,editor: {type: "text",mask: '9999999.999'}
        } );
    columns.push(
        {display: "单价", name: "price", width: "100", align: "left", type: "string"
            ,editor: {type: "text",mask: '9999999.999'}
        } );
    columns.push(
        {display: "单位", name: "unitName", width: "80", align: "left", type: "string"
          ,editor: {type: "text"}
        } );
    columns.push(
        {display: "币别", name: "currencyName", width: "100", align: "left", type: "string"
             ,//editor: {type: "text"}
            editor: {
                required: false, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "WAERS"}
                    },
                    back: {
                        WAERS: "currency",
                        KTEXT: "currencyName",
                    }
                },
            }
        } );
    columns.push(
        {display: "汇率", name: "exchangeRate", width: "100", align: "left", type: "string"
            ,editor: {type: "text",mask: '9999999.999'}
        } );
    columns.push(
        {display: "异常金额", name: "money", width: "100", align: "left", type: "string"
         ,editor: {type: "text",mask: '9999999.999'}
        } );
    columns.push(
        {
            display: "折算金额", name: "rmbMoney", width: "100", align: "left", type: "string",
            editor: {type: "text", mask: '9999999.999'}
        } );
    columns.push(
        {display: "运输费", name: "freight", width: "100", align: "left", type: "string"
           ,editor: {type: "text",mask: '9999999.999'}
        } );
    columns.push(
        {display: "返工费", name: "rework", width: "100", align: "left", type: "string"
          ,editor: {type: "text",mask: '9999999.999'}
        } );
    columns.push(
        {display: "停工待料费", name: "stopWaitMaterial", width: "100", align: "left", type: "string"
          ,editor: {type: "text",mask: '9999999.999'}
        } );
    columns.push(
        {display: "出货日期", name: "sendDate", width: "140", align: "left", type: "date"
         ,editor: {type: "date"}
        } );
    return columns;
}
function getProcduceGridColumns() {
    var columns = [];
    columns.push({
        display: "生产单号", name: "produceNo", width: "160", align: "left", type: "string",
        editor: {type: 'text'}
    });

    columns.push(
        {display: "产品编码", name: "productCode", width: "160", align: "left", type: "string"
            ,editor: {type: 'text'}
        },
        {display: "产品名称", name: "productName", width: "200", align: "left", type: "string"
            ,editor: {type: 'text'}
        },
        {display: "数量", name: "number", width: "100", align: "left", type: "string"
            ,editor: {type: "text",mask: '9999999.999'}
        },
        {display: "单位", name: "unitName", width: "80", align: "left", type: "string"
            ,editor: {type: "text"}
        },
        {display: "币别", name: "currencyName", width: "100", align: "left", type: "string",
            editor: {
                required: false, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "WAERS"}
                    },
                    back: {
                        WAERS: "currency",
                        KTEXT: "currencyName",
                    }
                },
            }
            //,editor: {type: "text"}
        },
        {display: "金额", name: "money", width: "100", align: "left", type: "string"
            ,editor: {type: "text",mask: '9999999.999'}
        },
        {
            display: "折算金额", name: "rmbMoney", width: "100", align: "left", type: "string",
            editor: {type: "text", mask: '9999999.999'}
        },
        {
            display: "运输费", name: "freight", width: "100", align: "left", type: "string",
            editor: {type: "text", mask: '9999999.999'}
        },
        {
            display: "返工费", name: "rework", width: "100", align: "left", type: "string",
            editor: {type: "text", mask: '9999999.999'}
        },
        {
            display: "停工待料费", name: "stopWaitMaterial", width: "100", align: "left", type: "string",
            editor: {type: "text", mask: '9999999.999'}
        },
        // {
        //     display: "总金额", name: "totalMoney", width: "100", align: "left", type: "string"
        //  },
        {display: "出货日期", name: "sendDate", width: "140", align: "left", type: "date"
            ,editor: {type: "date"}
        }
    );
    return columns;
}

function initDutyPersonGridGrid() {
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: function () {
            UICtrl.addGridRow(dutyPersonGridManager,{
                dutyRate: 100
            });
        },
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#dutyPersonGrid');
            DataUtil.delSelectedRows({
                action: 'exceptionReport/deleteExceptionReportDutyPerson.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    reloadGrid();
                }
            });
        },
    });
    dutyPersonGridManager = UICtrl.grid('#dutyPersonGrid', {
            columns: getDutyPersonGridColumns(),
            dataAction: 'server',
            url: web_app.name + '/exceptionReport/slicedExceptionReportDutyPersonList.ajax',
            parms: {exceptionReportId: getId()},
            height: '300',
            heightDiff: -4,
            sortName: 'id',
            sortOrder: 'asc',
            checkbox: true,
            usePager: true,
            rownumbers: true,
            enabledEdit: true,
            fixedCellHeight: true,
            selectRowButtonOnly: true,
            //autoApplyNextEditor:false,
            toolbar: toolbarOptions,
        }
    );
    UICtrl.setSearchAreaToggle(dutyPersonGridManager);
}
/*
function initPurchaseToolBar(){
     purchaseToolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: function () {
            UICtrl.addGridRow(purchaseGridManager);
        },
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#purchasegrid');
            DataUtil.delSelectedRows({
                action: 'exceptionReport/deleteExceptionReportItem.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    countSum(purchaseGridManager.rows);
                    reloadGrid();
                }
            });
        },
    });
} */

function initPurchaseGrid() {
   var purchaseToolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: function () {
            UICtrl.addGridRow(purchaseGridManager);
        },
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#purchasegrid');
            DataUtil.delSelectedRows({
                action: 'exceptionReport/deleteExceptionReportItem.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    countSum(purchaseGridManager.rows);
                    reloadGrid();
                }
            });
        },
    });

    purchaseGridManager = UICtrl.grid('#purchasegrid', {
        columns: getPurchaseGridColumns(),
        dataAction: 'server',
        url: web_app.name + '/exceptionReport/slicedExceptionReportItemList.ajax',
        parms: {exceptionReportId: getId(),exceptionReasonType:"1"},
        height: '300',
        heightDiff: -2,
        sortName: 'id',
        sortOrder: 'asc',
        checkbox: true,
        usePager: true,
        rownumbers: true,
        enabledEdit: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        //autoApplyNextEditor:false,
        toolbar: purchaseToolbarOptions,
        onAfterEdit: function (item) {
            if (item.column.name == 'money' || item.column.name == 'rmbMoney' || item.column.name == 'freight'
            || item.column.name == 'rework' || item.column.name == 'stopWaitMaterial'
            || item.column.name =='startupFee') {
                var money = MathUtil.add(item.record.money, item.record.rmbMoney)
                    .add(item.record.freight)
                    .add(item.record.rework)
                    .add(item.record.stopWaitMaterial)
                    .add(item.record.startupFee);
                purchaseGridManager.updateRow(item.record, {totalMoney:money });
                countSum(purchaseGridManager.rows);
            }
        },
        onAfterShowData() {
            countSum(purchaseGridManager.rows);
            for (var r = 0; r < purchaseGridManager.rows.length; r++) {
                var money = MathUtil.add(purchaseGridManager.rows[r].rmbMoney, purchaseGridManager.rows[r].money);
                purchaseGridManager.updateRow(purchaseGridManager.rows[r], {totalMoney:money });
            }
        }
    })
    UICtrl.setSearchAreaToggle(purchaseGridManager);
}


function getPurchaseGridColumns() {
    var columns = [];
    columns = [
        {
            display: "采购单号", name: "produceNo", width: "160", align: "left", type: "string",
           // editor: {type: 'text', required: true}
            editor: {
                required: false, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "EKKO"}
                    },
                    back: {
                        EBELN: "produceNo",
                        BSART: "bsart",
                        BATXT: "batxt"
                    }
                }
            }
        },
        {display: "采购订单类型", name: "bsart", width: "80", align: "left", type: "string"},
        {display: "采购订单类型描述", name: "batxt", width: "200", align: "left", type: "string"},
        {
            display: "产品名称", name: "productName", width: "200", align: "left", type: "string"
            // , editor: {type: 'text', required: true}
            ,editor: {
                required: true, type: "select",
                data: {
                    type: 'material',
                    name: "selectMaterialsByPurchaseOrder",
                    getParam: function (item) {
                        return {
                            ebeln:item.produceNo
                        }
                    },
                    back: {
                        matnr: "productCode",
                        txz01: "productName",
                        menge: "number",
                        meins: "unit",
                        msehl: "unitName",
                        waers: "currency",
                        name: "currencyName",

                    }
                }
            }
        },
        {
            display: "产品编码", name: "productCode", width: "160", align: "left", type: "string"
            //, editor: {type: 'text', required: true}
        },
        {
            display: "数量", name: "number", width: "100", align: "left", type: "string"
            , editor: {type: "text", mask: '9999999.999'}
        },
        {
            display: "单位", name: "unitName", width: "80", align: "left", type: "string"
            // ,editor: {type: "text"}
            , editor: {
                required: true, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "MEINS"}
                    },
                    back: {
                        MSEH3: "unit",
                        MSEHL: "unitName"
                    }
                }
            }
        },
        {
            display: "币别", name: "currencyName", width: "100", align: "left", type: "string",
            editor: {
                required: false, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "WAERS"}
                    },
                    back: {
                        WAERS: "currency",
                        KTEXT: "currencyName",
                    }
                },
            }
            //editor: {type: "text"}
        },
        {
            display: "损失金额", name: "money", width: "100", align: "left", type: "string"
            , editor: {type: "text", mask: '9999999.999'}
        },
        {
            display: "罚款金额", name: "rmbMoney", width: "100", align: "left", type: "string",
            editor: {type: "text", mask: '9999999.999'}
        },
        {
            display: "运输费", name: "freight", width: "100", align: "left", type: "string",
            editor: {type: "text", mask: '9999999.999'}
        },
        {
            display: "返工费", name: "rework", width: "100", align: "left", type: "string",
            editor: {type: "text", mask: '9999999.999'}
        },
        {
            display: "停工待料费", name: "stopWaitMaterial", width: "100", align: "left", type: "string",
            editor: {type: "text", mask: '9999999.999'}
        },
        {
            display: "开机费", name: "startupFee", width: "100", align: "left", type: "string",
            editor: {type: "text", mask: '9999999.999'}
        },
        {
            display: "损失总金额", name: "totalMoney", width: "100", align: "left", type: "string"
         }
        // {
        //     display: "出货日期", name: "sendDate", width: "140", align: "left", type: "date"
        //     , editor: {type: "date"}
        // }
    ]
    return columns;
}


function countSum(zrow) {
    //var row=itemGridManager.rows;
    // var zrow=itemGridManager.rows;
    var money = 0;
    for (var r = 0; r < zrow.length; r++) {
        //客户异常/生产异常 运输费+返工费+停工待料费+折算金额+赔付金额=损失金额
        if ($('#exceptionReasonType').val() == "3" || $('#exceptionReasonType').val() == "2") {
           if (Public.isNotBlank(zrow[r].rmbMoney) && zrow[r].rmbMoney != 0) {
               money = MathUtil.add(zrow[r].rmbMoney, money);
           }else {
               money = MathUtil.add(zrow[r].money, money);
           }
           money = money.add(zrow[r].freight).add(zrow[r].rework).add(zrow[r].stopWaitMaterial);
        }else {
            //供应商材料问题 运输费+返工费+停工待料费+损失金额+开机费+赔付金额=损失总金额
            money = MathUtil.add(zrow[r].money, money);
            money = money.add(zrow[r].freight).add(zrow[r].rework).add(zrow[r].stopWaitMaterial).add(zrow[r].startupFee);
        }
    }
    money = MathUtil.add($('#payMoney').val(), money);

    $('#loseMoney').val(money);
}

function getDutyPersonGridColumns() {
    var columns = [];
    columns = [
        {
            display: "工号/客户编码", name: "personNo", width: "180", align: "left", type: "string",
            editor: {type: 'text'}
        },
        {
            display: "姓名/客户", name: "personName", width: "180", align: "left", type: "string",
            editor: {type: 'text'}
        },
        {
            display: "部门/客户名称", name: "deptName", width: "200", align: "left", type: "string",
            editor: {type: 'text'}
        },
        {
            display: "定责比例（%）", name: "dutyRate", width: "100", align: "left", type: "string",
            editor: {type: "text", mask: '999.99'}
        },
        {
            display: "个人责任比例（%）", name: "personDutyRate", width: "100", align: "left", type: "string",
            editor: {type: "text", mask: '999.99'}
        },
        {
            display: "责任金额", name: "dutyMoney", width: "100", align: "left", type: "string",
            editor: {type: "text", mask: '9999999.999'}
        },
        {
            display: "备注", name: "dutyRemark", width: "300", align: "left", type: "string",
            editor: {type: "text"}
        },
    ]
    return columns;
}

//获取数据保存的参数
function getExtendedData(processAction) {
//回退、打回、转交时，不需要验证必填项是否已经填写；
    if (processAction == ProcessAction.BACK
        || processAction == ProcessAction.REPLENISH
        || processAction == ProcessAction.TRANSMIT) {
//不验证
        $('#submitForm').attr('check', false);
    }
    var extendedData = {};
    let exceptionReasonType = $('#exceptionReasonType').val();
    var _grid = UICtrl.getGridManager('#producegrid');
    if ( exceptionReasonType === "1") { //供应商材料问题
        _grid = UICtrl.getGridManager('#purchasegrid');
    }
    if (exceptionReasonType === "3" || exceptionReasonType === "2") { //客户异常
        _grid = UICtrl.getGridManager('#clientgrid');
    }
    if (_grid) {
        var datas = DataUtil.getGridData({
            gridManager: _grid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        extendedData.exceptionReportItems = Public.encodeJSONURI(datas);
    }

    var _dutyPersonGrid = UICtrl.getGridManager('#dutyPersonGrid');
    if (_dutyPersonGrid) {
        var datas2 = DataUtil.getGridData({
            gridManager: _dutyPersonGrid,
            isAllData: true
        });
        if (!datas2) {
            return false;
        }
        extendedData.personList = Public.encodeJSONURI(datas2);
    }
    return extendedData;
}

function getId() {
    return $('#id').val();
}

function setId(value) {
    $("#id").val(value);
    // var produce_grid = UICtrl.getGridManager('#producegrid');
    // produce_grid.options.parms.exceptionReportId = value;

    var clientg_grid = UICtrl.getGridManager('#clientgrid');
    clientg_grid.options.parms.exceptionReportId = value;

    var _purchasegrid = UICtrl.getGridManager('#purchasegrid');
    _purchasegrid.options.parms.exceptionReportId = value;

    var _dutyPersonGrid = UICtrl.getGridManager('#dutyPersonGrid');
    _dutyPersonGrid.options.parms.exceptionReportId = value;
}

function reloadGrid() {
    clientGridManager.loadData();
    //produceGridManager.loadData();
    purchaseGridManager.loadData();
    dutyPersonGridManager.loadData();
    countSumChange();
}

function printPage() {
    Public.openPostWindow(web_app.name + '/PDFViewer/PDFViewer.do', {
        id: $("#id").val(),
        applicationType: "exceptionReport"
    });
}

function isNumber(val) {
    var regPos = /^\+?[1-9][0-9]*$/;
    // var regNeg = /^\-[1-9][0-9]*$/; // 负整数
    if (regPos.test(val)) {
        return true;
    } else {
        return false;
    }
}

function checkConstraints(){
    var exceptionReasonType = $('#exceptionReasonType').val();
    var grid ;
    var msg ;
    if (exceptionReasonType == "1") { //供应商材料问题
        grid = UICtrl.getGridManager('#purchasegrid');
        msg = "采购单号明细项必填";
    }else {
        //订单行项目信息
        grid = UICtrl.getGridManager('#clientgrid');
        msg = "生产单号明细项必填";
    }
    if (grid) {
        var datas = DataUtil.getGridData({
            gridManager: grid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        if (isApplyProcUnit() && datas.length == 0 ){
            Public.tip(msg);
            return false;
        }
    }
    return true;
}
