var itemGridManager,dutyPersonGridManager = null
$(function () {
    initialize();
    initItemGrid();
    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);
        }
    });

}

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: "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 toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addHandler: function(){
           UICtrl.addGridRow(itemGridManager);
        },
        deleteHandler: function (){
            var _grid = UICtrl.getGridManager('#maingrid');
            DataUtil.delSelectedRows({
                action: 'exceptionReport/deleteExceptionReport.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    countSum();
                    reloadGrid();
                }
            });
        },
    });
        itemGridManager = UICtrl.grid('#maingrid', {
            columns: getGridColumns(),
            dataAction: 'server',
            url: web_app.name + '/exceptionReport/slicedExceptionReportItemList.ajax',
            parms: {exceptionReportId: getId()},
            height: '300px',
            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();
                }
            },
            onAfterShowData(){
                 countSum();
            }
        })
         UICtrl.setSearchAreaToggle(itemGridManager);
}

function getGridColumns() {
var columns = [];
columns = [
    {
        display: "采购/外发单号", name: "produceNo", width: "160", align: "left", type: "string",
        editor: {type: 'text',required:true}
    },
    {display: "产品类别", name: "productType", width: "160", align: "left", type: "string"
        ,editor: {type: 'text',required:true}
    },
{display: "产品编码", name: "productCode", 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}
},
{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: "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: '300px',
    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   countSum(){
     //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 (_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 _dutyPersonGrid=UICtrl.getGridManager('#dutyPersonGrid');
_dutyPersonGrid.options.parms.exceptionReportId = value;
}

function reloadGrid() {
    itemGridManager.loadData();
    dutyPersonGridManager.loadData();
    countSum();
}

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