var gridManager = null;
var sapSuppliersPayGridManager = null;
var sapSuppliersBuyerGridManager = null;
var sapSuppliersItemPeriodGridManager = null;
var  canEdit=true;

$(document).ready(function () {
    initialize();
    loadSuppliersPayListGrid();
    loadSuppliersBuyerListGrid();
    loadSuppliersItemPeriodListGrid();
    bindEvent();
});
function initialize(){
    UICtrl.layout("#layout", {leftWidth: 3});
    $("#rltgr").val("Z00001X");
   // let isDetailPage = ($("#isDetailPage").val() === "true");
 //   if (isDetailPage) {
   //     $("#jobPageTop").hide();
 //   }
    if (applyType=="-1"){
      //  $("form[id='submitForm']:text").attr("disabled","disabled");
      //  disableForm("submitForm","disabled");
        UICtrl.setDisable($("#submitForm"));
        canEdit=false;
    }
    if (applyType == "0" || applyType=="-1" || applyType=="2"){
        $("#frozenDiv").hide();
    }else if (applyType == "1"){
        $("#frozenDiv").show();
    }
    $('#supplierList').fileList({
        bizId : $("#id").val()
    });

 }

/**
 * 流程引擎回调设置打样的id
 * @param value 打样申请的id
 */
function setId(bizId) {
    $("#id").val(bizId);
    var _grid = UICtrl.getGridManager('#sapSuppliersPayGrid');
    _grid.options.parms.sId = bizId;
    var _grid2 = UICtrl.getGridManager('#sapSuppliersBuyerGrid');
    _grid2.options.parms.sId = bizId;
    var _grid3 = UICtrl.getGridManager('#sapSuppliersItemPeriodGrid');
    _grid3.options.parms.sId = bizId;

    $("#sId").val(bizId);
    sapSuppliersPayGridManager.loadData();
    sapSuppliersBuyerGridManager.loadData();
    sapSuppliersItemPeriodGridManager.loadData();

    $('#supplierList').fileList({
        bizId : bizId
    });
}

/**
 * 流程引擎获取打样申请id的回掉方法。
 * @return 打样申请的id
 */
function getId() {
    var id=$("#id").val() || "";
    return id;
}

function getsId() {
    var sid=$("#id").val() || "";  //alert(applyType); alert($("#sId").val());
    if (applyType!="0"){ // alert("sID=00===="+$("#sId").val())
        sid=$("#sId").val();
    }
    return sid;

}

// 加载采购组织信息表格
function loadSuppliersBuyerListGrid() {
    var toolbarOptions = null;
    if (applyType == 0){
        toolbarOptions = UICtrl.getDefaultToolbarOptions({
            // 添加一行表格
            addHandler: function () {
                UICtrl.addGridRow(sapSuppliersBuyerGridManager,
                    {
                        // 行号加一
                        sequence: (sapSuppliersBuyerGridManager.getData().length + 1)*10,
                        webre:"X",
                        waers:"CNY",
                        waersTextView:"CNY-人民币",
                        kalsk:"Z1",
                        telf1: $("#buGroup").val() == "Z005" ? $("#mobNumber").val():""

                    }
                );
            },
            // 删除
            deleteHandler: function () {
                var _grid = UICtrl.getGridManager('#sapSuppliersBuyerGrid');
                DataUtil.delSelectedRows({
                    action: 'sapSuppliersData/deleteSuppliersBuyers.ajax',
                    param: {},
                    gridManager: _grid,
                    idFieldName: 'id',
                    onSuccess: function () {
                        sapSuppliersBuyerGridManager.loadData();
                    }
                });
            }
        });
    }
    // 表格
    sapSuppliersBuyerGridManager = UICtrl.grid("#sapSuppliersBuyerGrid", {
        gridManager: null,
        columns: getBuyColumns(),
        dataAction: "server",
        url: web_app.name + '/sapSuppliersData/slicedSuppliersBuyerData.ajax',
        parms: {sId: getsId},
        pageSize: 20,
        usePager: true,
        toolbar: toolbarOptions,
        enabledEdit: canEdit,
        width: "98%",
        height: "200px",
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        onAfterEdit: function (editParm) {
            var c = editParm.column, data = editParm.record;
            if (c.name == 'telf1' && $("#buGroup").val() == "Z005") {
                $("#mobNumber").val(data.telf1)
            }
        },
    });
    UICtrl.setSearchAreaToggle(sapSuppliersBuyerGridManager);
}

function getBuyColumns(){
    var columns = [];
    columns.push({
        display: "行号", name: "sequence", width: 80, minWidth: 60, type: "String", align: "left",
        //editor: {type: 'spinner', min: 1, max: 100, mask: 'nnn'}
    },)
    //修改不能编辑采购组织
    if (applyType == 1){
        columns.push({
            display: "采购组织", name: "ekorgTextView", width: 200, minWidth: 60, type: "String", align: "left",
        })
    }else {
        columns.push({
            display: "采购组织", name: "ekorgTextView", width: 200, minWidth: 60, type: "String", align: "left",
            editor: {
                type: 'dictionary',
                data: {name: 'ekorg'},
                textField: 'ekorgTextView',
                valueField: 'ekorg',
                required: true,
                render: function (item) {
                    return item.ekorgTextView;
                }
            },
        },)
    }

    columns.push({
        display: "货币码", name: "waersTextView", width: 140, minWidth: 60, type: "String", align: "left",
        editor: {
            type: 'dictionary',
            data: {name: 'waers'},
            textField: 'waersTextView',
            valueField: 'waers',
            required: true,
            render: function (item) {
                return item.waersTextView;
            }
        },
    },)
    columns.push({
        display: "付款条件", name: "payConditionTextView", width: 150, minWidth: 60, type: "String", align: "left",
        editor: {
            type: 'dictionary',
            data: {name: 'payCondition'},
            textField: 'payConditionTextView',
            valueField: 'payCondition',
            required: true,
            render: function (item) {
                return item.payConditionTextView;
            }
        },
    },)
    columns.push({
        display: "国际贸易条款", name: "inco1TextView", width: 200, minWidth: 60, type: "String", align: "left",
        editor: {
            type: 'dictionary',
            data: {name: 'inco1'},
            textField: 'inco1TextView',
            valueField: 'inco1',
            required: false,
            render: function (item) {
                return item.inco1TextView;
            }
        },
    },)
    columns.push({
        display: "国际贸易条款位置1", name: "inco2L", width: 140, minWidth: 60, type: "String", align: "left",
        editor: {type: 'text', required: false}
    },)
    columns.push( {
        display: "国际贸易条款位置2", name: "inco3L", width: 160, minWidth: 60, type: "String", align: "left",
        editor: {type: 'text', required: false}
    },)
    columns.push({
        display: "收货的发票验证", name: "webre", width: 100, minWidth: 60, type: "String", align: "left",
        //editor: {type: 'text', required: true}
    },)
    columns.push({
        display: "供应商方案组", name: "kalsk", width: 140, minWidth: 60, type: "String", align: "left",
        //editor: {type: 'text', required: true}
    },)
    columns.push({
        display: "供应商销售人员", name: "verkf", width: 140, minWidth: 60, type: "String", align: "left",
        editor: {type: 'text', required: false}
    },)
    columns.push({
        display: "供应商电话号码", name: "telf1", width: 140, minWidth: 60, type: "String", align: "left",
        editor: {type: 'text', required: false}
    },)
    columns.push({
        display: "服务的发票校验标识", name: "lebre", width: 140, minWidth: 60, type: "String", align: "left",
        editor: {type: 'text', required: false}
    },)
    columns.push( {
        display: "采购冻结", name: "sperm", width: 140, minWidth: 60, type: "String", align: "left",
        editor: {type: 'text', required: false}
    },)
    return columns;
}

//加载供应商子范围
function loadSuppliersItemPeriodListGrid() {
    var toolbarOptions = null;
    if (applyType == 0){
        toolbarOptions = UICtrl.getDefaultToolbarOptions({
            // 添加一行表格
            addHandler: function () {
                UICtrl.addGridRow(sapSuppliersItemPeriodGridManager,
                    {
                        // 行号加一
                        sequence: (sapSuppliersItemPeriodGridManager.getData().length + 1)*10,
                        ltsnr: (sapSuppliersItemPeriodGridManager.getData().length + 1)*10,
                        webre:"X",
                        kalsk:"Z1",
                        telf1: $("#buGroup").val() == "Z005" ? $("#mobNumber").val():""

                    }
                );
            },
            // 删除
            deleteHandler: function () {
                var _grid = UICtrl.getGridManager('#sapSuppliersItemPeriodGrid');
                DataUtil.delSelectedRows({
                    action: 'sapSuppliersData/deleteSuppliersItemPeriods.ajax',
                    param: {},
                    gridManager: _grid,
                    idFieldName: 'id',
                    onSuccess: function () {
                        sapSuppliersItemPeriodGridManager.loadData();
                    }
                });
            }
        });
    }
    // 表格
    sapSuppliersItemPeriodGridManager = UICtrl.grid("#sapSuppliersItemPeriodGrid", {
        gridManager: null,
        columns: getItemPeriodColumns(),
        dataAction: "server",
        url: web_app.name + '/sapSuppliersData/slicedSuppliersItemPeriodData.ajax',
        parms: {sId: getsId},
        pageSize: 20,
        usePager: true,
        sortName: 'sequence',
        sortOrder: 'asc',
        toolbar: toolbarOptions,
        enabledEdit: canEdit,
        width: "98%",
        height: "200px",
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        onAfterEdit: function (editParm) {
            var c = editParm.column, data = editParm.record;
            if (c.name == 'telf1' && $("#buGroup").val() == "Z005") {
                $("#mobNumber").val(data.telf1)
            }
            if (c.name == 'waersTextView' ) {
                sapSuppliersItemPeriodGridManager.updateRow(data,{ltsbz:data.ltsnr+"-"+ data.waersTextView});
            }
        },
    });
    UICtrl.setSearchAreaToggle(sapSuppliersItemPeriodGridManager);
}

function getItemPeriodColumns(){
    var columns = [];
    columns.push({
        display: "行号", name: "sequence", width: 80, minWidth: 60, type: "String", align: "left",
        //editor: {type: 'spinner', min: 1, max: 100, mask: 'nnn'}
    },)
    columns.push({
        display: "采购组织", name: "ekorgTextView", width: 200, minWidth: 60, type: "String", align: "left",
        editor: {
            type: 'dictionary',
            data: {name: 'ekorg'},
            textField: 'ekorgTextView',
            valueField: 'ekorg',
            required: true,
            render: function (item) {
                return item.ekorgTextView;
            }
        },
    },)
    columns.push({
        display: "供应商子范围", name: "ltsnr", width: 100, minWidth: 60, type: "String", align: "left",
        //editor: {type: 'text', required: true}
    },)
    columns.push({
        display: "供应商子范围描述", name: "ltsbz", width: 120, minWidth: 60, type: "String", align: "left",
        //editor: {type: 'text', required: true}
    },)
    // columns.push({
    //     display: "工厂", name: "werks", width: 100, minWidth: 60, type: "String", align: "left",
    //     editor: {
    //         required: false, 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, minWidth: 60, type: "String", align: "left",
    // },)
    columns.push({
        display: "货币码", name: "waersTextView", width: 140, minWidth: 60, type: "String", align: "left",
        editor: {
            type: 'dictionary',
            data: {name: 'waers'},
            textField: 'waersTextView',
            valueField: 'waers',
            required: true,
            render: function (item) {
                return item.waersTextView;
            }
        },
    },)
    columns.push({
        display: "付款条件", name: "payConditionTextView", width: 150, minWidth: 60, type: "String", align: "left",
        editor: {
            type: 'dictionary',
            data: {name: 'payCondition'},
            textField: 'payConditionTextView',
            valueField: 'payCondition',
            required: true,
            render: function (item) {
                return item.payConditionTextView;
            }
        },
    },)
    columns.push({
        display: "国际贸易条款", name: "inco1TextView", width: 200, minWidth: 60, type: "String", align: "left",
        editor: {
            type: 'dictionary',
            data: {name: 'inco1'},
            textField: 'inco1TextView',
            valueField: 'inco1',
            required: false,
            render: function (item) {
                return item.inco1TextView;
            }
        },
    },)
    columns.push({
        display: "国际贸易条款位置1", name: "inco2L", width: 140, minWidth: 60, type: "String", align: "left",
        editor: {type: 'text', required: false}
    },)
    columns.push( {
        display: "国际贸易条款位置2", name: "inco3L", width: 160, minWidth: 60, type: "String", align: "left",
        editor: {type: 'text', required: false}
    },)
    columns.push({
        display: "收货的发票验证", name: "webre", width: 100, minWidth: 60, type: "String", align: "left",
        //editor: {type: 'text', required: true}
    },)
    columns.push({
        display: "供应商方案组", name: "kalsk", width: 140, minWidth: 60, type: "String", align: "left",
        //editor: {type: 'text', required: true}
    },)
    columns.push({
        display: "供应商销售人员", name: "verkf", width: 140, minWidth: 60, type: "String", align: "left",
        editor: {type: 'text', required: false}
    },)
    columns.push({
        display: "供应商电话号码", name: "telf1", width: 140, minWidth: 60, type: "String", align: "left",
        editor: {type: 'text', required: false}
    },)
    columns.push({
        display: "服务的发票校验标识", name: "lebre", width: 140, minWidth: 60, type: "String", align: "left",
        editor: {type: 'text', required: false}
    },)
    columns.push( {
        display: "采购冻结", name: "sperm", width: 140, minWidth: 60, type: "String", align: "left",
        editor: {type: 'text', required: false}
    },)
    return columns;
}

// 加载付款信息表格
function loadSuppliersPayListGrid() {
    var toolbarOptions = null;
    if (applyType == 0){
        toolbarOptions = UICtrl.getDefaultToolbarOptions({
            // 添加一行表格
            addHandler: function () {
                UICtrl.addGridRow(sapSuppliersPayGridManager,
                    {
                        // 行号加一
                        sequence: (sapSuppliersPayGridManager.getData().length + 1)*10,
                        reprf:"X",
                        zterm:"Z002",
                        ztermTextView:"月结30天",
                    }
                );
            },
            // 删除选中的尺码信息
            deleteHandler: function () {
                var _grid = UICtrl.getGridManager('#sapSuppliersPayGrid');
                DataUtil.delSelectedRows({
                    action: 'sapSuppliersData/deleteSuppliersPays.ajax',
                    param: {},
                    gridManager: _grid,
                    idFieldName: 'id',
                    onSuccess: function () {
                        sapSuppliersPayGridManager.loadData();
                    }
                });
            }
        });
    }
    // 表格
    sapSuppliersPayGridManager = UICtrl.grid("#sapSuppliersPayGrid", {
        //gridManager: null,
        columns: [
            {
                display: "行号", name: "sequence", width: 80, minWidth: 60, type: "String", align: "left",
                //editor: {type: 'spinner', min: 1, max: 100, mask: 'nnn'}
            },
            {
                display: "公司代码", name: "bukrs", width: 100, minWidth: 60, type: "String", align: "left",
                editor: {
                    required: true, type: "select",
                    data: {
                        type: 'system',
                        name: "dictionary",
                        getParam: function (item) {
                            return {fieldName: "BUKRS"}
                        },
                        back: {
                            BUKRS: "bukrs",
                        }
                    },
                }
            },
            {
                display: "统驭科目", name: "akontTextView", width: 250, minWidth: 60, type: "String", align: "left",
                editor: {
                    type: 'dictionary',
                    data: {name: 'akont'},
                    textField: 'akontTextView',
                    valueField: 'akont',
                    required: true,
                    render: function (item) {
                        return item.akontTextView;
                    }
                },
            },
            {
                display: "根据分配号排序代码", name: "zuawa", width: 150, minWidth: 60, type: "String", align: "left",
                render:function (item){
                    return item.sequence;
                }
            },
            {
                display: "付款条件", name: "ztermTextView", width: 100, minWidth: 60, type: "String", align: "left",
                editor: {
                    type: 'dictionary',
                    data: {name: 'zterm'},
                    textField: 'ztermTextView',
                    valueField: 'zterm',
                    required: true,
                    render: function (item) {
                        return item.ztermTextView;
                    }
                },
            },
            {
                display: "考虑的付款方式清单", name: "zwelsTextView", width: 140, minWidth: 60, type: "String", align: "left",
                editor: {
                    type: 'dictionary',
                    data: {name: 'zwels'},
                    textField: 'zwelsTextView',
                    valueField: 'zwels',
                    //  checkbox:true,
                    required: true,
                    render: function (item) {
                        return item.zwelsTextView;
                    }
                },
            },
            {
                display: "检查双重发票", name: "reprf", width: 160, minWidth: 60, type: "String", align: "left",
                //editor: {type: 'text', required: true}
            },
            // {
            //     display: "中心记帐冻结", name: "sperrTextView", width: 100, minWidth: 60, type: "String", align: "left",
            //     editor: {
            //         type: 'dictionary',
            //         data: {name: 'sperr'},
            //         textField: 'sperrTextView',
            //         valueField: 'sperr',
            //         required: false,
            //         render: function (item) {
            //             return item.sperrTextView;
            //         }
            //     }
            // },
            {
                display: "对公司代码过帐冻结", name: "sperrBTextView", width: 140, minWidth: 60, type: "String", align: "left",
                editor: {
                    type: 'dictionary',
                    data: {name: 'sperrB'},
                    textField: 'sperrBTextView',
                    valueField: 'sperrB',
                    required: false,
                    render: function (item) {
                        return item.sperrBTextView;
                    }
                }
            },

        ],
        dataAction: "server",
        url: web_app.name + '/sapSuppliersData/slicedSuppliersPayData.ajax',
        parms: {sId: getsId},
        pageSize: 20,
        usePager: true,
        toolbar: toolbarOptions,
        enabledEdit: canEdit,
        width: "98%",
        height: "200px",
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        onAfterEdit:function (item) {
            if (item.column.name == "akontTextView"){
                var value = item.value;
                if (value.indexOf('1122010100')>=0 || value.indexOf("1122010200")>=0 || value.indexOf("1221050000")>=0){
                    Public.tip("供应商只能选择应付账款类型");
                    var _grid = UICtrl.getGridManager('#sapSuppliersPayGrid');
                    _grid.updateRow(item.record,{
                        akont:'',
                        akontTextView:''
                    })
                }
            }
            return item;
        },
    });
    UICtrl.setSearchAreaToggle(sapSuppliersPayGridManager);
}

// 加载银行信息表格

//获取数据保存的参数
function getExtendedData(processAction) {
    //回退、打回、转交时，不需要验证必填项是否已经填写；
    if (processAction == ProcessAction.BACK
        || processAction == ProcessAction.REPLENISH
        || processAction == ProcessAction.TRANSMIT) {
        //不验证
        $('#submitForm').attr('check', false);
    }
    const isAllData = $('#oldId') || !getId();
    var extendedData = {};
    var _grid = UICtrl.getGridManager('#sapSuppliersPayGrid');
    if (_grid) {
        var datas = DataUtil.getGridData({
            gridManager: _grid,
            isAllData: isAllData
        });
        if (!datas) {
            return false;
        }
        extendedData.suppliersPayList = Public.encodeJSONURI(datas);
    }
    var buy_grid = UICtrl.getGridManager('#sapSuppliersBuyerGrid');
    if (buy_grid) {
        var rows = buy_grid.getData();
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            if (row.Inco1 != ""&&row.Inco2L=="") {
                Public.errorTip('请输入国际贸易条款位置1!');
                return false;
            }
        }
        var datas = DataUtil.getGridData({
            gridManager: buy_grid,
            isAllData: isAllData
        });
        if (!datas) {
            return false;
        }
        extendedData.suppliersBuyerList = Public.encodeJSONURI(datas);
    }
    var item_period_grid = UICtrl.getGridManager('#sapSuppliersItemPeriodGrid');
    if (item_period_grid) {
        var rows = item_period_grid.getData();
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            if (row.Inco1 != ""&&row.Inco2L=="") {
                Public.errorTip('请输入国际贸易条款位置1!');
                return false;
            }
        }
        var datas = DataUtil.getGridData({
            gridManager: item_period_grid,
            isAllData: isAllData
        });
        if (!datas) {
            return false;
        }
        extendedData.suppliersItemPeriodList = Public.encodeJSONURI(datas);
    }
    return extendedData;
}


function checkConstraints(){
    var buGroup = $("#buGroup").val();
    var _grid = UICtrl.getGridManager('#sapSuppliersBuyerGrid');
    if (_grid) {
        var datas = DataUtil.getGridData({
            gridManager: _grid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        if (buGroup != "Z004" && datas.length == 0){
            Public.tip("供应商采购组织信息必填");
            return false;
        }
    }

    //付款信息
    var pay_grid = UICtrl.getGridManager('#sapSuppliersPayGrid');
    if (pay_grid) {
        var datas = DataUtil.getGridData({
            gridManager: pay_grid,
            isAllData: true
        });
        if (!datas) {
            return false;
        }
        if (isApplyProcUnit() && datas.length == 0 && "2" != getHandleResult()){
            Public.tip("供应商公司信息必填");
            return false;
        }
    }
    return true;
}


function bindEvent(){
    $('#land1Name').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {
                fieldName: "LAND1",
            }
        },
        onChange: function (value, data) {
            $('#land1').val(data.LAND1);
            $('#land1Name').val(data.LANDX);
        }
    });

    $('#regionName').searchbox({
        type: "system", name: "getArea",
        getParam: function (item) {
            if (Public.isBlank($('#land1').val())){
                Public.tip("请先选择国家")
                return false;
            }
            return {
                LAND1: $('#land1').val(),
            }
        },
        onChange: function (value, data) {
            $('#region').val(data.BLAND);
            $('#regionName').val(data.BEZEI);
        }
    });

    $('#city1Name').searchbox({
        type: "system", name: "getArea",
        getParam: function (item) {
            if (Public.isBlank($('#land1').val())){
                Public.tip("请先选择国家")
                return false;
            }
            return {
                LAND1: $('#land1').val(),
            }
        },
        onChange: function (value, data) {
            $('#city1').val(data.BLAND);
            $('#city1Name').val(data.BEZEI);
        }
    });

    $("#buGroup").combox({onChange:function(data){
        //2.	当供应商账户组=Z005时，“销售员”和“销售员电话”这两个字段均成为“必须输入字段
            var columns = sapSuppliersBuyerGridManager.columns;
            columns.some(column => {
                if (column.name == "verkf" || column.name == "telf1"){
                    column.editor.required = data.value == "Z005"? true:false;
                }
            })
            columns.splice(0,1)
            UICtrl.setGridColumns(sapSuppliersBuyerGridManager,columns);
            $("#buGroup").val(data.value);
            $("#buGroup_text").val(data.text);
        }
    })

    $('#bankl').searchbox({
        type: "system", name: "getBankInfo",
        getParam: function (item) {
            return {BANKS: $("#banks").val()}
        },
        onChange: function (value, data) {
            $('#bankl').val(data.BANKL);
            $('#banka').val(data.BANKA);
        }
    });
}

function reloadGrid() {
    sid=$("#id").val();
    sapSuppliersPayGridManager.loadData();
    sapSuppliersBuyerGridManager.loadData();
    sapSuppliersItemPeriodGridManager.loadData();
}