var itemGridManager, purchaseGridManager, dutyPersonGridManager = null
//var purchaseToolbarOptions=null;
$(function () {
    initialize();
    initProduceGrid();
    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 {
        showProduceDiv();
    }
    $('#exceptionReasonType').combox({
        onChange: function (v) {
            if (v.value == 1) { //供应商原料问题
                if ($('#exceptionType').val()=="in"){
                    Public.tip("供应商原料问题的异常类型只能是外部！");
                    clearExceptionType();
                    return false;
                }
                showPurchaseDiv();
            } else {
                if ($('#exceptionType').val()=="out"){
                    Public.tip("生产和客户异常的异常类型只能是内部！");
                    clearExceptionType();
                    return false;
                }
                showProduceDiv();
            }
        }
    });
    $('#exceptionType').combox({
        onChange: function (v) {
            if (v.value == "in") { //内部
                if ($('#exceptionReasonType').val()==1){
                    Public.tip("供应商原料问题的异常类型只能是外部！");
                    clearExceptionType();
                     return false;
                }
            } else {
                if ($('#exceptionReasonType').val()!=""&&$('#exceptionReasonType').val()!=1){
                    Public.tip("生产和客户异常的异常类型只能是内部！");
                    clearExceptionType();
                    return false;
                }
            }
        }
    });
}

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

function showProduceDiv() {

    $("#purchaseDiv").hide();
    $("#produceDiv").show();

    setPurchaseMustInput(false);
    setProduceMustInput(true);
}

function showPurchaseDiv() {
    $("#produceDiv").hide();
   // var row = purchaseGridManager.rows;
   // for (var u = 0; u < row.length; u++) {
       // purchaseGridManager.deleteRow(purchaseGridManager.rows[u]);
   // }
    purchaseGridManager.loadData();

    $("#purchaseDiv").show();

    setPurchaseMustInput(true);
    setProduceMustInput(false);
}

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

}

function setProduceMustInput(flag) {
    UICtrl.setElRequiredFlag("#customerNo", flag);
    UICtrl.setElRequiredFlag("#customerOrderNo", flag);
}

function initProduceGrid() {
    //工厂
    $('#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();
    })
    /*$('#customerName').searchbox({
        type: "system", name: "sapCustomerOrderSelect",
        getParam: function (item) {
            if (Public.isBlank($('#werksName').val())){
                Public.tip("请先选择工厂！")
                return false
            }
            return {
                werks: $('#werks').val(),
            }
        },
        onChange: function (value, data) {
            $('#customerName').val(data.NAME1);
            $('#customerNo').val(data.KUNNR);
        }
    });*/
    $('#customerOrderNo').searchbox({
        type: "system", name: "sapCustomerOrderSelect",
        getParam: function (item) {
            if (Public.isBlank($('#werksName').val())) {
                Public.tip("请先选择工厂！")
                return false
            }
            if (Public.isBlank($('#customerNo').val())) {
                Public.tip("请先输入客户编号！")
                return false
            }
            return {
                werks: $('#werks').val(),
                kunnr: $('#customerNo').val()
            }
        },
        onChange: function (value, data) {
            $('#customerOrderNo').val(data.VBELN);
            $('#customerName').val(data.NAME1);
        }
    });
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: function () {
           /* if (Public.isBlank($('#customerOrderNo').val())) {
                Public.tip("请先输入客户订单号！")
                return false
            }*/
            UICtrl.addGridRow(itemGridManager);
        },
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#maingrid');
            DataUtil.delSelectedRows({
                action: 'exceptionReport/deleteExceptionReport.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    countSum(itemGridManager.rows);
                    reloadGrid();
                }
            });
        },
    });
    itemGridManager = UICtrl.grid('#maingrid', {
        columns: getGridColumns(),
        dataAction: 'server',
        url: web_app.name + '/exceptionReport/slicedExceptionReportItemList.ajax',
        parms: {exceptionReportId: getId()},
        height:'auto', // 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,
        onAfterEdit: function (item) {
            if (item.column.name == 'rmbMoney') {
                countSum(itemGridManager.rows);
                var money = MathUtil.add(item.record.money, item.value);
                itemGridManager.updateRow(item.record, {totalMoney:money });
            }
        },
        onAfterShowData() {
            countSum(itemGridManager.rows);
            for (var r = 0; r < itemGridManager.rows.length; r++) {
                var money = MathUtil.add(itemGridManager.rows[r].rmbMoney, itemGridManager.rows[r].money);
                itemGridManager.updateRow(itemGridManager.rows[r], {totalMoney:money });
            }

        }
    })
    UICtrl.setSearchAreaToggle(itemGridManager);
}

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

function getGridColumns() {
    var columns = [];
    columns = [
        {
            display: "生产单号", name: "produceNo", width: "160", align: "left", type: "string",
            editor: {
                required: true, 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()
                        }
                    },
                    back: {
                        AUFNR: "produceNo",
                        MATNR: "productCode",
                        MAKTX: "productName",
                        PSMNG: "number",
                        MEINS: "unitName",
                        KOEIN: "currencyName",
                        KWERT: "money",
                        LFDAT: "sendDate"
                    }
                }
            }
        },
        {
            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: {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: "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);
        },
        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: 'auto',
            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/deleteExceptionReport.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/deleteExceptionReport.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()},
        height: 'auto',
        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 == 'rmbMoney') {
                countSum(purchaseGridManager.rows);
                var money = MathUtil.add(item.record.money, item.value);
                purchaseGridManager.updateRow(item.record, {totalMoney:money });
            }
        },
        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"
                        // MSEHL: "unitName"
                    }
                }
            }
        },
        // {display: "产品类别", name: "productType", width: "160", align: "left", type: "string"
        //     ,editor: {type: 'text',required:true}
        // },
        {
            display: "产品名称", name: "productName", width: "200", align: "left", type: "string"
            // , editor: {type: 'text', required: true}
            ,editor: {
                required: true, type: "select",
                data: {
                    type: 'system',
                    name: "sapMaterialSelect",
                    getParam: function (item) {
                        return {
                           // filterValue:item.company
                        }
                    },
                    back: {
                        MATNR: "productCode",
                        MAKTX: "productName",
                      //  EKGRP: "ekgrp",
                        MEINS: "unit",
                        MSEHL: "unitName"

                    }
                }
            }
        },
        {
            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: {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: "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++) {
        money = MathUtil.add(zrow[r].rmbMoney, money);
    }
    money = MathUtil.add($('#payMoney').val(), money);
    // for  (var x=0;x<row.length;x++){
    //  money = MathUtil.add(row[x].dutyMoney,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: "remark", 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 = {};
    var _grid = UICtrl.getGridManager('#maingrid');
    if ($('#exceptionReasonType').val() == "1") { //供应商材料问题
        _grid = UICtrl.getGridManager('#purchasegrid');
    }
    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 datas = DataUtil.getGridData({
            gridManager: _dutyPersonGrid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        extendedData.personList = Public.encodeJSONURI(datas);
    }
    return extendedData;
}

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

function setId(value) {
    $("#id").val(value);
    var _grid = UICtrl.getGridManager('#maingrid');
    _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() {
    itemGridManager.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;
    }
}
