var itemGridManager,gridManager = null, pstyp = " ", fillinDate = "", bsart = "";
var isAllData = true;
$(function () {
    initializeCommonUI();
    bindEvent();
    initItemGrid();
    revoke()
});
function revoke(){
    var revokeType = $("#revokeType").val();
    if ("update" == revokeType) {
        $("#billTitle .subject").html("撤审修改采购申请")
        $("#revoke").show();
    }else if ("close" == revokeType){
        $("#billTitle .subject").html("撤审关闭采购申请")
        $("#revoke").show();
    }else {
        $("#revoke").hide();
    }
}
function initializeCommonUI() {
    bsart = $("#bsart").val();
    if ("ZFW" == bsart) {
        pstyp = "D";
    } else {
        pstyp = "";
    }
}

function bindEvent() {
    fillinDate = $("#fillinDate").val();
    $('#knttp').val("A");
    /*$('#knttp').searchbox({
        type: "system", name: "knttp",
        getParam: function (item) {
            return {
                filterValue: $("#bsart").val()
            }
        },
        onChange: function (value, data) {
            $('#knttp').val(data.knttp);
        }
    });*/
}

function initItemGrid() {
    var toolbar = UICtrl.getDefaultToolbarOptions({
        addHandler: function () {
            UICtrl.addGridRow(itemGridManager, {
                bnfpo: (itemGridManager.getData().length + 1) * 10,
                pstyp: pstyp,
                badat: fillinDate,
                //erdat: fillinDate,
                ernam: $("#personMemberName").val(),
                afnam: $("#personMemberName").val(),
                afnamId: $("#personMemberId").val(),
                waersName: "人民币",
                waers: "CNY"
            });
        },
        deleteHandler: function () {
            var _grid = UICtrl.getGridManager('#maingrid');
            DataUtil.delSelectedRows({
                action: 'sapPurchaseItem/deleteSapPurchaseItem.ajax',
                param: {},
                gridManager: _grid,
                idFieldName: 'id',
                onSuccess: function () {
                    reloadGrid();
                }
            });
        },
        copyHandler: {
            id: 'copyHandler', text: '复制', img: 'fa-copy', click: function () {
                var row = itemGridManager.getSelectedRow();
                if (!row) {
                    Public.tip("请勾选一条数据");
                    return;
                }
                var newRow = JSON.parse(JSON.stringify(row));
                newRow.bnfpo = (itemGridManager.getData().length + 1) * 10;
                newRow.id = null;
                UICtrl.addGridRow(itemGridManager, newRow);
            }
        }
    })
    itemGridManager = UICtrl.grid('#maingrid', {
            columns: getGridColumns(),
            dataAction: 'server',
        _tableKey: 'sapPurchaseItemZNE1',
        _local: true,
            url: web_app.name + '/sapPurchaseItem/querySapPurchaseItems.ajax',
            parms: {sapPurchaseId: getId()},
            height: '95%',
            heightDiff: -4,
            sortName: 'id',
            sortOrder: 'asc',
            checkbox: true,
            usePager: true,
            rownumbers: true,
            enabledEdit: true,
            fixedCellHeight: true,
            selectRowButtonOnly: true,
            autoApplyNextEditor: false,
            toolbar: toolbar,
            onBeforeEdit: function (editParm) {
                // var c = editParm.column, data = editParm.record;
                // //非资产类消耗性采购申请类型当“科目分配类型”选择K后“物料编号”字段调整为非必须输入项；“成本中心”、“总账科目”字段调整为必须输入项。订单号不可编辑。
                // if ("ZNE2" == bsart && (data.knttp == "K"|| data.knttp == "F" ) && c.name === 'kostl') {
                //     return true;
                // }else {
                //     return false;
                // }
                // //仅适用于KNTTP=F时
                // if (("ZFW" == bsart || "ZNE2" == bsart) && data.knttp == "F" && c.name === 'aufnr') {
                //     return true;
                // }else {
                //     return false;
                // }
                // //仅适用于KNTTP=A时
                // if (data.knttp == 'A' && c.name === 'anln1') {
                //     return true;
                // }else {
                //     return false;
                // }
            },
            onAfterEdit: function (editParm) {
                // if (editParm.record.knttp === "K") {
                //     var colums = itemGridManager.columns;
                //     colums.forEach(colum => {
                //         if (colum.name == "matnr") {
                //             colum.editor.required = false;
                //             itemGridManager.columns = colums
                //         }
                //     })
                // }
            }
        }
    );
    $('#maingrid').on('click', function (e) {
        var $clicked = $(e.target || e.srcElement);
        if ($clicked.is('a.bindAnln1')) {// 绑定资产编号
            var id =$clicked.data('id');
            var werks =$clicked.data('werks');
            var menge =$clicked.data('menge');
            var matkl =$clicked.data('matkl');
            var anln1 =$clicked.data('anln1');
            UICtrl.showAjaxDialog({
                title: '绑定',
                height: 500,
                width: 700,
                url: web_app.name + '/sapPurchase/showBindAnln1.load?itemId='+id +"&werks="+werks+ "&matkl="+matkl+"&anln1="+anln1,
                ok: function(d){
                    var _self = this;
                    var selectValues = $("#selectValues").val();
                    var length = selectValues.split(",").length;
                    //var rows = gridManager.getSelectedRows();
                    if (length != menge){
                        Public.tip("资产号数量必须与采购数量（"+menge+"）一致");
                        return false;
                    }
                    // var anln1s = [];
                    // var anln1 = "";
                    // if (rows.length>0){
                    //     rows.forEach(row=>{
                    //         anln1s.push(row.ANLN1);
                    //     })
                    //     anln1 = anln1s.join(',');
                    // }
                    initAddAnln1(selectValues,id);
                    _self.close();
                },
            });
            return false;
        }
    });
    UICtrl.setSearchAreaToggle(itemGridManager);
}

function getGridColumns() {
    var columns = [];
        columns.push({
            display: "申购项次号", name: "bnfpo", width: "80", align: "left", type: "string",
            //editor: {type: 'spinner', min: 10, max: 200, mask: 'nnn'}
        },);
        columns.push({display: "项次类别", name: "pstyp", width: "100", align: "left", type: "string", hide: true},);
        columns.push({
            display: "工厂", name: "werks", width: "100", align: "left", type: "string",
            editor: {
                required: true, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "WERKS"}
                    },
                    back: {
                        WERKS: "werks",
                        NAME1: "name1"
                    },

                },
            }
        },);
        columns.push({
            display: "工厂名称", name: "name1", width: "200", align: "left", type: "string",
            //editor: {required: false, type: "text"}
        });
        columns.push({
            display: "库存地点", name: "lgort", width: "100", align: "left", type: "string",
            editor: {
                required: false, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        if (Public.isBlank(item.werks)){
                            Public.tip("请先选择工厂");
                            return false;
                        }
                        return {
                            fieldName: "LGORT",
                            filterValue: item.werks
                        }
                    },
                    back: {
                        LGORT: "lgort",
                        LGOBE: "lgobe"
                    }
                },
            }
        },);
        columns.push({
            display: "库存地点名称", name: "lgobe", width: "200", align: "left", type: "string",
            //editor: {required: false, type: "text"}
        },);
        columns.push({
            display: "短文本", name: "txz01", width: "200", align: "left", type: "string",
            editor: {required: true, type: "text"}
        },);
        columns.push({
            display: "物料组", name: "matklName", width: "100", align: "left", type: "string",
            editor: {
                required: true, type: "select",
                data: {
                    type: 'system',
                    name: "purchaseMatklDictionary",
                    getParam: function (item) {
                        return {
                            fieldName: "MATKL",
                            filterValue: "A"
                        }
                    },
                    back: {
                        MATKL: "matkl",
                        WGBEZ: "matklName",
                    }
                },
            }
        },);
        columns.push({
            display: "申购数量", name: "menge", width: 150, minWidth: 60, type: "string", align: "center",
            editor: {required: true, type: "text", mask: '9999999.999'}
        },);
        columns.push({
            display: "申购数量单位", name: "meinsName", width: 150, minWidth: 60, type: "string", align: "center",
            editor: {
                required: true, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "MEINS"}
                    },
                    back: {
                        MSEH3: "meins",
                        MSEHL: "meinsName"
                    }
                },
            }
        },);
        columns.push({
            display: "采购组", name: "ekgrpName", width: 150, minWidth: 60, type: "string", align: "center",
            editor: {
                required: true, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "EKGRP"}
                    },
                    back: {
                        EKGRP: "ekgrp",
                        EKNAM: "ekgrpName",
                    }
                },
            }
        },);
        columns.push({
            display: "批准日期", name: "frgdt", width: "100", align: "left", type: "string",
            //editor: {required: false, type: "date"}
        },);
        columns.push({
            display: "要求交货日期", name: "lfdat", width: "100", align: "left", type: "string",
            editor: {required: true, type: "date"}
        },);
        columns.push({display: "创建者", name: "ernam", width: "200", align: "left", type: "string"},);
        columns.push({
            display: "申请人", name: "afnam", width: "90", align: "left", type: "string",
            //editor: {type: 'text', required: true},
            editor: {
                type: 'tree',
                required: true,
                checkbox: true,
                data: {
                    name: 'org',
                    filter: 'psm',
                    minWidth: 250,
                    param: {
                        orgRoot: "14636F3F48934EE7811768692A0AC5E1"
                    }
                },
                back: {
                    name: 'afnam',
                    id: 'afnamId'
                },
                // textField: 'executor',
                // valueField: 'executorId',
            }
        },);
        columns.push({
            display: "预估单价", name: "preis", width: "100", align: "left", type: "string",
            editor: {type: 'text', mask: '999999999.99', required: true}
        },);
        columns.push({
            display: "价格基数", name: "ebanPeinh", width: "100", align: "left", type: "string",
            //editor: {type: 'text', mask: '9999999',required: false}
            render: function (item) {
                return item.ebanPeinh = 1;
            }
        },);
        columns.push({
            display: "币种", name: "waersName", width: "100", align: "left", type: "string",
            editor: {
                required: true, type: "select",
                data: {
                    type: 'system',
                    name: "dictionary",
                    getParam: function (item) {
                        return {fieldName: "WAERS"}
                    },
                    back: {
                        WAERS: "waers",
                        KTEXT: "waersName",
                    }
                },
            }
        },);
        columns.push({
            display: "评估金额", name: "ebanNetwr", width: "100", align: "left", type: "string",
            render: function (item) {
                if (item.ebanPeinh == '') {
                    return item.ebanNetwr = null;
                }
                return item.ebanNetwr = (item.preis * item.menge / item.ebanPeinh).toFixed(2);
            }
            //editor: {type: 'text'}
        },);
    //财务部填写
    if (typeof(getSubProcUnitId) =='function'&&"financeNode" == getSubProcUnitId()){
        columns.push({
            display: "操作", name: "bindAnln1", width: 150, minWidth: 60, type: "string", align: "left",
            render: function (item) {
                var html = [];
                html.push('<a class="bindAnln1" href="javascript:void(0);"');
                html.push(' data-id="', item.id, '"');
                html.push(' data-werks="', item.werks, '"');
                html.push(' data-matkl="', item.matkl, '"');
                html.push(' data-menge="', item.menge, '"');
                html.push(' data-anln1="', item.anln1, '"');
                html.push(' data-name="', item.txz01, '">');
                html.push('<i class="fa fa-location-arrow"></i>&nbsp;');
                html.push('绑定资产编号');
                html.push('</a>');
                return html.join('');
            }
        },)
    }
    columns.push({
        display: "资产编号", name: "anln1", width: "500", align: "left", type: "string",
    },);
    columns.push({
        display: "申请日期", name: "badat", width: "100", align: "left", type: "string",
        editor: {required: false, type: "date"}
    },);
    columns.push({
        display: "创建日期", name: "erdat", width: "100", align: "left", type: "string",
        //editor: {required: false, type: "date"}
    },);
    return columns;
}

//获取数据保存的参数
function getExtendedData(processAction) {
    var handleResult=getHandleResult();
    //回退、打回、转交时，不需要验证必填项是否已经填写；
    if (processAction == ProcessAction.BACK
        || processAction == ProcessAction.REPLENISH
        || processAction == ProcessAction.TRANSMIT || "2" == handleResult) {
        //不验证
        $('#submitForm').attr('check', true);
        isAllData = false;
    }
    var extendedData = {};
    var _grid = UICtrl.getGridManager('#maingrid');
    if (_grid) {
        var datas = DataUtil.getGridData({
            gridManager: _grid,
            isAllData: isAllData
        });
        if (!datas) {
            return false;
        }
        if (isApplyProcUnit() && datas.length == 0 ){
            Public.tip("采购项次不能为空");
            return false;
        }
        var check = false;
        datas.forEach(data=>{
            if (Public.isBlank(data.anln1)){
                check = true;
            }
        })
        if ("financeNode" == getSubProcUnitId() && check){
            Public.tip("请为每条明细绑定资产编号");
            return false;
        }
        extendedData.sapPurchaseItems = Public.encodeJSONURI(datas);
    }
    return extendedData;
}

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

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

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

function getGridData() {
    var _grid = UICtrl.getGridManager('#maingrid');
    var datas = DataUtil.getGridData({
        gridManager: _grid,
        isAllData: isAllData
    });
    return datas;
}

function initAddAnln1(anln1,id){
    var _maingrid = UICtrl.getGridManager('#maingrid');
    if (_maingrid != null){
        if (_maingrid.currentData != null){
            var rows = _maingrid.currentData.Rows;
            $.each(rows, function (i, row) {
                if (id === row.id){
                    _maingrid.updateRow(row,{
                        anln1:anln1
                    })
                }
            });
        }
    }
}
