var itemGridManager1,itemGridManager2,itemGridManager3=null
$(function () {
    initialize();
    initItemGrid();
});

function initialize() {
    var mainFileTable = $('#exceptionStateInfoList').fileList();
    mainFileTable.find('table').css({
        borderTopWidth : 0
    });
    $('#exceptionStateInfoList').fileList({
        bizId : $("#attbizId").val()
    });
    hideBusiness();
    var dealWay="";
    for (var x=0;x<$("input[name='dealWay']").length;x++) {
        if ($("input[name='dealWay']")[x].checked) {
            showBusiness($("input[name='dealWay']")[x].value);
            dealWay=$("input[name='dealWay']")[x].value;
        }
    }
    $('input[name="dealWay"]').change(function () {
        if ($(this).is(':checked')) {
            showBusiness($(this).val());
        }
    });

    if ((dealWay=="cash"&&"financial" === getSubProcUnitId())
        //||(dealWay=="pay"&&"buyer" === getSubProcUnitId())
    ){
      UICtrl.setElRequiredFlag("#sapBillNo",true);
    }else {
        UICtrl.setElRequiredFlag("#sapBillNo",false);
    }

}

function showBusiness(val) {
    if (val=='pay'){
        $("#payDiv").show();
        $("#cashDiv").hide();
        $("#goodsDiv").hide();
        $("#specialDiv").hide();
    }
    if (val=='cash'){
        $("#payDiv").hide();
        $("#cashDiv").show();
        $("#goodsDiv").hide();
        $("#specialDiv").hide();
    }
    if (val=='goods'){
        $("#payDiv").hide();
        $("#cashDiv").hide();
        $("#goodsDiv").show();
        $("#specialDiv").hide();
    }
    if (val=='special'){
        $("#payDiv").hide();
        $("#cashDiv").hide();
        $("#goodsDiv").hide();
        $("#specialDiv").show();
    }
}

function hideBusiness() {
    $("#payDiv").hide();
    $("#cashDiv").hide();
    $("#goodsDiv").hide();
    $("#specialDiv").hide();
}

function initItemGrid() {
    //工厂
    /*$('#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("");
            countSum();
            return false;
        }
        countSum();
    }) */
    //供应商
    $('#customerName').searchbox({
        type: "system", name: "selectSuppliersDatas",
        getParam: function (item) {
            return {
                ///  fieldName: "sapMaterialSelect",
                //filterValue: $('#werks').val()
            }
        },
        onChange: function (value, data) {
            $('#customerNo').val(data.partner);
            $('#customerName').val(data.nameOrg1);
        }
    });

    //物料编码
    /*$('#maktx').searchbox({
        type: "system", name: "sapMaterialSelect",
        getParam: function (item) {
            return {
                filterValue: $('#werks').val()
            }
        },
        onChange: function (value, data) {
            $('#matnr').val(data.MATNR);
            $('#maktx').val(data.MAKTX);
        }
    });
    $('#customerOrderNo').searchbox({
       type: "system", name: "dictionary",
       getParam: function (item) {
           return {fieldName: "EKKO"}
       },
       onChange: function (value, data) {
           $('#customerOrderNo').val(data.EBELN);
       }
   });
   $('#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);
       }
   });*/

    var toolbarOptions1 = UICtrl.getDefaultToolbarOptions({
        addHandler: function(){
           UICtrl.addGridRow(itemGridManager1);
        },
        deleteHandler: function (){
            var _grid = UICtrl.getGridManager('#maingrid1');
            DataUtil.delSelectedRows({
                action: 'exceptionReport/deleteExceptionReportPayable.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                   // countSum();
                    reloadGrid();
                }
            });
        },
    });
        itemGridManager1 = UICtrl.grid('#maingrid1', {
            columns: getGridColumns1(),
            dataAction: 'server',
            url: web_app.name + '/exceptionReport/slicedExceptionReportPayableList.ajax',
            parms: {exceptionReportId: getId()},
            height: '150px',
            heightDiff: -4,
            sortName: 'id',
            sortOrder: 'asc',
            checkbox: true,
            usePager: true,
            rownumbers: true,
            enabledEdit: true,
            fixedCellHeight: true,
            selectRowButtonOnly: true,
            //autoApplyNextEditor:false,
            toolbar: toolbarOptions1,
            onAfterEdit: function (item) {
                if (item.column.name == "money"){
                    var value = item.value;
                    var  zbrtwr = item.record.zbrtwr;
                    if (MathUtil.compare(value,zbrtwr) > 0){
                        itemGridManager1.updateRow(item.record, {
                            money: null,
                        });
                        Public.tip("金额不能大于过账金额（含税）")
                        return false;
                    }
                }
                return item;
            },
        })
         UICtrl.setSearchAreaToggle(itemGridManager1);

    var toolbarOptions2 = UICtrl.getDefaultToolbarOptions({
        addHandler: function(){
            UICtrl.addGridRow(itemGridManager2);
        },
        deleteHandler: function (){
            var _grid = UICtrl.getGridManager('#maingrid2');
            DataUtil.delSelectedRows({
                action: 'exceptionReport/deleteExceptionReportCash.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    reloadGrid();
                }
            });
        },
    });
    itemGridManager2 = UICtrl.grid('#maingrid2', {
        columns: getGridColumns2(),
        dataAction: 'server',
        url: web_app.name + '/exceptionReport/slicedExceptionReportCashList.ajax',
        parms: {exceptionReportId: getId()},
        height: '150px',
        heightDiff: -4,
        sortName: 'id',
        sortOrder: 'asc',
        checkbox: true,
        usePager: true,
        rownumbers: true,
        enabledEdit: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        //autoApplyNextEditor:false,
        toolbar: toolbarOptions2,
        onAfterEdit: function (item) {
        },
        onAfterShowData(){
        }
    })
    UICtrl.setSearchAreaToggle(itemGridManager2);

    var toolbarOptions3 = UICtrl.getDefaultToolbarOptions({
        addHandler: function(){
            UICtrl.addGridRow(itemGridManager3);
        },
        deleteHandler: function (){
            var _grid = UICtrl.getGridManager('#maingrid3');
            DataUtil.delSelectedRows({
                action: 'exceptionReport/deleteExceptionReportGoods.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    // countSum();
                    reloadGrid();
                }
            });
        },
    });
    itemGridManager3 = UICtrl.grid('#maingrid3', {
        columns: getGridColumns3(),
        dataAction: 'server',
        url: web_app.name + '/exceptionReport/slicedExceptionReportGoodsList.ajax',
        parms: {exceptionReportId: getId()},
        height: '150px',
        heightDiff: -4,
        sortName: 'id',
        sortOrder: 'asc',
        checkbox: true,
        usePager: true,
        rownumbers: true,
        enabledEdit: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        //autoApplyNextEditor:false,
        toolbar: toolbarOptions3
    })
    UICtrl.setSearchAreaToggle(itemGridManager3);
}

function getGridColumns1() {
var columns1 = [];
columns1 = [
    { display: "采购订单", name: "purchaseNo", width: "130", align: "left", type: "string",
       // editor: {required: true,type: 'text'}
       editor: {
        required: false, type: "select",
            data: {
            type: 'system',
                name: "sapPurchaseOrderSelect",
                getParam: function (item) {
                return {
                    werks: $('#werks').val(),
                    lifnr: $("#customerNo").val()
                }
            },
                //[
                //     {
                //         "EBELN": "8000000272",
                //         "EBELP": "00010",
                //         "GJAHR": "2025",
                //         "BELNR": "5000000409",
                //         "BUZEI": "0001",
                //         "BUKRS": "1000",
                //         "WERKS": "1000",
                //         "NAME1": "广州市宝绅科技有限公司",
                //         "MATNR": "000000000010100012",
                //         "TXZ01": "白格背印AW4200A",
                //         "BPMNG": 400000.000,
                //         "MEINS": "M2",
                //         "MSEHL": "平方米",
                //         "MWSKZ": "J0",
                //         "ZBRTWR": 720000.00,
                //         "WAERS": "USD",
                //         "KTEXT": "美元",
                //         "MENGE": 400000.000,
                //         "KWERT": 720000.00
                //     }
                // ]
            back: {
                EBELN: "purchaseNo",
                EBELP: "ebelp",
                GJAHR: "gjahr",
                BELNR: "belnr",
                BUZEI: "buzei",
                BUKRS: "bukrs",
                WERKS: "werks",
                MATNR: "productCode",
                TXZ01: "productName",
                BPMNG: "number",
                MEINS: "unit",
                MSEHL: "unitName",
                MWSKZ: "mwskz",
                WAERS: "waers",
                KTEXT: "ktext",
                MENGE: "menge",
                ZBRTWR: "zbrtwr"
            }
          }
        }
    },
    {
        display: "产品名称", name: "productName", width: "200", align: "left", type: "string"
    },
    {
        display: "产品编码", name: "productCode", width: "160", align: "left", type: "string"
    },
    {
        display: "数量", name: "number", width: "100", align: "left", type: "string"
        , editor: {type: "text", mask: '9999999.999'}
    },
    {
        display: "单位", name: "unitName", width: "80", align: "left", type: "string"
    },
    {
        display: "货币", name: "ktext", width: "80", align: "left", type: "string"
    },
    {
        display: "过账金额（含税）", name: "zbrtwr", width: "120", align: "left", type: "money"
    },
    //填写现有金额必须≤ZBRTWR（过账金额（含税））
    {display: "金额", name: "money", width: "120", align: "left", type: "money"
        ,editor: {required: true,type: "text",mask: '9999999.999'}
    },
    {display: "日期", name: "sendDate", width: "140", align: "left", type: "date"
        ,editor: {type: "date"}
    },
    {display: "备注", name: "remark", width: "280", align: "left", type: "string"
        ,editor: {type: 'text',required:false}
    }]
   return columns1;
}

function getGridColumns2() {
    var columns2 = [];
    columns2 = [
        {display: "", name: "payment", width: 80, minwidth: 80, type: "string", align: "left", hide: true},
        {display: "付款方式", name: "paymentTextView", width: "160", align: "left", type: "string",
           editor: {
                type: 'dictionary',
                data: {name: 'zwels'},
                textField: 'paymentTextView',
                valueField: 'payment',
                //  checkbox:true,
                required: true,
                render: function (item) {
                    return item.paymentTextView;
                }
            },
        },

        {display: "金额", name: "money", width: "100", align: "left", type: "string"
            ,editor: {required: true,type: "text",mask: '9999999.999'}
        },
        {display: "币别", name: "currencyName", width: "100", align: "left", type: "string"
            ,editor: {type: "text"}
        },
        {display: "账期", name: "period", width: "140", align: "left", type: "text"
            ,editor: {type: "text"}
        },
        {display: "备注", name: "remark", width: "350", align: "left", type: "string"
            ,editor: {type: 'text',required:false}
        }
    ]
    return columns2;
}


function getGridColumns3() {
    var columns3 = [];
    columns3 = [
        {display: "公司", name: "company", width: "100", align: "left", type: "string",hide:"true"},
        {display: "公司名称", name: "companyName", width: "180", align: "left", type: "string",
            editor: {
                required: true, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "BUKRS"}
                    },
                    back: {
                        BUKRS: "company",
                        BUTXT: "companyName"
                    }
                }
            }
        },
        {display: "采购组织", name: "purchaseTeam", width: "100", align: "left", type: "string",hide:"true"},
        {display: "采购组织名称", name: "purchaseTeamName", width: "160", align: "left", type: "string"
            ,editor: {
                required: true, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {
                            fieldName: "EKORG",
                            filterValue:item.company
                        }
                    },
                    back: {
                        EKORG: "purchaseTeam",
                        EKOTX: "purchaseTeamName",
                    }
                }
            }
        },
        {display: "物料编码", name: "productCode", width: "160", align: "left", type: "string",hide:"true"},
        {display: "物料名称", name: "productName", width: "180", align: "left", type: "string"
            ,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: "ekgrp", width: "120", align: "left", type: "string"
            ,editor: {
                required: true, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "EKGRP"}
                    },
                    back: {
                        EKGRP: "ekgrp",
                        EKNAM: "ekgrpName",
                    }
                }
            }
        },
        {display: "数量", name: "number", width: "100", align: "left", type: "string"
            ,editor: {type: "text",mask: '9999999.999',required: true}
        },
        {display: "单位", name: "unit", width: "120", align: "left", type: "string",hide:"true"},
        {display: "单位名称", name: "unitName", width: "80", align: "left", type: "string"
          /*  ,editor: {
                required: false, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "MEINS"}
                    },
                    back: {
                        MSEHI: "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: "needDate", width: "140", align: "left", type: "date"
            ,editor: {type: "date",required: true}
        },
        {display: "工厂编码", name: "werks", width: "140", align: "left", type: "string",hide:"true"},
        {display: "收货工厂", name: "werksName", width: "160", align: "left", type: "string",
           // editor: {type: "text"}
            editor: {
                required: true, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "WERKS"}
                    },
                    back: {
                        WERKS: "werks",
                        NAME1: "werksName",
                    }
                }
            }
        },
        {display: "收货地点", name: "locationName", width: "160", align: "left", type: "string",
            editor: {
                required: true, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "LGORT"}
                    },
                    back: {
                        LGORT: "location",
                        LGOBE: "locationName"
                    }
                }
            }
        },
        {display: "备注", name: "remark", width: "200", align: "left", type: "string"
            ,editor: {type: 'text',required:false}
        }
    ]
    return columns3;
}


//获取数据保存的参数
function getExtendedData(processAction) {
//回退、打回、转交时，不需要验证必填项是否已经填写；
if (processAction == ProcessAction.BACK
   || processAction == ProcessAction.REPLENISH
    || processAction == ProcessAction.TRANSMIT) {
  //不验证
    $('#submitForm').attr('check', false);
}
    var dealWay="0";
    for (var x=0;x<$("input[name='dealWay']").length;x++) {
        if ($("input[name='dealWay']")[x].checked) {
            dealWay="1";
            break;
        }
    }
    if (dealWay=="0"){
        Public.errorTip("处理方式必输！");
        return false;
    }
    if (($("input[name='dealWay']")[x].value=="cash"&&"financial" === getSubProcUnitId())
       //||($("input[name='dealWay']")[x].value=="pay"&&"buyer" === getSubProcUnitId())
      ){
       if ($('#sapBillNo').val()==""){
          Public.errorTip("SAP单据编号必输！");
          return false;
       }
    }
    var extendedData = {};
    var _grid = UICtrl.getGridManager('#maingrid1');
   if (_grid) {
     var datas = DataUtil.getGridData({
        gridManager: _grid,
       isAllData: true
    });
   if (!datas) {
     return false;
   }
    extendedData.handlePayable = Public.encodeJSONURI(datas);
  }

   var _cashGrid = UICtrl.getGridManager('#maingrid2');
   if (_cashGrid) {
     var datas = DataUtil.getGridData({
        gridManager: _cashGrid,
        isAllData: true
        });
    if (!datas) {
      return false;
    }
     extendedData.handleCash = Public.encodeJSONURI(datas);
   }
    var _goodsGrid = UICtrl.getGridManager('#maingrid3');
    if (_goodsGrid) {
        var datas = DataUtil.getGridData({
            gridManager: _goodsGrid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        extendedData.handleGoods = Public.encodeJSONURI(datas);
    }
  return extendedData;
}

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

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

   var _cashGrid=UICtrl.getGridManager('#maingrid2');
    _cashGrid.options.parms.exceptionReportId = value;
   var _goodsGrid=UICtrl.getGridManager('#maingrid3');
    _goodsGrid.options.parms.exceptionReportId = value;
}

function reloadGrid() {
    itemGridManager1.loadData();
    itemGridManager2.loadData();
    itemGridManager3.loadData();
}

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;
    }
}
