let gridManager = null;
let coRowNum=0;
//页面控制标识
let control = {
    isInitiator: false,//是否为审核人
    isDistribute: false,//是否已分发
    isConfirm:false,//是否已确认
}

$(document).ready(function () {
    initializate()
    loadRejectReasonBox();
    bindEvent();
})


function initializate() {
    UICtrl.disable("#mtart")
    UICtrl.setDisable("#totalContentDiv");
    coRowNum= $("#busiLens").val();
    var mtart = $("#mtart").val();
    initKlart(mtart);
    initRaube(mtart);
    initbstmi(mtart);
    initueetk(mtart);
    initKunnrName(mtart);
    //页面控制
    UICtrl.enable($("#businessUsage"));
    UICtrl.enable($("#matklName"));
    //物品类型 控制存储的序列号参数
    $("#mtart").combox({onChange:function(data) {
         initKlart(data.value);
         initRaube(data.value);
         storeDisplaySer(data.value);
         getBklas(data.value);
         getAwsls(data.value);
         initSale(data.value);
         initMRP(data.value);
         initbstmi(data.value);
         initueetk(data.value);

      }
    });
    //价格控制  控制财务核算的 不参与成本核算
    $("#vprsv").combox({onChange:function(data) {
          financialDisplayNcost(data.value);
        }
    });
    //获取类型   控制财务核算的 不参与成本核算
    $("#beskz").combox({onChange:function(data) {
            financialDisplayNcost($("#vprsv").val());
        }
    });
    //特殊获取方式  价格控制  控制财务核算的 不参与成本核算
    $("#sobsl").combox({onChange:function(data) {
          financialDisplayNcost($("#vprsv").val());
       }
    });
    //仓库设施1类型 控制 仓库设施1存储数量和单位的必填
    $("#lety1").combox({onChange:function(data) {
           warehouseSet(data.value);
        }
    });
    //不参与成本核算  修改 根据价格控制决定
    // $("#ncost").combox({onChange:function(data) {
    //         financialDisplayNcost($("#vprsv").val());
    //     }
    // });
    switch ($("#active").val()) {
        case '0'://待填报
          //  $("#businessUsageDiv").hide();
            hideAllBusiness(false); //隐藏但不清理值
            var selectedValues = $('input[name="businessUsage"]:checked').map(function() {
                return this.value;
            }).get();
            for (var x=0;x<$("input[name='businessUsage']").length;x++) {
                var value = $("input[name='businessUsage']")[x].value;
                // if ("S" == value){
                //     $("#businessUsageS").prop("checked",false);
                // }
                if (selectedValues.indexOf(value) > -1) {
                    if (("1010" == $("#werks").val() || "ZGMB" == $("#mtart").val() ) && x == 5){
                        $("input[name='businessUsage']")[x].checked = false;
                    }else if ("ZKGL" == $("#mtart").val() && x == 6){
                        $("input[name='businessUsage']")[x].checked = false;
                    }else {
                        $("input[name='businessUsage']")[x].checked = true;
                    }
                    if ($("input[name='businessUsage']")[x].checked) {
                        showBusiness(value);
                    }
                }else {
                    $("input[name='businessUsage']")[x].checked = false;
                }
            }
            if ($("#deptCode").val() === "system") {
                $("#auditForm").show();
            } else {
                $("#buttonBox").show();
                $("#showChart").remove();
            }
            if (applyType==2){ //扩展
                //$("#isAll").attr("disabled",true);
            }
            break;
        case '1'://待确认
            $("#buttonBox").show();
            $("#submit").remove();
            $("#save").remove();
            $("#back").remove();
              viewOnly();
               break;
        case '2'://已办结
            // $("#auditForm").show();
            $("#buttonBox").remove();
             UICtrl.setDisable("#basicInfoDiv");
             UICtrl.setDisable("#distributeDiv");
             viewOnly();
            break;
      //  case '3'://已办结
          //  showRejectCauseBox();
       //     $("#buttonBox").remove();
       //     break;
        default://其他/详情
            $("#buttonBox").show();
            break;
    }

     if (isAll=="1"){
        $('input[name="isAll"]').attr("checked",true);
     }

    $('input[name="isAll"]').change(function () {
       // debugger
        if ($(this).is(':checked')) {
            $("#busiLens").val(dictUsage.length);
            coRowNum=dictUsage.length;
             for (var x=0;x<$("input[name='businessUsage']").length;x++) {
                 if (("1010" == $("#werks").val() || "ZGMB" == $("#mtart").val()) && x == 5){
                     $("input[name='businessUsage']")[x].checked = false;
                 }else {
                     $("input[name='businessUsage']")[x].checked = true;
                 }
             }
            showAllBusiness();
            initMRP($("#mtart").val());
        } else {
            $("input[name='businessUsage']").each(function(){
                $(this).attr("checked",false);
                hideAllBusiness(true);
            })
        }
    });

    var dictUsage=dictUsages.split(";");
    $('input[name="businessUsage"]').change(function () {
       //alert($(this).is(':checked'));
        if ($(this).is(':checked')) {
             //let datas=gridManager.getData();
            // var name="",deptCode="";
            coRowNum=MathUtil.add(coRowNum,1);
            showBusiness($(this).val());

            if ("S"== $(this).val() ){
                if ($("#werks").val() == "1010" || $("#mtart").val() == "ZGMB"){
                    Public.tip("广州市宝绅科技有限公司RFID工厂或者刀工模板具不维护仓库管理视图");
                    $("#businessUsageS").prop("checked",false);
                } else {
                    $("#businessUsageS").prop("checked",true);
                }
            }
            if (coRowNum==dictUsage.length){
              $('input[name="isAll"]')[0].checked = true;
            }
        } else {
             hideBusiness($(this).val());
             coRowNum=MathUtil.sub(coRowNum,1);
             $('input[name="isAll"]').attr("checked",false);
        }
    });

    if (applyType==1){ //变更
        var lvorm = $("#lvorm").val();
        bindEvent_lvorm(lvorm)
    }

    //BPM不能修改产成品、半成品、设备类的产品名称、物料组、单位、规格
    if (mtart == "ZBCP" || mtart == "ZZCP" || mtart == "ZSHB"){
        UICtrl.disable("#matklTypeName");
        UICtrl.disable("#matklName");
        // UICtrl.disable("#groes");
        // UICtrl.disable("#spartName");
        // UICtrl.disable("#meinsName");
        // UICtrl.disable("#maktxRemZh");
        // UICtrl.disable("#maktx");
    }
}

function initKlart(mtart) {
    if (mtart == "ZBCP" || mtart == "ZZCP"){
        //分类类型、分类名称
        $("#klart").val("023");
        $("#classify").val("Z_PROD");
    }else if (mtart == "ZYCL"){
        //分类类型、分类名称
        $("#klart").val("023");
        $("#classify").val("Z_YCL");
    }
}

function initRaube(mtart) {
    if (mtart == "ZSHB"){
        //物品类型ZSHB，默认为S1
        $("#raube").val("S1");
        $("#raube_text").val("S1-小塘工厂五金库拣配_3000");
    }
    if (mtart == "ZGMB"){
        UICtrl.setElRequiredFlag("#raube",false);
        UICtrl.setElRequiredFlag("#lgtypName",false);
    }

    if (mtart == "ZKGL"){
        UICtrl.setElRequiredFlag("#raube",false);
    }
}

function initSale(mtart){
    if (mtart == "ZZCP" && $("#businessUsageV").prop("checked")){
        saleAndMtartRequired(true);
    }else if ((mtart == "ZBCP" || mtart == "ZSHB") && $("#businessUsageV").prop("checked")){
        UICtrl.setElRequiredFlag("#tragr",true);
        UICtrl.setElRequiredFlag("#ladgrName",true);
    } else {
        saleAndMtartRequired(false);
    }
}

function initMRP(mtart){
    if (mtart == "ZKGL" && $("#businessUsageD").prop("checked")){
        UICtrl.setElRequiredFlag("#beskz",false);
        UICtrl.disable("#beskz");
        $("#beskz").val("")//客供料，获取类型传空
        $("#beskz_text").val("")//客供料，获取类型传空
    }else {
        UICtrl.setElRequiredFlag("#beskz",true);
        UICtrl.enable("#beskz");
    }

    //物料主数据的创建，修改 物料类型为：ZGKL（客供料），字段mrp控制者（DISPO），改为默认并且只能是105
    if (mtart == "ZKGL"){
        $("#dispo").val("105");//MRP控制者
        $("#dispo_text").val("105-客供料");//MRP控制者
    }else if (mtart == "ZBCP" || mtart == "ZZCP"){
        $("#dispo").val("106");//MRP控制者
        $("#dispo_text").val("106-半成品");//MRP控制者
    }else if (mtart == "ZSHB"){
        $("#dispo").val("107");//MRP控制者
        $("#dispo_text").val("107-自制设备");//MRP控制者
    }
}

function initbstmi(mtart){
    //物料主数据的创建，修改：当物料类型等于，ZMYP(贸易品），ZFBL（辅料与包材），ZYCL（原材料）时：BSTMI（最小批量），BSTRF（舍入值）设置为必输
    if ((mtart == "ZFBL" || mtart == "ZMYP" || mtart == "ZYCL") && $("#businessUsageD").prop("checked")){
        bstmiChange(true);
    }else {
        bstmiChange(false);
    }
}

function initueetk(mtart){
    if (mtart == "ZBCP" || mtart == "ZZCP" || mtart == "ZSHB"){
        UICtrl.setElRequiredFlag("#ueetk", true);
        $("#ueetk").val("X");//允许未限制的过量交货
        $("#ueetk_text").val("是");//允许未限制的过量交货
    }else {
        $("#ueetk").val("0");//允许未限制的过量交货
        $("#ueetk_text").val("否");//允许未限制的过量交货
    }
}

function initKunnrName(mtart){
    if (mtart == "ZKGL"){
        UICtrl.setElRequiredFlag("#kunnrName", true);
    }else {
        UICtrl.setElRequiredFlag("#kunnrName", false);
    }
}

function bstmiChange(flag){
    UICtrl.setElRequiredFlag("#bstmi", flag);
    UICtrl.setElRequiredFlag("#bstrf", flag);
}

function saleAndMtartRequired(flag){
    UICtrl.setElRequiredFlag("#mvgr1",flag);
    UICtrl.setElRequiredFlag("#mvgr2",flag);
    UICtrl.setElRequiredFlag("#tragr",flag);
    UICtrl.setElRequiredFlag("#ladgrName",flag);
}

function  showBusiness(busiCode) {
    if (busiCode=="V") {  //销售
        $("#saleDiv").show();
        saleMustInput(true);
    }
    if (busiCode=="E") { //采购
        $("#purchaseDiv").show();
        purchaseMustInput(true);
    }
    if (busiCode=="D")  { //MRP
        $("#mrpDiv").show();
        $("#dismm").combox({onChange:function(data) {
             if (data.value=='ND'){
                  mrpMustInput(false);
              } else {
                  mrpMustInput(true);
              }
            }
        });
        var dismm=$("#dismm").val();
        if (dismm=='ND'){
            mrpMustInput(false);
        }else {
            mrpMustInput(true);
        }
        UICtrl.setElRequiredFlag("#dismm",true);
        UICtrl.setElRequiredFlag("#werksName",true);
        UICtrl.setElRequiredFlag("#mtvfp",true);
        initMRP($("#mtart").val());
    }

    if (busiCode=="A")  { //生产
        $("#produceDiv").show();
        produceMustInput(true);
    }
    if (busiCode=="L")  {  //存储
        $("#storeDiv").show();
        storeMustInput(true);
    }
    if (busiCode=="S")   { // 仓库
        $("#warehouseDiv").show();
        warehouseMustInput(true);
    }
    if (busiCode=="B")  { //财务
        $("#financialDiv").show();
        financialMustInput(true);
    }
}

function  hideBusiness(busiCode) {
    if (busiCode=="E") {
        $("#purchaseDiv").hide();
        purchaseMustInput(false);
        clearForm_purchase();
    }
    if (busiCode=="V") {
        $("#saleDiv").hide();
        saleMustInput(false);
        clearForm_sale();
    }
    if (busiCode=="D"){
        $("#mrpDiv").hide();
        mrpMustInput(false);
        UICtrl.setElRequiredFlag("#dismm",false);
        clearForm_mrp();
    }
    if (busiCode=="A") {
        $("#produceDiv").hide();
        produceMustInput(false);
        clearForm_produce();
    }
    if (busiCode=="L") {
        $("#storeDiv").hide();
        storeMustInput(false);
        clearForm_store();
    }
    if (busiCode=="S") {
        $("#warehouseDiv").hide();
        warehouseMustInput(false);
        clearForm_warehouse();
    }
    if (busiCode=="B") {
        $("#financialDiv").hide();
        financialMustInput(false);
        clearForm_financial();
    }
}
function  showAllBusiness() {
    $("#saleDiv").show();
    $("#purchaseDiv").show();
    $("#mrpDiv").show();
    $("#produceDiv").show();
    $("#storeDiv").show();
    $("#warehouseDiv").show();
    $("#financialDiv").show();
    //设置必输项
    saleMustInput(true);
    purchaseMustInput(true);
    produceMustInput(true);
    UICtrl.setElRequiredFlag("#dismm",true); //MRP类型
    storeMustInput(true);
    warehouseMustInput(true);
    financialMustInput(true);
    werksMustInput();
    lgortMustInput();
    mtvfpMustInput();
}

function  hideAllBusiness(flag) {
    $("#saleDiv").hide();
    $("#purchaseDiv").hide();
    $("#mrpDiv").hide();
    $("#produceDiv").hide();
    $("#storeDiv").hide();
    $("#warehouseDiv").hide();
    $("#financialDiv").hide();
    werksMustInput(); //可以不需要的？
    lgortMustInput();
    mtvfpMustInput();
    mrpMustInput(false);

    saleMustInput(false);
    purchaseMustInput(false);
    produceMustInput(false);
    UICtrl.setElRequiredFlag("#dismm",false); //MRP类型
    storeMustInput(false);
    warehouseMustInput(false);
    financialMustInput(false);

    if (flag) {
        clearForm_sale();
        clearForm_produce();
        clearForm_purchase();
        clearForm_mrp();
        clearForm_store();
        clearForm_warehouse();
        clearForm_financial();
    }
}

function  showBusinessReadOnly(busiCode) {
  if (busiCode=="V") {
      $("#saleDiv").show();
      //产品：产品经营类型、运输组，转载组，默认生产库存地 必填
      UICtrl.setDisable("#saleDiv");
   }
  if (busiCode=="E") {
      $("#purchaseDiv").show();
      UICtrl.setDisable("#purchaseDiv");
  }
  if (busiCode=="D")  {
     $("#mrpDiv").show();
      UICtrl.setDisable("#mrpDiv");
  }
  if (busiCode=="A")  {
     $("#produceDiv").show();
      UICtrl.setDisable("#produceDiv");
 }
  if (busiCode=="L")  {
     $("#storeDiv").show();
      UICtrl.setDisable("#storeDiv");
  }
  if (busiCode=="S")   {
     $("#warehouseDiv").show();
      UICtrl.setDisable("#warehouseDiv");
  }
  if (busiCode=="B")  {
     $("#financialDiv").show();
     UICtrl.setDisable("#financialDiv");
  }
}
function viewOnly(){ //只能查看
      hideAllBusiness();
    for (var x=0;x<$("input[name='businessUsage']").length;x++) {
        if ($("input[name='businessUsage']")[x].checked) {
          showBusinessReadOnly($("input[name='businessUsage']")[x].value);
        }
    }
    UICtrl.setDisable("#basicInfoDiv");
    UICtrl.setDisable("#distributeDiv");
    $("#maktxRemZh").attr("readonly",true);
    $("#maktxRemEn").attr("readonly",true);
    //UICtrl.setDisable($("#businessUsageV"));
    // UICtrl.setDisable($("#isAll"));
    $("#businessUsageV").attr("disabled",true);
    $("#businessUsageE").attr("disabled",true);
    $("#businessUsageD").attr("disabled",true);
    $("#businessUsageA").attr("disabled",true);
    $("#businessUsageL").attr("disabled",true);
    $("#businessUsageS").attr("disabled",true);
    $("#businessUsageB").attr("disabled",true);
    $("#isAll").attr("disabled",true);
}

function  saleMustInput(flag) { //销售必输项
    UICtrl.setElRequiredFlag("#alandName",flag);
    UICtrl.setElRequiredFlag("#aland",flag);
    UICtrl.setElRequiredFlag("#taxkm",flag);
    //UICtrl.setElRequiredFlag("#ktgrm",flag);
    UICtrl.setElRequiredFlag("#vkorgName",flag);
    UICtrl.setElRequiredFlag("#vtwegName",flag);
    var mtart = $("#mtart").val();
    if (!flag) {
        UICtrl.setElRequiredFlag("#umrenSale", flag);
        UICtrl.setElRequiredFlag("#umrezSale", flag);
        saleAndMtartRequired(flag)
    }else {
        //产成品品牌必填
        if (mtart == "ZZCP"){
            saleAndMtartRequired(flag)
        }
        if (mtart == "ZBCP" || mtart == "ZSHB"){
            UICtrl.setElRequiredFlag("#tragr",flag);
            UICtrl.setElRequiredFlag("#ladgrName",flag);
        }
    }

    mtvfpMustInput();
}
function purchaseMustInput(flag) { //采购必输项
    UICtrl.setElRequiredFlag("#ekgrpName",flag);
    UICtrl.setElRequiredFlag("#ekgrp",flag);
    if (!flag) {
        UICtrl.setElRequiredFlag("#umrenPurch", flag);
        UICtrl.setElRequiredFlag("#umrezPurch", flag);
    }
    werksMustInput();
}
function werksMustInput(){ //工厂必输
    var isMustInput="0";
    for (var x=0;x<$("input[name='businessUsage']").length;x++) {
       // alert($("input[name='businessUsage']")[x].value);
        if ($("input[name='businessUsage']")[x].checked) {
            // E 采购  L 存储 D MRP  A 生产
            if ($("input[name='businessUsage']")[x].value == "L" || $("input[name='businessUsage']")[x].value == "D"
                || $("input[name='businessUsage']")[x].value=="A"|| $("input[name='businessUsage']")[x].value=="E"){
                isMustInput="1";
                break;
            }
        }
    }
    if  (isMustInput=="1"){
        UICtrl.setElRequiredFlag("#werksName",true);
    } else {
        UICtrl.setElRequiredFlag("#werksName",false);
    }
}

function lgortMustInput(){ //库存地点必输
    var isMustInput="0";
    for (var x=0;x<$("input[name='businessUsage']").length;x++) {
        // alert($("input[name='businessUsage']")[x].value);
        if ($("input[name='businessUsage']")[x].checked) {
            //  L 存储 S 仓库
            if ($("input[name='businessUsage']")[x].value == "L" || $("input[name='businessUsage']")[x].value == "S"
              ){
               isMustInput="1";
              break;
            }
        }
    }
    if  (isMustInput=="1"){
        UICtrl.setElRequiredFlag("#lgortName",true);
    } else {
        UICtrl.setElRequiredFlag("#lgortName",false);
    }
}

function mtvfpMustInput(){ //可用性检查必输
    var isMustInput="0";
    for (var x=0;x<$("input[name='businessUsage']").length;x++) {
        // alert($("input[name='businessUsage']")[x].value);
        if ($("input[name='businessUsage']")[x].checked) {
            //  V  销售  D MRP
            if ($("input[name='businessUsage']")[x].value == "V" || $("input[name='businessUsage']")[x].value == "D"
            ){
                isMustInput="1";
                break;
            }
        }
    }
    if  (isMustInput=="1"){
        UICtrl.setElRequiredFlag("#mtvfp",true);
    } else {
        UICtrl.setElRequiredFlag("#mtvfp",false);
    }
}

function  mrpMustInput(flag) { //MRP必输项
    UICtrl.setElRequiredFlag("#dispo",flag);
    UICtrl.setElRequiredFlag("#disls",flag);
    UICtrl.setElRequiredFlag("#beskz",flag);
    UICtrl.setElRequiredFlag("#mtvfp",flag);

    UICtrl.setElRequiredFlag("#rgekz",flag);
    //物料主数据需求计划1：MARC-DISGR（MRP组）
    // 需求计划3：MARC-MISKZ（综合MRP标识）
    // 上述两个字段，确保在BPM系统的“物料主数据扩展/修改”功能和“非产成品/非半成品物料维护申请”功能中，不必显示出来，更不必带出默认值。
    UICtrl.setElRequiredFlag("#disgr",false);
    UICtrl.setElRequiredFlag("#strgr",flag);
    UICtrl.setElRequiredFlag("#sbdkz",flag);
    UICtrl.setElRequiredFlag("#vrmod",flag);
    UICtrl.setElRequiredFlag("#vint1",flag);
    UICtrl.setElRequiredFlag("#vint2",flag);
    //产成品品牌必填
    var mtart = $("#mtart").val();
    if (mtart == "ZZCP"){
        UICtrl.setElRequiredFlag("#lgproName",flag);
    }
    if (mtart == "ZKGL"){
        UICtrl.setElRequiredFlag("#beskz",false);
        UICtrl.disable("#beskz");
        $("#beskz").val("")//客供料，获取类型传空
        $("#beskz_text").val("")//客供料，获取类型传空
        $("#dispo").val("105");//MRP控制者
        $("#dispo_text").val("105-客供料");//MRP控制者
    }else {
        UICtrl.setElRequiredFlag("#beskz",flag);
        UICtrl.enable("#beskz");
    }
    werksMustInput();
    mtvfpMustInput();
}
function produceMustInput(flag){
    UICtrl.setElRequiredFlag("#sfcpf",flag);
    UICtrl.setElRequiredFlag("#fevor",flag);
    if (!flag) {
        UICtrl.setElRequiredFlag("#umrenProd", flag);
        UICtrl.setElRequiredFlag("#umrezProd", flag);
    }
    werksMustInput();
}

function  storeMustInput(flag) {
    UICtrl.setElRequiredFlag("#prctr",flag);
    UICtrl.setElRequiredFlag("#insmk",flag);
    storeDisplaySer($('#mtart').val());
    werksMustInput();
    lgortMustInput();
}
function storeDisplaySer(mtart){
    UICtrl.disable($("#sernp"));
    UICtrl.disable($("#serlv"));
    if (mtart=='ZGMB'){
        $('#sernp').val('Z005');
        $('#sernp_text').val('刀工模版采购序列号参数');
        $('#serlv').val('1');
        $('#serlv_text').val('保持设备号和序列号同步');
    } else {
        $('#sernp').val('');
        $('#sernp_text').val('');
        $('#serlv').val('');
        $('#serlv_text').val('');
    }
}
function  warehouseMustInput(flag) {
    // if (flag){
    //     $('#lhme1').val($('#meins').val());  //仓库的仓库设施1存储单位 默认基本计量单位
    //     $('#lhme1Name').val( $('#meinsName').val());
    // }   24.08.28取消
    UICtrl.setElRequiredFlag("#ltkzaName",flag);
    UICtrl.setElRequiredFlag("#ltkzeName",flag);
    UICtrl.setElRequiredFlag("#lgortProfitName",flag);
   // UICtrl.setElRequiredFlag("#lhmg1",flag);
   // UICtrl.setElRequiredFlag("#lhme1Name",flag);
    UICtrl.setElRequiredFlag("#lgnumName",flag);
    UICtrl.setElRequiredFlag("#lgortName",flag);
    UICtrl.setElRequiredFlag("#lgtypName",flag);
    lgortMustInput();
    if (!flag){
        $('#lety1').val("");
        $('#lety1_text').val("");
    }
    warehouseSet($('#lety1').val());
}

function warehouseSet(val){
    if (val=="TP"){
        UICtrl.setElRequiredFlag("#lhme1Name",true);
        UICtrl.setElRequiredFlag("#lhmg1",true);
     } else {
        UICtrl.setElRequiredFlag("#lhme1Name",false);
        UICtrl.setElRequiredFlag("#lhmg1",false);
        $('#lhmg1').val("");
    }

}
function  financialMustInput(flag) {
    UICtrl.setElRequiredFlag("#bklas",flag);
    UICtrl.setElRequiredFlag("#vprsv",flag);
    UICtrl.setElRequiredFlag("#mlast",flag);
    UICtrl.setElRequiredFlag("#peinh",flag);
    //UICtrl.setElRequiredFlag("#ncost",flag);
    UICtrl.setElRequiredFlag("#hkmat",flag);
    UICtrl.setElRequiredFlag("#ekalr",flag);
    var peinh = $("#peinh").val(); //定价基数
    if (Public.isBlank(peinh)){
        $("#peinh").val("1000");
    }
    financialDisplayNcost($("#vprsv").val());
    getBklas($('#mtart').val());
    getAwsls($('#mtart').val());
}

function financialDisplayNcost(vprsv) { // alert("-="+vprsv);
    if (vprsv == 'S') { //标准价格
        $('#ncost').val('0');
        //$('#ncost_text').val('0-空');
        $('#mlast').val('3');
        $('#mlast_text').val('单/多级');
    } else  if (vprsv == 'V') { //移动平均价格
        if ($('#beskz').val() == 'F' && ($('#sobsl').val() == '40' || $('#sobsl').val() == '70')) { //外部采购，库存转储，从1010工厂领料
            $('#ncost').val('0');
            //$('#ncost_text').val('0-空');
        } else {
            // $('#ncost').val('X');
            // $('#ncost_text').val('X-是');
            $('#ncost').val('0');
            //$('#ncost_text').val('0-空');
        }
        $('#mlast').val('2');
        $('#mlast_text').val('基于交易的');
    }

    //物料类型=ZSRV服务时。成本视图——不计算成本默认打勾选上
    var mtart = $("#mtart").val();
    if (mtart == "ZKGL" || mtart == "ZXNJ"){
        $("#ncost").val("X");//不参与成本核算
        $("#ncost_text").val("X-是");//不参与成本核算
    }else if (mtart == "ZSRV"){
        $("#ncost").val("");//不参与成本核算
        $("#ncost_text").val("");//不参与成本核算
    }else {
        $("#ncost").val("0");//不参与成本核算
        $("#ncost_text").val("0-否");//不参与成本核算
    }
}

function getBklas(mtart){ //获取评估分类
    if (mtart=='ZBCP'){
       $('#bklas').val("7900");
    } else if (mtart=='ZBPJ'||mtart=='ZCOM'||mtart=='ZECC'||mtart=='ZFBL'||mtart=='ZGMB'
      ||mtart=='ZXHP'||mtart=='ZXNJ') {
         $('#bklas').val("3001");
     } else  if (mtart=='ZKGL') {
         $('#bklas').val("3000");
     } else  if (mtart=='ZMYP') {
         $('#bklas').val("7930");
     } else  if (mtart=='ZSHB'|| mtart=='ZZCP') {
         $('#bklas').val("7920");
     } else  if (mtart=='ZSRV') {
         $('#bklas').val("7940");
     } else if  (mtart=='ZYCL') {
         $('#bklas').val("3000");
     }else if (mtart == "ZBZP"){
        setBklasByMatklAndMtart($('#matkl').val(),mtart)
    }

}

//If MTART（物料类型）∈{ZBCP、ZZCP、ZSHB}，此字段必须录入，且默认值唯一赋值只能是PP1；
// Else，此字段灰色而且为空（不可赋值，也无法修改）
function getAwsls(mtart) {//差异码
    if (mtart=='ZBCP'||mtart=='ZZCP'||mtart=='ZSHB'){
        $('#awsls').val("PP1");
    }else {
        $('#awsls').val("");
    }
}
/**
 * 表单提交
 * @returns {boolean}
 */
function saveForm(status) {
   // alert($("#businessCode").val());
   // let extendedData = getExtendedData();
   // debugger
   // if (!extendedData) return false;
    if (status==1 && $('input[name="businessUsage"]:checked').length <= 0){
        Public.errorTip("请选择业务用途！");
        return false;
    }
    var _self = this;
    $("#active").val(status);
    $('#submitForm').ajaxSubmit({
        url: web_app.name + '/sapNonProdApplyNext/saveSapNonProdApplyDept.ajax',
        //param: extendedData,
        success: function (data) {
            $("#applyDeptId").val(data.applyDeptId);
             if (data.type=="S") {
               Public.successTip("保存成功！");
             } else {
               Public.tip(data.backStr);
             }
             if (status==1 && data.type=="S") {
               $("#buttonBox").remove();
              }
           // _self.close();
            UICtrl.reloadTabById('#homepage');
        }
    });
}

//撤销
function  clearForm() {
    // $("#saleForm").formClean();
   // $("#matnr").val("");
    $("#mtart").val("");
    $("#matkl").val("");
    $("#matklName").val("");

    $("#groes").val("");
    $("#lvorm").val("");
    $("#spart").val("");
    $("#spartName").val("");

    $("#mtposMara").val("");
    $("#maktx").val("");
    $("#xchpf").val("");


    $("#magrv").val("");
    $("#maktxEn").val("");
    $("#meins").val("");
    $("#meinsName").val("");

    $("#raube").val("");
    $("#brgew").val("");
    $("#gewei").val("");
    $("#volum").val("");
    $("#voleh").val("");

    $("#iprkz").val("");
    $("#mhdhb").val("");
    $("#mhdrz").val("");
    $("#normt").val("");

    $("#werks").val("");
    $("#werksName").val("");
    $("#lgort").val("");
    $("#vkorg").val("");
    $("#vtweg").val("");
    $("#lgnum").val("");
    $("#lgtyp").val("");
    $("#lgtypName").val("");

    $("#maktxRemZh").val("");
    $("#maktxRemEn").val("");

    clearForm_sale();
    clearForm_produce();
    clearForm_purchase();
    clearForm_mrp();
    clearForm_store();
    clearForm_warehouse();
    clearForm_financial();
}

//撤销采购
function  clearForm_purchase(){
    // $("#saleForm").formClean();
    $("#bstme").val("");
    $("#bstmeName").val("");
    $("#umrenPurch").val("");
    $("#umrezPurch").val("");
    $("#ekgrp").val("");
    $("#ekgrpName").val("");
}

//撤销销售
function  clearForm_sale(){

    $("#vrkme").val("");
    $("#vrkmeName").val("");

    $("#umrenSale").val("");
    $("#umrezSale").val("");

    $("#dwerkName").val("");
    $("#dwerk").val("");
    $("#aland").val("");
    $("#alandName").val("");

    $("#taxkm").val("");
    $("#versg").val("");
    $("#kondm").val("");
    $("#ktgrm").val("");
    $("#prodh").val("");
    $("#mvgr1").val("");
    $("#mvgr2").val("");
    // $("#mvgr3").val("");
    //
    // $("#mvgr4").val("");
    // $("#mvgr5").val("");
    $("#mtpos").val("");
    //$("#xchpf").val("");
    $("#tragr").val("");
    $("#ladgr").val("");
    $("#ladgrName").val("");
}
// /撤销MRP
function  clearForm_mrp() {
    // $("#saleForm").formClean();
    //$("#disgr").val("");
    $("#dismm").val("");
    $("#minbe").val("");
    $("#dispo").val("");
    $("#disls").val("");
    $("#bstfe").val("");
    $("#bstma").val("");
    $("#bstmi").val("");
    $("#mabst").val("");
    $("#bstrf").val("");

    $("#beskz").val("");
    $("#sobsl").val("");
    $("#lgpro").val("");
    $("#rgekz").val("");
    $("#lgfsb").val("");
    $("#webaz").val("");
    $("#dzeit").val("");
    $("#plifz").val("");
    $("#fhori").val("");
    $("#eisbe").val("");
    $("#eislo").val("");
    $("#strgr").val("");
    //$("#mtvfp").val("");
    $("#wzeit").val("");
    $("#sbdkz").val("");
    $("#diskz").val("");
}
//撤销生产
function  clearForm_produce() {
    // $("#saleForm").formClean();
    $("#ausmeName").val("");
    $("#ausme").val("");
    $("#umrenProd").val("");
    $("#umrezProd").val("");
    $("#sfcpf").val("");
    $("#fevor").val("");
   // $("#fevorName").val("");
    $("#insmk").val("");
    $("#ueetk").val("");
    $("#ueetk_text").val("");
}

//撤销储存
function  clearForm_store() {
    // $("#saleForm").formClean();
    $("#sernp").val("");
    $("#serlv").val("");
    $("#prctr").val("");
}

//撤销仓库
function  clearForm_warehouse(){
    // $("#saleForm").formClean();
    $("#ltkza").val("");
    $("#ltkze").val("");
    $("#lgbkz").val("");
    $("#lhmg1").val("");
    $("#lhme1").val("");
    $("#lety1").val("");
}
//撤销财务核算
function  clearForm_financial(){
    // $("#saleForm").formClean();
    $("#bklas").val("");
    $("#mlast").val("");
    $("#vprsv").val("");
    //$("#peinh").val("");
    $("#verpr").val("");
    $("#stprs").val("");

}

/**
 *领导确认/回退
 */
function  confirmForm(val){
    $("#status").val(val);
    if (control.isConfirm) {
        Public.successTip("已确认！");
        return false;
    }
  //  let extendedData = getExtendedData();
  //  if (!extendedData) return false;
    $('#submitForm').ajaxSubmit({
        url: web_app.name + '/sapNonProdApplyNext/confirmSapNonProdApplyDept.ajax?confirm='+val,
       // param: extendedData,
        success: function (data) {
          //  alert(data.result);
            if (data.result=='')  {
                Public.successTip("操作成功！");
            } else {
                Public.errorTip(data.result);
            }
            //parent.reloadSpecialTaskGrid();
           // parent.homepage.trackTaskContent
            UICtrl.reloadTabById('homepage');
            $("#buttonBox").remove();
            control.isConfirm = true;
           // _self.close();
        }
    });

}

function bindEvent() {
    //物料组
    $('#matklTypeName').searchbox({
        type: "system", name: "matklDictionary",
        getParam: function (item) {
            return {
                fieldName: "MATKLTYPE",
                filterValue: $("#mtart").val()
            }
        },
        onChange: function (value, data) {
            $('#matklType').val(data.MATKL);
            $('#matklTypeName').val(data.WGBEZ);
        }
    });
    $('#matklName').searchbox({
        type: "system", name: "matklDictionary",
        getParam: function (item) {
            return {
                fieldName: "MATKL",
                filterValue: $('#matklType').val()
            }
        },
        onChange: function (value, data) {
            $('#matkl').val(data.MATKL);
            $('#matklName').val(data.WGBEZ);


            //当选择物料类型为ZBZP-保障类物品时，需根据不同的物料组对字段：评估类（BKLAS）进行赋值
            if ("ZBZP" == $("#mtart").val()){
                setBklasByMatklAndMtart(data.MATKL,$("#mtart").val());
            }
        }
    });

    $('#kunnrName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "KUNNR"}
        },
        onChange: function (value, data) {
            $('#kunnr').val(data.KUNNR);
            $('#kunnrName').val(data.NAME);
        }
    });
    //产品组
    $('#spartName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "SPART"}
        },
        onChange: function (value, data) {
            $('#spart').val(data.SPART);
            $('#spartName').val(data.VTEXT);
        }
    });
    //基本计量单位
    $('#meinsName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "MEINS"}
        },
        onChange: function (value, data) {
            $('#meins').val(data.MSEH3);
            $('#meinsName').val(data.MSEHL);
            $('#lhme1').val(data.MSEH3);  // 仓库的仓库设施1存储单位
            $('#lhme1Name').val(data.MSEHL);

            if ($('#ausme').val()==data.MSEH3) {//投料计量单位
                $('#ausme').val("");
                $('#ausmeName').val("");
                UICtrl.setElRequiredFlag("#umrenProd", false);
                UICtrl.setElRequiredFlag("#umrezProd", false);
            }
            if ($('#vrkme').val()==data.MSEH3) { //销售计量单位
                $('#vrkme').val("");
                $('#vrkmeName').val("");
                UICtrl.setElRequiredFlag("#umrenSale", false);
                UICtrl.setElRequiredFlag("#umrezSale", false);
            }
            if ($('#bstme').val()==data.MSEH3) { //采购计量单位
                $('#bstme').val("");
                $('#bstmeName').val("");
                UICtrl.setElRequiredFlag("#umrenPurch", false);
                UICtrl.setElRequiredFlag("#umrezPurch", false);
            }
        }
    });

  //工厂
    $('#werksName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "WERKS"}
        },
        onChange: function (value, data) {
            $('#werks').val(data.WERKS);
            $('#werksName').val(data.NAME1);

            //如果是1010工厂，不维护仓库管理视图
            if ("1010" == data.WERKS){
                //不勾选仓库管理视图
                $("#businessUsageS").prop("checked",false);
                hideBusiness("S");
                Public.tip("广州市宝绅科技有限公司RFID工厂不维护仓库管理视图")
            }else {
                $("#businessUsageS").prop("checked",true);
                showBusiness("S");
            }
        }
    });
    //库存地点
    $('#lgortName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "LGORT", filterValue: $('#werks').val()}
        },
        onChange: function (value, data) {
            $('#lgort').val(data.LGORT);
            $('#lgortName').val(data.LGOBE);

            //物料主数据创建，修改，字段LGPRO优化一下
            // 当LGPRO当为空时，默认=LGORT
            // 不为空时，以实际填写为准
            if (Public.isBlank($("#lgpro").val())){
                $("#lgpro").val(data.LGORT);
                $("#lgproName").val(data.LGOBE);
            }
        }
    });
   //仓库号
    $('#lgnumName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "LGNUM"}
        },
        onChange: function (value, data) {
            $('#lgnum').val(data.LGNUM);
            $('#lgnumName').val(data.LNUMT);
        }
    });
    //存储类型
    $('#lgtypName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {
                fieldName: "LGTYP",
                filterValue:$('#lgnum').val()
            }
        },
        onChange: function (value, data) {
            $('#lgtyp').val(data.LGTYP);
            $('#lgtypName').val(data.LTYPT);
        }
    });
     //默认采购组 --采购视图
    $('#ekgrpName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "EKGRP"}
        },
        onChange: function (value, data) {
            $('#ekgrp').val(data.EKGRP);
            $('#ekgrpName').val(data.EKNAM);
        }
    });
    //采购计量单位
    $('#bstmeName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "MEINS"}
        },
        onChange: function (value, data) {
           if ($('#meins').val()==data.MSEH3) {
               Public.errorTip("不能与基本计量单位相同！");
               $('#bstme').val("");
               $('#bstmeName').val("");
               UICtrl.setElRequiredFlag("#umrenPurch",false);
               UICtrl.setElRequiredFlag("#umrezPurch",false);
           } else {
             $('#bstme').val(data.MSEH3);
             $('#bstmeName').val(data.MSEHL);
               UICtrl.setElRequiredFlag("#umrenPurch",true);
               UICtrl.setElRequiredFlag("#umrezPurch",true);
          }
        }
    });
    bindEvent_sale(); //销售视图
    bindEvent_mrp();
    //库存地点--存储管理
    $('#lgortQmName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {
                fieldName: "LGORT",
                filterValue:$("#werks").val()
            }
        },
        onChange: function (value, data) {
            $('#lgortQm').val(data.LGORT);
            $('#lgortQmName').val(data.LGOBE);
        }
    });
    $('#fevor').searchbox({  //生产主管
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "T024F", filterValue: $('#werks').val()}
        },
        onChange: function (value, data) {
            $('#fevor').val(data.FEVOR);
          //  $('#fevorName').val(data.LGOBE);
        }
    });
    //投料计量单位
    $('#ausmeName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "MEINS"}
        },
        onChange: function (value, data) {
            if ($('#meins').val()==data.MSEH3) {
                Public.errorTip("不能与基本计量单位相同！");
                $('#ausme').val("");
                $('#ausmeName').val("");
                UICtrl.setElRequiredFlag("#umrenProd",false);
                UICtrl.setElRequiredFlag("#umrezProd",false);
            }else {
                $('#ausme').val(data.MSEH3);
                $('#ausmeName').val(data.MSEHL);
                UICtrl.setElRequiredFlag("#umrenProd",true);
                UICtrl.setElRequiredFlag("#umrezProd",true);
            }
        }
    });
    //品牌选择
    $('#mvgr1').searchbox({
        type: "system", name: "selectEpBrandByItemCode",
        getParam: function (item) {
            return {itemCode: $("#matnr").val()}
        },
        onChange: function (value, data) {
            $('#mvgr1').val(data.code);
        }
    });
    bindEvent_warehouse();

    //MRP类型
    $("#dismm").combox({onChange:function(data) {
            if (data.value=='ND'){
                mrpMustInput(false);
            } else {
                mrpMustInput(true);
            }
        }
    });

    //参考物料选择
    $("#copyMatnr").searchbox({
        type: "material", name: "selectMaterials",
        getParam: function (item) {
            if (Public.isBlank($('#mtart').val())){
                Public.tip("请先选择物品类型！")
                return false
            }
            if (Public.isBlank($('#matkl').val())){
                Public.tip("请先选择物料组！")
                return false
            }
            return {
                mtart: $("#mtart").val(),
                matkl: $("#matkl").val()
            }
        },
        onChange: function (value, data) {
            //先清空勾选视图
            $("input[name='businessUsage']").each(function(){
                $(this).prop("checked",false);
                hideAllBusiness(true);
            })

            $("#copyMatnr").val(value.text);
            var mtart = $("#mtart").val();
            var matkl = $("#matkl").val();
            if (Public.isBlank(mtart)){
                $("#mtart").val(data.mtart)
                $("#mtart_text").val(data.mtartTextView)
            }
            if (Public.isBlank(matkl)){
                $("#matkl").val(data.matkl)
                $("#matklName").val(data.matklName)
            }
            //$("#groes").val(data.groes)
            $("#spartName").val(data.spartName)
            $("#spart").val(data.spart)
            $("#mtposMara").val(data.mtposMara)
            //$("#maktx").val(data.maktx)
            $("#xchpf").val(data.xchpf)
            $("#xchpf_text").val(data.xchpfTextView)
            $("#maktxEn").val(data.maktxEn)
            //$("#meinsName").val(data.meinsName)
            //$("#meins").val(data.meins)
            $("#werksName").val(data.werksName)
            $("#werks").val(data.werks)
            $("#lgortName").val(data.lgortName)
            $("#lgort").val(data.lgort)
            $("#raube").val(data.raube)
            $("#raube_text").val(data.raubeTextView)
            $("#brgew").val(data.brgew)
            $("#gewei").val(data.gewei)
            $("#gewei_text").val(data.geweiTextView)
            $("#volum").val(data.volum)
            $("#voleh").val(data.voleh)
            $("#voleh_text").val(data.volehTextView)
            $("#iprkz").val(data.iprkz)
            $("#iprkz_text").val(data.iprkzTextView)
            $("#mhdhb").val(data.mhdhb)
            $("#mhdrz").val(data.mhdrz)
            $("#normt").val(data.normt)
            $("#length").val(data.length)
            $("#widthCm").val(data.widthCm)
            $("#thickness").val(data.thickness)
            $("#weight").val(data.weight)
            $("#singleThickness").val(data.singleThickness)
            $("#klart").val(data.klart)
            $("#classify").val(data.class)
            //$("#maktxRemZh").val(data.maktxRemZh)
            //$("#maktxRemEn").val(data.maktxRemEn)
            //$("#businessUsage").val(data.businessUsage)
            var businessUsages = data.businessUsage;
            var businessUsageStr = businessUsages.split(",");
            for (let i = 0; i < businessUsageStr.length; i++) {
                var businessUsageVal = businessUsageStr[i];
                var id = "businessUsage"+businessUsageVal;
                $("#"+id).prop("checked",true);
                coRowNum=MathUtil.add(coRowNum,1);
                showBusiness(businessUsageVal)
            }
            $("#isAll").val(data.isAll)

            $("#lgtypName").val(data.lgtypName)
            $("#lgtyp").val(data.lgtyp)
            $("#mtvfp").val(data.mtvfp)
            $("#mtvfp_text").val(data.mtvfpTextView)

            //销售视图
            $("#vkorgName").val(data.vkorgName)
            $("#vkorg").val(data.vkorg)
            $("#vtwegName").val(data.vtwegName)
            $("#vtweg").val(data.vtweg)
            $("#vrkmeName").val(data.vrkmeName)
            $("#vrkme").val(data.vrkme)
            $("#umrenSale").val(data.umrenSale)
            $("#umrezSale").val(data.umrezSale)
            $("#dwerkName").val(data.dwerkName)
            $("#dwerk").val(data.dwerk)
            $("#alandName").val(data.alandName)
            $("#aland").val(data.aland)
            $("#taxkm").val(data.taxkm)
            $("#taxkm_text").val(data.taxkmTextView)
            $("#versg").val(data.versg)
            $("#versg_text").val(data.versgTextView)
            $("#kondm").val(data.kondm)
            $("#kondm_text").val(data.kondmTextView)
            $("#ktgrm").val(data.ktgrm)
            $("#ktgrm_text").val(data.ktgrmTextView)
            $("#prodh").val(data.prodh)
            //$("#mvgr1").val(data.mvgr1)
            $("#mvgr2").val(data.mvgr2)
            $("#mvgr2_text").val(data.mvgr2TextView)
            // $("#mvgr3").val(data.mvgr3)
            // $("#mvgr4").val(data.mvgr4)
            // $("#mvgr5").val(data.mvgr5)
            //2
            $("#mtpos").val(data.mtpos)
            $("#mtpos_text").val(data.mtposTextView)
            $("#tragr").val(data.tragr)
            $("#tragr_text").val(data.tragrTextView)
            $("#ladgr").val(data.ladgr)
            $("#ladgrName").val(data.ladgrName)

            //采购视图
            $("#bstmeName").val(data.bstmeName)
            $("#bstme").val(data.bstme)
            $("#umrenPurch").val(data.umrenPurch)
            $("#umrezPurch").val(data.umrezPurch)
            $("#ekgrpName").val(data.ekgrpName)
            $("#ekgrp").val(data.ekgrp)
            $("#mmsta").val(data.mmsta)

            //MRP视图
            $("#rgekz").val(data.rgekz)
            $("#rgekz_text").val(data.rgekzTextView)
            $("#strgr").val(data.strgr)
            $("#strgr_text").val(data.strgrTextView)
            $("#sbdkz").val(data.sbdkz)
            $("#sbdkz_text").val(data.sbdkzTextView)
            $("#vrmod").val(data.vrmod)
            $("#vrmod_text").val(data.vrmodTextView)
            $("#vint1").val(data.vint1)
            $("#vint2").val(data.vint2)
            $("#perkz").val(data.perkz)
            $("#perkz_text").val(data.perkzTextView)
            $("#dismm").val(data.dismm)
            $("#dismm_text").val(data.dismmTextView)
            $("#dispo").val(data.dispo)
            $("#dispo_text").val(data.dispoTextView)
            $("#disls").val(data.disls)
            $("#disls_text").val(data.dislsTextView)
            $("#bstmi").val(data.bstmi)
            $("#bstrf").val(data.bstrf)
            $("#lgproName").val(data.lgproName)
            $("#lgpro").val(data.lgpro)
            $("#lgfsbName").val(data.lgfsbName)
            $("#lgfsb").val(data.lgfsb)

            //$("#disgr").val(data.disgr)
            //$("#disgr_text").val(data.disgrTextView)
            $("#minbe").val(data.minbe)
            $("#bstfe").val(data.bstfe)
            $("#bstma").val(data.bstma)
            $("#beskz").val(data.beskz)
            $("#beskz_text").val(data.beskzTextView)
            $("#sobsl").val(data.sobsl)
            $("#sobsl_text").val(data.sobslTextView)
            $("#webaz").val(data.webaz)
            $("#dzeit").val(data.dzeit)
            $("#fhori").val(data.fhori)
            $("#eisbe").val(data.eisbe)
            $("#eislo").val(data.eislo)
            $("#wzeit").val(data.wzeit)
            $("#plifz").val(data.plifz)
            $("#diskz").val(data.diskz)
            $("#diskz_text").val(data.diskzTextView)
            //$("#miskz_text").val(data.miskzTextView)
            //$("#miskz").val(data.miskz)

            //生产视图
            $("#fevor").val(data.fevor)
            $("#sfcpf").val(data.sfcpf)
            $("#sfcpf_text").val(data.sfcpfTextView)
            $("#ausmeName").val(data.ausmeName)
            $("#ausme").val(data.ausme)
            $("#umrenProd").val(data.umrenProd)
            $("#umrezProd").val(data.umrezProd)
            $("#ueetk").val(data.ueetk);
            $("#ueetk_text").val(data.ueetkTextView);

            //存储视图
            $("#lgortQmName").val(data.lgortQmName)
            $("#lgortQm").val(data.lgortQm)
            $("#sernp").val(data.sernp)
            $("#sernp_text").val(data.sernpTextView)
            $("#serlv").val(data.serlv)
            $("#prctr").val(data.prctr)
            $("#prctr_text").val(data.prctrTextView)
            $("#insmk").val(data.insmk)
            $("#insmk_text").val(data.insmkTextView)
            $("#sledBbd").val(data.sledBbd)
            $("#sledBbd_text").val(data.sledBbdTextView)

            //仓库视图
            $("#lgnumName").val(data.lgnumName)
            $("#lgnum").val(data.lgnum)
            $("#lgortProfitName").val(data.lgortProfitName)
            $("#lgortProfit").val(data.lgortProfit)
            $("#ltkzaName").val(data.ltkzaName)
            $("#ltkza").val(data.ltkza)
            $("#lety1").val(data.lety1)
            $("#lhmg1").val(data.lhmg1)
            $("#lhme1Name").val(data.lhme1Name)
            $("#lhme1").val(data.lhme1)
            $("#ltkzeName").val(data.ltkzeName)
            $("#ltkze").val(data.ltkze)
            $("#lgbkz").val(data.lgbkz)

            //财务视图
            $("#bklas").val(data.bklas)
            $("#vprsv").val(data.vprsv)
            $("#vprsv_text").val(data.vprsvTextView)
            $("#mlast").val(data.mlast)
            $("#mlast_text").val(data.mlastTextView)
            $("#peinh").val(data.peinh)
            $("#ncost").val(data.ncost)
            $("#ncost_text").val(data.ncostTextView)
            $("#hkmat").val(data.hkmat)
            $("#hkmat_text").val(data.hkmatTextView)
            $("#verpr").val(data.verpr)
            $("#stprs").val(data.stprs)
            $("#ekalr").val(data.ekalr)
            $("#ekalr_text").val(data.ekalrTextView)
            $("#awsls").val(data.awsls)
            $("#eklas").val(data.eklas)
        }
    });

    //正面图片
    var _img=$('#showFrontPicture');
    var _frontPicturePath=$('#frontPicturePath').val();
    if (Public.isNotBlank(_frontPicturePath)) {
        _img[0].src = $.getCSRFUrl('attachment/downFileBySavePath.ajax',{file:_frontPicturePath});
    }
    $('#addFrontPicture').uploadButton({
        filetype: ['jpg','gif','jpeg','png','bmp'],
        afterUpload: function(data){
            _img[0].src = $.getCSRFUrl('attachmentDownFile.ajax',{id:data.id});
        },
        param: function(){
            return {bizCode: 'frontPicture', bizId: $("#id").val(), flag: 'false', deleteOld: 'true', returnPath: 'true'};
        }
    });

    //反面图片
    var back_img=$('#showBackPicture');
    var _backPicturePath=$('#backPicturePath').val();
    if (Public.isNotBlank(_backPicturePath)) {
        back_img[0].src = $.getCSRFUrl('attachment/downFileBySavePath.ajax',{file:_backPicturePath});
    }
    $('#addBackPicture').uploadButton({
        filetype: ['jpg','gif','jpeg','png','bmp'],
        afterUpload: function(data){
            back_img[0].src = $.getCSRFUrl('attachmentDownFile.ajax',{id:data.id});
        },
        param: function(){
            return {bizCode: 'backPicture', bizId: $("#id").val(), flag: 'false', deleteOld: 'true', returnPath: 'true'};
        }
    });

    $("#maktx").click(function () {
        if ($('#maktx').prop('readonly')) {
            return;
        }
        UICtrl.showAjaxDialog({
            title: '汉语品名维护',
            width: 700,
            height: 400,
            url: web_app.name + '/sapNonProdApply/showMaterialNameElement.load',
            param:{billCode:$("#submitForm #billCode").val()},
            init: function (){

            },
            ok: function () {
                var result = $("#materialNameElement #maktx").val();
                var specifications = $("#materialNameElement #specifications").val();
                var thickness = $("#materialNameElement #thickness").val();
                var weight = $("#materialNameElement #weight").val();
                var maktxRemZh = $("#materialNameElement #maktxRemZh").val();
                $('#materialNameElement').ajaxSubmit({
                    url: web_app.name + '/sapNonProdApply/saveMaterialNameElement.ajax',
                    param: "",
                    success: function (data) {
                        $("#maktx").val(result);
                        $("#groes").val(specifications);
                        $("#thickness").val(thickness);
                        $("#weight").val(weight);
                        $("#maktxRemZh").val(maktxRemZh);
                    }
                });
                this.close();
            }
        })
    })

    //集团级删除、启用填写原因
    $("#lvorm").combox({onChange:function(data){
            bindEvent_lvorm(data.value)
        }
    });
}

function bindEvent_lvorm(data){
    if (data=='X'){
        UICtrl.setElRequiredFlag("#disableReason",true);
        UICtrl.setElRequiredFlag("#enableReason",false);
        $("#enableReason").val("");
    }else if (data=='0'){
        UICtrl.setElRequiredFlag("#disableReason",false);
        UICtrl.setElRequiredFlag("#enableReason",true);
        $("#disableReason").val("");
    }else {
        UICtrl.setElRequiredFlag("#disableReason",false);
        UICtrl.setElRequiredFlag("#enableReason",false);
        $("#disableReason").val("");
        $("#enableReason").val("");

    }
}

function bindEvent_sale() {
    $('#vkorgName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "VKORG"}
        },
        onChange: function (value, data) {
            $('#vkorg').val(data.VKORG);
            $('#vkorgName').val(data.VTEXT);
        }
    });
    $('#vtwegName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {
                fieldName: "VTWEG",
                filterValue: $('#vkorg').val()
            }
        },
        onChange: function (value, data) {
            $('#vtweg').val(data.VTWEG);
            $('#vtwegName').val(data.VKORGTEXT);
        }
    });


    $('#ladgrName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "LADGR"}
        },
        onChange: function (value, data) {
            $('#ladgr').val(data.LADGR);
            $('#ladgrName').val(data.LADGRTEXT);
        }
    });


    $('#vrkmeName').searchbox({ //销售记量单位
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {
                fieldName:"MEINS"
            }
        },
        onChange: function (value, data) {
            if ($('#meins').val()==data.MSEH3) {
                Public.errorTip("不能与基本计量单位相同！");
                $('#vrkme').val("");
                $('#vrkmeName').val("");
                UICtrl.setElRequiredFlag("#umrenSale",false);
                UICtrl.setElRequiredFlag("#umrezSale",false);
            }else {
                $('#vrkme').val(data.MSEH3);
                $('#vrkmeName').val(data.MSEHL);
                UICtrl.setElRequiredFlag("#umrenSale",true);
                UICtrl.setElRequiredFlag("#umrezSale",true);
            }

        }
    });

    //交货工厂
    $('#dwerkName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "WERKS"}
        },
        onChange: function (value, data) {
            $('#dwerk').val(data.WERKS);
            $('#dwerkName').val(data.NAME1);
        }
    });

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

function bindEvent_mrp(){
    if ($('#vint1').val()==''){
        $('#vint1').val("999");
    }
    if ($('#vint2').val()==''){
        $('#vint2').val("999");
    }
    if ($('#vrmod').val()==''){ //消耗模式
        $('#vrmod').val("2");
    }
    $('#lgproName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {
                fieldName: "LGORT",
                filterValue:$('#werks').val()
            }
        },
        onChange: function (value, data) {
            $('#lgpro').val(data.LGORT);
            $('#lgproName').val(data.LGOBE);
        }
    });
    $('#lgfsbName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {
                fieldName: "LGORT",
                filterValue:$('#werks').val()
            }
        },
        onChange: function (value, data) {
            $('#lgfsb').val(data.LGORT);
            $('#lgfsbName').val(data.LGOBE);
        }
    });


    /*$('#minbeName').searchbox({  重订货点
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {
                fieldName: "MINBE",
                //filterValue:$('#lgnum').val()
            }
        },
        onChange: function (value, data) {
            $('#minbe').val(data.MINBE);
            $('#minbeName').val(data.NAME);
        }
    }); */

    $('#dispoName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {
                fieldName: "DISPO",
                //filterValue:$('#lgnum').val()
            }
        },
        onChange: function (value, data) {
            $('#dispo').val(data.DISPO);
            $('#dispoName').val(data.NAME);
        }
    });

    $("#sbdkz").combox({onChange:function(data){
        var mtart = $("#mtart").val();
        //物料类型只有选了这两种类型后，可以不填，其他值只能选2
        if (mtart != "ZZCP" && mtart != "ZSHB") {
            if (data.value != "2"){
                $("#sbdkz").val("")
                $("#sbdkz_text").val("")
                Public.tip("物料类型不是产成品和自制机械设备时，只能选”只汇总请求“")
            }
        }
        }
    });
}

function bindEvent_warehouse(){
   // $("#lety1").val("TP");
    //库存地点
    $('#lgortProfitName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
           return {fieldName: "LGORT", filterValue: $('#werks').val()}
        },
        onChange: function (value, data) {
            $('#lgortProfit').val(data.LGORT);
            $('#lgortProfitName').val(data.LGOBE);
            //  $('#ltkza').val("001");
            //   $('#ltkzaName').val("高架仓库");
        }
    });
    //存储类型
    $('#lgtypName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {
                fieldName: "LGTYP",
                filterValue:$('#lgnum').val(),
            }
        },
        onChange: function (value, data) {
            $('#lgtyp').val(data.LGTYP);
            $('#lgtypName').val(data.LTYPT);
        }
    });
    //存货下架存储类型
    $('#ltkzaName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {
                fieldName: "LGTYP",
                filterValue:$('#lgnum').val()
            }
        },
        onChange: function (value, data) {
            $('#ltkza').val(data.LGTYP);
            $('#ltkzaName').val(data.LTYPT);
        }
    });
    //存货上架存储类型
    $('#ltkzeName').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {
                fieldName: "LGTYP",
                filterValue:$('#lgnum').val()
            }
        },
        onChange: function (value, data) {
            $('#ltkze').val(data.LGTYP);
            $('#ltkzeName').val(data.LTYPT);
        }
    });
    //存储分区标识
    // $('#lgbkzName').searchbox({
    //     type: "system", name: "dictionary",
    //     getParam: function (item) {
    //         return {
    //             fieldName: "LGTYP",
    //             filterValue:$('#lgnum').val()
    //         }
    //     },
    //     onChange: function (value, data) {
    //         $('#lgbkz').val(data.LGTYP);
    //         $('#lgbkzName').val(data.LTYPT);
    //     }
    // });

    $('#lhme1Name').searchbox({
        type: "system", name: "dictionary",
        getParam: function (item) {
            return {fieldName: "MEINS"}
        },
        onChange: function (value, data) {
            $('#lhme1').val(data.MSEH3);
            $('#lhme1Name').val(data.MSEHL);
        }
    });
}


function getExtendedData() {
    let msg = "[";
    let isUndefined = false;
    let extendedData = {};
  /*  let deptStaffResult = DataUtil.getGridData({
        gridManager: gridManager,
        isAllData: true,
        onCheck: function (data) {
            if (typeof data.userCode === 'undefined') {
                msg += `${data.deptName}`;
                isUndefined = true;
            }
            return true;
        }
    }); */
        let deptStaffResult = gridManager.getData();
        for (var i = 0; i < deptStaffResult.length; i++) {
            //  alert(deptStaffResult[i].deptName); alert(deptStaffResult[i].userCode);
            if (deptStaffResult[i].userCode == undefined) {
                //if (isUndefined) {
                isUndefined = true;
                break;
            }
        }
        if (isUndefined) {
            Public.tip(deptStaffResult[i].deptName + '未选择对应分发人员');
            return false
        }
        extendedData.deptStaff = Public.encodeJSONURI(deptStaffResult);
      return extendedData;
}


function rejectForm() {
    $('#auditForm').ajaxSubmit({
        url: web_app.name + '/sapNonProdApplyNext/rejectNonProdApplyDept.ajax',
        param: {meId:getMeId()},
        success: function (data) {
            Public.successTip("已驳回！");
            _self.close();
        }
    });

}

function checkThrough(){
    $('#exPass').ajaxSubmit({
        url: web_app.name + '/sapNonProdApplyNext/rejectNonProdApplyDept.ajax',
        param: {meId:getMeId()},
        success: function (data) {
            Public.successTip("检查通过！");
            _self.close();
        }
    });
}


/**
 * 根据选择的驳回的部门生成输入框
 */
function loadRejectReasonBox() {
    $('input[name="auditDept"]').change(function () {
            let val = $(this).val()
            let textData = $(this).parent().text().trim()
            if (this.checked) {
                if ($(`#id_${val}`).length) {
                    // 元素存在
                    $(`#id_${val}`).show();
                } else {
                    // 元素不存在
                    let box = `<div id="id_${val}">
                            <div class="col-xs-4 col-sm-2" style="height:60px;">
                                <label class="hg-form-label" name="${val}" title="[${textData}]驳回原因">[${textData}]驳回原因&nbsp;:</label>
                             </div>
                             <div class="col-xs-8 col-sm-10 col-warp col-white-bg" style="height:60px;">
                                <textarea name="${val}"  label="[${textData}]驳回原因" id="text_${val}"></textarea>
                             </div>
                        </div>`;
                    $("#rejectReasonBox").append(box)
                }
                $(window).scrollTop($(document).height());
            } else {
                $(`#id_${val}`).hide();
            }
        }
    );
}

/**
 *根据驳回信息生成驳回信息展示栏
 */
/*function showRejectCauseBox() {
    Public.ajax(web_app.name + '/sapNonProdApplyNext/slicedRejectCauseList.ajax', {meId: getMeId()}, function (data) {
        const generateCauseHTML = (item, newCause) => {
            const { rectifyDate, rejectMsg, bsnExecuteId, rejectDate } = item;
            return `
    <div class="hg-form-row">
      <div class="col-xs-4 col-sm-1" style="height:56px;">
        <label class="hg-form-label" title="驳回原因">驳回原因${newCause}&nbsp;:</label>
      </div>
      <div class="col-xs-8 col-sm-11 col-warp col-gray-bg" style="height:56px;">
        <textarea rows="2" label="驳回原因" readonly="readonly">${rejectMsg}</textarea>
      </div>
    </div>
    <div class="hg-form-row">
      <div class="col-xs-4 col-sm-1">
        <label class="hg-form-label" title="驳回人">驳回人&nbsp;:</label>
      </div>
      <div class="col-xs-8 col-sm-3 col-warp col-gray-bg">
        <input type="text" value="${bsnExecuteId}" readonly="readonly" label="驳回人">
      </div>
      <div class="col-xs-4 col-sm-1">
        <label class="hg-form-label" title="驳回时间">驳回时间&nbsp;:</label>
      </div>
      <div class="col-xs-8 col-sm-3 col-warp col-gray-bg">
        <input type="text" value="${rejectDate}" readonly="readonly" label="驳回时间">
      </div>
      <div class="col-xs-4 col-sm-1">
        <label class="hg-form-label" title="处理时间">处理时间&nbsp;:</label>
      </div>
      <div class="col-xs-8 col-sm-3 col-warp col-gray-bg">
        <input type="text" value="${rectifyDate}" readonly="readonly" label="处理时间">
      </div>
    </div>
  `;
        };
        let newCause = `<span style="color:red;">new</span>`;
        const ahtml = data
            .map((item) => {
                const cause = item.rectifyDate === '' ? `[${newCause}]` : '';
                return generateCauseHTML(item, cause);
            })
            .join('');

        $("#cause-details-box").html(ahtml);
        $("#causeBox").show();
    })

} */

function getMeId() {
    return $("#meId").val() || '';
}

function setBklasByMatklAndMtart(value,mtart){
    if ("ZBZP" == mtart){
        if (value == "900"){// 900	办公文具	6000
            $("#bklas").val("6000");
        }else if (value == "92001"){// 92001	建材类 	6002
            $("#bklas").val("6002");
        }else if (value == "92002"){// 92002	劳保用品	6003
            $("#bklas").val("6003");
        }else if (value == "92003"){// 92003	清洁用品	6005
            $("#bklas").val("6005");
        }else if (value == "92004"){// 92004	食品调料	6006
            $("#bklas").val("6006");
        }else if (value == "92005"){// 92005	五金备件	6007
            $("#bklas").val("6007");
        }else if (value == "92006"){// 92006	市场公关品 	6008
            $("#bklas").val("6008");
        }else if (value == "92007"){// 92007	餐厨用具	6009
            $("#bklas").val("6009");
        }else if (value == "92008"){// 92008	广告宣传品 	6010
            $("#bklas").val("6010");
        }else if (value == "92009"){// 92009	员工福利用品	6011
            $("#bklas").val("6011");
        }
    }
}