public without sharing class OutboundorderImportController {
  //经销商产品分类
  public String agencyProType {get;set;}
  private String sqlagencyProType ;
  public Blob csvFileBody{get;set;}
  public string csvAsString{get;set;}
  public String[] csvFileLines{get;set;}
  public List<ConsumableorderdetailsInfo> orderRecords { get; set; }
  List<String []> csvRecordStr = new List<String []>();
  public Map<String,String> hospitalconMap = new Map<String,String>();
  public Map<String,String> product2conMap = new Map<String,String>();
  public Map<String,String> hospitalSysMap = new Map<String,String>();
  public Map<String,String> secondAgencyMap = new Map<String,String>();
  private String accountid = null;
  private String accountName = null;
  private Integer messageCount;
  public boolean saveFLGbln {get;set;}
  private List<String> barcodeList = new List<String>();
  private List<String> barcodePieceList = new List<String>();
  public Map<String,Integer> barcodePieceMap = new Map<String,Integer>();
  public boolean errorflg {get;set;}
  public String errorMessage {get;set;}
  // 登录者工作地
  private String userWorkLocation;
    public OutboundorderImportController() {
      csvFileLines = new String[]{};
      orderRecords = new List<ConsumableorderdetailsInfo>();
      saveFLGbln= false;
      messageCount = 0;
    }

  public void init() {
    messageCount = 0;
    errorflg = false;
    errorMessage =null;
    //User useracc = [SELECT accountid FROM user WHERE id ='00510000005QO75'];
    User useracc = [SELECT accountid, Work_Location__c,UserPro_Type__c FROM user WHERE id =:UserInfo.getUserId()];
    accountid = Useracc.accountid;
    userWorkLocation = Useracc.Work_Location__c;
    agencyProType = Useracc.UserPro_Type__c;
    if(String.isBlank(Useracc.UserPro_Type__c)){
      agencyProType = 'ET';
    }
    sqlagencyProType = '%' + agencyProType + '%';
    Account accountInfo = [SELECT Name FROM account WHERE id =:accountid];
    accountName = accountInfo.name;
  }

    public void importCSVFile(){
    messageCount = 0;
    errormessage = null;
    saveFLGbln= false;
    csvRecordStr = new List<String []>();
    barcodeList = new List<String>();
    barcodePieceMap = new Map<String,Integer>();
    barcodePieceList = new List<String>();
    orderRecords = new List<ConsumableorderdetailsInfo>();
    if(csvFileBody == null){
        errorflg = true;
        saveFLGbln = true;
        errormessage = '读取内容为空。';
    }else{
      //产品数据查找
      map<string,string> orderNameMap = new map<string,string>();
      try{
        csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n');
        for(Integer i=0;i<csvFileLines.size();i++){
          string[] csvRecordData = csvFileLines[i].split(',');
          if(String.isNotBlank(csvRecordData[6])){
              barcodeList.add(csvRecordData[6]);
              if(String.valueOf(csvRecordData[9]) == '个'){
                barcodePieceList.add(csvRecordData[6]);
                barcodePieceMap.put(csvRecordData[6], Integer.valueOf(csvRecordData[7]));
              }
          }
          String[] csvRecordDataStr = new String[13];
          for(Integer j=0;j<csvRecordData.size();j++){
            csvRecordDataStr[j] = csvRecordData[j];
          }
          if(i==0){
            csvRecordDataStr[12] = '产品';
          }else{
            csvRecordDataStr[12] = '';
          }
          csvRecordStr.add(csvRecordDataStr);
        }
        Map<String,String> productBarcodeMap = new Map<String,String>();
        List<Consumable_order_details2__c> cOrderDet = [SELECT Id,
                            Bar_Code__c,
                            Name,
                            Consumable_Product__c,
                            Box_Piece__c
                        FROM Consumable_order_details2__c
                        WHERE  Dealer_Arrive__c = true
                        AND Dealer_Shipment__c = false
                        AND Dealer_Saled__c = false
                        AND Lose_Flag__c = false
                        AND Bar_Code__c in : barcodeList
                        AND Product_Type__c like : sqlagencyProType
                        AND Arrive_Owner_Work_Location__c =: userWorkLocation
                        AND Dealer_Info_text__c = :accountName];
        for(Consumable_order_details2__c pdinfo :cOrderDet){
          productBarcodeMap.put(pdinfo.Bar_Code__c, pdinfo.Consumable_Product__c);
        }
        for(String [] csvlistStr : csvRecordStr){
          if(productBarcodeMap.containsKey(csvlistStr[6])){
            csvlistStr[12] = productBarcodeMap.get(csvlistStr[6]);
          }else{
          }
        }
        //检索存在拆盒产品数量
        Map<String,Integer> exitpieceBarcodeMap = new Map<String,Integer>();
        AggregateResult[] pieceOrderDet = [SELECT count(Id) cnt,
                            Bar_Code__c
                        FROM Consumable_order_details2__c
                        WHERE  Dealer_Arrive__c = true
                        AND Dealer_Shipment__c = false
                        AND Dealer_Saled__c = false
                        AND Lose_Flag__c = false
                        AND Bar_Code__c in : barcodePieceList
                        AND Product_Type__c like : sqlagencyProType
                        AND Dealer_Info_text__c = :accountName
                        AND Arrive_Owner_Work_Location__c =: userWorkLocation
                        AND Box_Piece__c = '个'
                        group by Bar_Code__c];
        for(AggregateResult ar :pieceOrderDet){
          exitpieceBarcodeMap.put(String.valueOf(ar.get('Bar_Code__c')), Integer.valueOf(ar.get('cnt')));
        }
        for(String bc : barcodePieceList){
          if(!exitpieceBarcodeMap.containsKey(bc)){
            if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, 'Barcode ' + bc + ' 不存在或单位错误，请确认。'));
              saveFLGbln= true;
              messageCount ++;
          }else if(exitpieceBarcodeMap.containsKey(bc) && exitpieceBarcodeMap.get(bc) < barcodePieceMap.get(bc)){
            if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, 'Barcode ' + bc + ' 库存不足，请确认。'));
              saveFLGbln= true;
              messageCount ++;
          }
        }
      }catch (Exception e)
      {
          ApexPages.addMessages(e);
      }
      getorderinfo();
      dataInfoconfim();
      getorderdet2info(csvRecordStr);
      if(saveFLGbln == false){
        getorderdetinfo(csvRecordStr);
      }
    }
    }
    public void getorderinfo(){
        map<string,string> orderNameMap = new map<string,string>();
        try{
            csvAsString = csvFileBody.toString();
            csvFileLines = csvAsString.split('\n');
          for(Integer i=1;i<csvFileLines.size();i++){
            Consumable_order__c cocObj = new Consumable_order__c() ;
            string[] csvRecordData = csvFileLines[i].split(',');
            if(orderNameMap.containsKey(csvRecordData[0])) continue;
            cocObj.Name                     = csvRecordData[0];
            if(String.isNotBlank(csvRecordData[1])){
              cocObj.SummonsForDirction__c    = csvRecordData[1];
             }else{
              if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + csvRecordData[0] + '出货目的为空，请确认。'));
              saveFLGbln= true;
              messageCount ++;
             }
            cocObj.Order_Attachment__c      = csvRecordData[2];
            cocObj.Order_Indication__c      = csvRecordData[3];
            cocObj.Order_ForCustomerText__c = csvRecordData[4];
            cocObj.Invoice_Note__c          = csvRecordData[5];
            if(String.isBlank(csvRecordData[11])){
              if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + cocObj.Name + '的产品中，存在出库日期为空，请确认。'));
              saveFLGbln= true;
              messageCount ++;
            }else{
              cocObj.Outbound_Date__c         = Date.parse(csvRecordData[11].trim());
            }
            if(String.isNotEmpty(csvRecordData[2])){
                    hospitalconMap.put(csvRecordData[2].trim(), csvRecordData[0].trim());
            }
            orderNameMap.put(csvRecordData[0],csvRecordData[0]);
            orderRecords.add(new ConsumableorderdetailsInfo(cocObj));
         }
      }
      catch (Exception e)
      {
          ApexPages.addMessages(e);
      }
    }
    public void getorderdetinfo(List<String []> csvRecordStr){
        map<string,string> orderdetMap = new map<string,string>();
        try{
            for(Integer i=1;i<csvRecordStr.size();i++){
             Consumable_Orderdetails__c codObj = new Consumable_Orderdetails__c() ;
             string[] csvRecordData = csvRecordStr[i];
             if(orderdetMap.containsKey(csvRecordData[0] + csvRecordData[12])) continue;
             codObj.Remarks__c             = csvRecordData[0] ;
             if(String.isBlank(csvRecordData[7])){
              if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + csvRecordData[0] + '产品出货数量为空，请确认。'));
              saveFLGbln= true;
              messageCount ++;
             }else if(Decimal.valueOf(csvRecordData[7]) > 1 && String.valueOf(csvRecordData[9]) == '盒'){
              if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + csvRecordData[0] + '存在单位是盒，产品出货数量大于1，请确认。'));
              saveFLGbln= true;
              messageCount ++;
             }else{
              codObj.Shipment_Count__c      =  Decimal.valueOf(csvRecordData[7]);
             }
             codObj.Box_Piece__c           =  csvRecordData[9];
             if(String.isNotBlank(csvRecordData[8])){
              codObj.Delivery_List_RMB__c   = Decimal.valueOf(csvRecordData[8]);
             }else{
              if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + csvRecordData[0] + '产品出货单价为空，请确认。'));
              saveFLGbln= true;
              messageCount ++;
             }
             //if(String.isNotBlank(csvRecordData[10])){
             // codObj.Unitprice_To_agency__c = Decimal.valueOf(csvRecordData[10]);
             //}
             codObj.Lose_reason__c        = csvRecordData[12];
             codObj.Used_date__c = Date.parse(csvRecordData[11].trim());
             product2conMap.put(csvRecordData[12].trim(), csvRecordData[12].trim());
             orderdetMap.put(csvRecordData[0] + csvRecordData[12],csvRecordData[0] + csvRecordData[12]);
             //orderdetRecords.add(new ConsumableorderdetailsInfo(codObj));
          }

      }
      catch (Exception e)
      {
          ApexPages.addMessages(e);
      }
    }

    public void getorderdet2info(List<String []> csvRecordStr){
    barcodeList = new List<String>();
        try{
            for(Integer i=1;i<csvRecordStr.size();i++){
            Consumable_Order_details2__c cod2Obj = new Consumable_Order_details2__c() ;
            string[] csvRecordData         = csvRecordStr[i];
            cod2Obj.TracingCode__c         = csvRecordData[0] ;
            cod2Obj.Bar_Code__c            = csvRecordData[6];
            if(String.isNotBlank(csvRecordData[6])){
              barcodeList.add(csvRecordData[6]);
            }
            if(String.isBlank(csvRecordData[9])){
              if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + cod2Obj.TracingCode__c + '的barcode ' + cod2Obj.Bar_Code__c + ' 不存在出库单位，请确认。'));
              saveFLGbln= true;
              messageCount ++;
            }else if(String.valueOf(csvRecordData[9]) != '盒' && String.valueOf(csvRecordData[9]) != '个'){
              if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + cod2Obj.TracingCode__c + '的barcode ' + cod2Obj.Bar_Code__c + ' 出库单位不正确，请确认。'));
              saveFLGbln= true;
              messageCount ++;
            }else{
              cod2Obj.Box_Piece__c           =  csvRecordData[9];
            }
            if(String.isBlank(csvRecordData[8])){
              if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + cod2Obj.TracingCode__c + '产品出货单价为空，请确认。'));
              saveFLGbln= true;
              messageCount ++;
             }else if(String.isNotBlank(csvRecordData[8])){
              if(Decimal.valueOf(csvRecordData[8]) == 0 && (String.valueOf(csvRecordData[1]) == '直接销售给医院' || String.valueOf(csvRecordData[1]) == '销售给二级经销商')){
                if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + cod2Obj.TracingCode__c + '产品出货单价不能为0，请确认。'));
              saveFLGbln= true;
              messageCount ++;
                }else{
                  cod2Obj.Delivery_List_RMB__c   = Decimal.valueOf(csvRecordData[8]);
                }
            }
            //if(String.isNotBlank(csvRecordData[10])){
            //  cod2Obj.Unitprice_To_agency__c = Decimal.valueOf(csvRecordData[10]);
            //}//销售给二级经销商 时，可以录入
            /*else if(String.valueOf(csvRecordData[1]) == '销售给二级经销商'){
              if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + cod2Obj.TracingCode__c + '二级经销商给客户单价为空，请确认。'));
              saveFLGbln= true;
              messageCount ++;
             }*/
            if(String.isBlank(csvRecordData[6])){
              if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + cod2Obj.TracingCode__c + '的产品中，存在barcode为空，请确认。'));
              saveFLGbln= true;
              messageCount ++;
            }else if(String.isBlank(csvRecordData[12])){
              if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + cod2Obj.TracingCode__c + '的barcode ' + cod2Obj.Bar_Code__c + ' 不存在或不是在库产品，请确认。'));
              saveFLGbln= true;
              messageCount ++;
            }
            cod2Obj.Return_reason__c       = csvRecordData[12];
            if(String.isBlank(csvRecordData[11])){
              if(messageCount >= 100) break;
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + cod2Obj.TracingCode__c + '的产品中，存在出库日期为空，请确认。'));
              saveFLGbln= true;
              messageCount ++;
            }else{
              cod2Obj.Send_Date__c           = Date.parse(csvRecordData[11].trim());
            }
            //orderdet2BoxRecords.add(new ConsumableorderdetailsInfo(cod2Obj));
          }
      }
      catch (Exception e)
      {
          ApexPages.addMessages(e);
      }
    }

  public List<ConsumableorderdetailsInfo> getorderdetList(List<String []> csvRecordStr){
    List<ConsumableorderdetailsInfo> orderdetRecords = new List<ConsumableorderdetailsInfo>();
    map<string,Decimal> orderdetMap = new map<string,Decimal>();
      try{
          for(Integer i=1;i<csvRecordStr.size();i++){
             Consumable_Orderdetails__c codObj = new Consumable_Orderdetails__c() ;
             string[] csvRecordData = csvRecordStr[i];
             if(orderdetMap.containsKey(csvRecordData[0] + csvRecordData[12] + csvRecordData[9]))
             {
              orderdetMap.put(csvRecordData[0] + csvRecordData[12] + csvRecordData[9],orderdetMap.get(csvRecordData[0] + csvRecordData[12] + csvRecordData[9]) + Decimal.valueOf(csvRecordData[7]));
              continue;
             }else{
              orderdetMap.put(csvRecordData[0] + csvRecordData[12] + csvRecordData[9], Decimal.valueOf(csvRecordData[7]));
             }
             codObj.Remarks__c             = csvRecordData[0] ;
             codObj.Shipment_Count__c      =  Decimal.valueOf(csvRecordData[7]);
             codObj.Box_Piece__c           =  csvRecordData[9];
             if(String.isNotBlank(csvRecordData[8])){
              codObj.Delivery_List_RMB__c   = Decimal.valueOf(csvRecordData[8]);
             }
             //if(String.isNotBlank(csvRecordData[10])){
             // codObj.Unitprice_To_agency__c = Decimal.valueOf(csvRecordData[10]);
             //}
             codObj.Lose_reason__c        = csvRecordData[12];
             if(String.isNotBlank(csvRecordData[11])){
              codObj.Used_date__c = Date.parse(csvRecordData[11].trim());
            }
             product2conMap.put(csvRecordData[12].trim(), csvRecordData[12].trim());
             orderdetRecords.add(new ConsumableorderdetailsInfo(codObj));
          }
          for(ConsumableorderdetailsInfo ass : orderdetRecords){
            if(orderdetMap.containsKey(ass.orderName + ass.productName + ass.orderdetails1.Box_Piece__c)){
              ass.orderdetails1.Shipment_Count__c = orderdetMap.get(ass.orderName + ass.productName + ass.orderdetails1.Box_Piece__c);
            }
          }
          return orderdetRecords;
      }
      catch (Exception e)
      {
          ApexPages.addMessages(e);
          return null;
      }
  }

  public List<ConsumableorderdetailsInfo> getorderdet2BoxList(List<String []> csvRecordStr){
    barcodeList = new List<String>();
    List<ConsumableorderdetailsInfo> orderdet2BoxRecords = new List<ConsumableorderdetailsInfo>();
      try{
          for(Integer i=1;i<csvRecordStr.size();i++){
            
            string[] csvRecordData         = csvRecordStr[i];
            if(String.valueOf(csvRecordData[9]) == '盒'){
              Consumable_Order_details2__c cod2Obj = new Consumable_Order_details2__c() ;
              cod2Obj.TracingCode__c         = csvRecordData[0] ;
              cod2Obj.Bar_Code__c            = csvRecordData[6];
              if(String.isNotBlank(csvRecordData[6])){
                barcodeList.add(csvRecordData[6]);
              }
              cod2Obj.Box_Piece__c           =  csvRecordData[9];
              if(String.isNotBlank(csvRecordData[8])){
                cod2Obj.Delivery_List_RMB__c   = Decimal.valueOf(csvRecordData[8]);
              }
              //if(String.isNotBlank(csvRecordData[10])){
              //  cod2Obj.Unitprice_To_agency__c = Decimal.valueOf(csvRecordData[10]);
              //}
              cod2Obj.Return_reason__c       = csvRecordData[12];
              if(String.valueOf(csvRecordData[1]) == '销售给二级经销商' || String.valueOf(csvRecordData[1]) == '直接销售给医院'){
                cod2Obj.Used_date__c           = Date.parse(csvRecordData[11].trim());
              }else{
                cod2Obj.Send_Date__c           = Date.parse(csvRecordData[11].trim());
              }
              orderdet2BoxRecords.add(new ConsumableorderdetailsInfo(cod2Obj));
            }
            
          }
          return orderdet2BoxRecords;
      }
      catch (Exception e)
      {
          ApexPages.addMessages(e);
          return null;
      }
  }

  public List<ConsumableorderdetailsInfo> getorderdet2pieceList(List<String []> csvRecordStr){
    barcodePieceList = new List<String>();
    List<ConsumableorderdetailsInfo> orderdet2PieceRecords = new List<ConsumableorderdetailsInfo>();
      try{
          for(Integer i=1;i<csvRecordStr.size();i++){
            string[] csvRecordData         = csvRecordStr[i];
            if(String.valueOf(csvRecordData[9]) == '个'){
              Consumable_Order_details2__c cod2Obj = new Consumable_Order_details2__c() ;
              cod2Obj.TracingCode__c         = csvRecordData[0] ;
              cod2Obj.Bar_Code__c            = csvRecordData[6];
              if(String.isNotBlank(csvRecordData[6])){
                barcodePieceList.add(csvRecordData[6]);
              }
              cod2Obj.Box_Piece__c           =  csvRecordData[9];
              if(String.isNotBlank(csvRecordData[8])){
                cod2Obj.Delivery_List_RMB__c   = Decimal.valueOf(csvRecordData[8]);
              }
              //if(String.isNotBlank(csvRecordData[10])){
              //  cod2Obj.Unitprice_To_agency__c = Decimal.valueOf(csvRecordData[10]);
              //}
              cod2Obj.Return_reason__c       = csvRecordData[12];
              if(String.valueOf(csvRecordData[1]) == '销售给二级经销商' || String.valueOf(csvRecordData[1]) == '直接销售给医院'){
                cod2Obj.Used_date__c           = Date.parse(csvRecordData[11].trim());
              }else{
                cod2Obj.Send_Date__c           = Date.parse(csvRecordData[11].trim());
              }              cod2Obj.Rrturn_count__c        = Decimal.valueOf(csvRecordData[7]);
              orderdet2PieceRecords.add(new ConsumableorderdetailsInfo(cod2Obj));
            }
            
          }
          return orderdet2PieceRecords;
      }
      catch (Exception e)
      {
          ApexPages.addMessages(e);
          return null;
      }
  }

  public PageReference dataImport(){
    List<ConsumableorderdetailsInfo> orderdetRecords = new List<ConsumableorderdetailsInfo>();
    List<ConsumableorderdetailsInfo> orderdet2BoxRecords = new List<ConsumableorderdetailsInfo>();
    List<ConsumableorderdetailsInfo> orderdet2PieceRecords = new List<ConsumableorderdetailsInfo>();
    orderdetRecords = getorderdetList(csvRecordStr);
    orderdet2BoxRecords = getorderdet2BoxList(csvRecordStr);
    orderdet2PieceRecords = getorderdet2pieceList(csvRecordStr);
    //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, 'orderdet2BoxRecords +++++' + orderdet2BoxRecords));
    //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, 'orderdet2PieceRecords +++++' + orderdet2PieceRecords));
    //return null;
    Savepoint sp = Database.setSavepoint();
    try{
      Map<String,String> orderInfoMap = new Map<String,String>();
      List<Consumable_order__c> coc = new List<Consumable_order__c>();
      for(ConsumableorderdetailsInfo ass : orderRecords){
        ass.order.Order_type__c = '传票';
        ass.order.SummonsStatus_c__c = '已完成';
        ass.order.Order_ProType__c = agencyProType;
        ass.order.Dealer_Info__c = accountid;
        ass.order.Order_ForHospital__c = hospitalSysMap.get(ass.hospitalCode);
        if(secondAgencyMap.containsKey(ass.agencyName)){
          ass.order.Order_ForDealer__c =secondAgencyMap.get(ass.agencyName);
        }else{
          ass.order.Order_ForDealerText__c = ass.agencyName;
        }
        ass.order.RecordTypeId = System.Label.RT_ConOrder_Sale;
        coc.add(ass.order);
      }
      if(coc.size()> 0){
        insert coc;
      }
      for(Consumable_order__c order : coc){
        orderInfoMap.put(order.Name,order.Id);
      }
      List<Consumable_Orderdetails__c> cod = new List<Consumable_Orderdetails__c>();
      for(String field : orderInfoMap.keySet()){
        Integer i = 1;
        for(ConsumableorderdetailsInfo ass : orderdetRecords){
          if(ass.orderName == field){
            String str = string.valueOf(i);
            if(str.length() == 1){
                str = '0' + str;
            }
            ass.orderdetails1.Name = ass.orderName + '-'+ str;
            ass.orderdetails1.Consumable_order__c = orderInfoMap.get(ass.orderName);
            ass.orderdetails1.Consumable_Product__c = ass.productName;
            ass.orderdetails1.RecordTypeId = System.Label.RT_ConOrderDetail1_Sale;
            cod.add(ass.orderdetails1);
            i++;
          }
        }
      }
      if(cod.size()> 0){
        insert cod;
      }
      //盒的数据检索
      List<Consumable_Order_details2__c> cod2List = new List<Consumable_Order_details2__c>();
      List<Consumable_order_details2__c> cOrderDet = [SELECT Id,
                            Bar_Code__c,
                            Name,
                            Consumable_Product__c,
                            Box_Piece__c
                        FROM Consumable_order_details2__c
                        WHERE  Dealer_Arrive__c = true
                        AND Dealer_Shipment__c = false
                        AND Dealer_Saled__c = false
                        AND Lose_Flag__c = false
                        AND Bar_Code__c in : barcodeList
                        AND Product_Type__c like : sqlagencyProType
                        AND Dealer_Info_text__c = :accountName
                        AND Arrive_Owner_Work_Location__c =: userWorkLocation
                        AND Box_Piece__c = '盒'];
      for(ConsumableorderdetailsInfo ass : orderdet2BoxRecords){
        Integer idx = 0;
        for(Consumable_order_details2__c codtest : cOrderDet){
          Consumable_Order_details2__c cod2 = new Consumable_Order_details2__c();
            if(codtest.Bar_Code__c == ass.orderdetails2.Bar_Code__c){
                cod2 = codtest;
                cod2.Consumable_Sale_order__c = orderInfoMap.get(ass.orderName);
                cod2.Consumable_ZS_order__c = orderInfoMap.get(ass.orderName);
                cod2.Used_date__c = ass.orderdetails2.Used_date__c;
                cod2.Send_Date__c = ass.orderdetails2.Send_Date__c;
                //cod2.Unitprice_To_agency__c = ass.orderdetails2.Unitprice_To_agency__c;
                cod2.Delivery_List_RMB__c   = ass.orderdetails2.Delivery_List_RMB__c;
                cod2List.add(cod2);
                cOrderDet.remove(idx);
                break;
            }
            idx++;
        }
      }

      //个的数据检索
      List<Consumable_order_details2__c> cOrderDetPiece = [SELECT Id,
                            Bar_Code__c,
                            RemoveBox_No__c,
                            Name,
                            Consumable_Product__c,
                            Box_Piece__c
                        FROM Consumable_order_details2__c
                        WHERE  Dealer_Arrive__c = true
                        AND Dealer_Shipment__c = false
                        AND Dealer_Saled__c = false
                        AND Lose_Flag__c = false
                        AND Arrive_Owner_Work_Location__c =: userWorkLocation
                        AND Bar_Code__c in : barcodePieceList
                        AND Product_Type__c like : sqlagencyProType
                        AND Dealer_Info_text__c = :accountName
                        AND Box_Piece__c = '个'
                        order by Bar_Code__c,RemoveBox_No__c desc];
      for(ConsumableorderdetailsInfo ass : orderdet2PieceRecords){
        Decimal idy = 1;
        for(Integer idx = 0; idx < cOrderDetPiece.size(); idx++){
          Consumable_Order_details2__c cod2 = new Consumable_Order_details2__c();
          if(cOrderDetPiece[idx].Bar_Code__c == ass.orderdetails2.Bar_Code__c && idy <= ass.pieceCount){
              cod2 = cOrderDetPiece[idx].Clone();
              cod2.Id = cOrderDetPiece[idx].Id;
              cod2.Consumable_Sale_order__c = orderInfoMap.get(ass.orderName);
              cod2.Consumable_ZS_order__c = orderInfoMap.get(ass.orderName);
              cod2.Used_date__c = ass.orderdetails2.Used_date__c;
              cod2.Send_Date__c = ass.orderdetails2.Send_Date__c;
              //cod2.Unitprice_To_agency__c = ass.orderdetails2.Unitprice_To_agency__c;
              cod2.Delivery_List_RMB__c   = ass.orderdetails2.Delivery_List_RMB__c;
              cod2List.add(cod2);
              cOrderDetPiece[idx].Bar_Code__c = '';
              idy++;
              //break;
          }
        }
      }
      if(cod2List.size() >0){
        update cod2List;
      }
      errorflg = true;
      errorMessage ='保存完成。';
      saveFLGbln = true;
      return null;
    }catch (Exception e)
    {
      Database.rollback(sp);
      ApexPages.addMessages(e);
      return null;
    }
  }
    public void dataInfoconfim(){
    //确认医院信息
    hospitalSysMap = new Map<String,String>();
    secondAgencyMap = new Map<String,String>();
    for(ConsumableorderdetailsInfo ass : orderRecords){
        if((ass.order.SummonsForDirction__c == '销售给二级经销商' ||
          ass.order.SummonsForDirction__c == '直接销售给医院' ||
          ass.order.SummonsForDirction__c == '医院试用')
        && (String.isBlank(ass.hospitalName) || String.isBlank(ass.hospitalCode) || String.isBlank(ass.order.Order_ForCustomerText__c))){
          if(messageCount >= 100) break;
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单' + ass.order.Name +'医院相关信息不能空，请确认。'));
          messageCount ++;
          saveFLGbln= true;
          //return null;
        }
        if(ass.order.SummonsForDirction__c == '销售给二级经销商'){
          if(String.isBlank(ass.agencyName)){
            if(messageCount >= 100) break;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单' + ass.order.Name +'经销商信息不能空，请确认。'));
            messageCount ++;
            saveFLGbln= true;
          }
        }
        if(ass.order.SummonsForDirction__c == '直接销售给医院'){
          if(String.isNotBlank(ass.agencyName)){
            if(messageCount >= 100) break;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单' + ass.order.Name +'不需要二级经销商，请确认。'));
            messageCount ++;
            saveFLGbln= true;
          }
        }
        if(ass.order.SummonsForDirction__c == '互相调货'){
          if(String.isBlank(ass.agencyName)){
            if(messageCount >= 100) break;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单' + ass.order.Name +'经销商信息不能空，请确认。'));
            messageCount ++;
            saveFLGbln= true;
          }
          if(String.isNotBlank(ass.hospitalName)||String.isNotBlank(ass.hospitalCode)||String.isNotBlank(ass.order.Order_ForCustomerText__c)){
            if(messageCount >= 100) break;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单' + ass.order.Name +'不需要医院相关信息，请确认。'));
            messageCount ++;
            saveFLGbln= true;
          }
        }
    }
    List<Agency_Hospital_Link__c> hospitalInfo = [select Hospital__c, Hospital__r.Management_Code__c,Hospital__r.Name from Agency_Hospital_Link__c where  Agency__r.Name = :accountName ];
    List<Dealer_elationship__c> secondAgencyInfo = [select Dealer_subordinate__c,Dealer_subordinate__r.Name from Dealer_elationship__c where Dealer_principal__r.Name = :accountName ];
    for(Agency_Hospital_Link__c hpinfo :hospitalInfo){
      hospitalSysMap.put(hpinfo.Hospital__r.Management_Code__c, hpinfo.Hospital__c);
    }
    for(Dealer_elationship__c safo :secondAgencyInfo){
      secondAgencyMap.put(safo.Dealer_subordinate__r.Name, safo.Dealer_subordinate__c);
    }
    //出库单信息验证
      for(String widget : hospitalconMap.keySet()) {
        if(!hospitalSysMap.containsKey(widget)){
            if(messageCount >= 100) break;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '出库单 ' + hospitalconMap.get(widget) + ' 的医院编码' + widget + ' 不存在或者不是本经销商负责的医院，请确认。'));
            saveFLGbln= true;
        }
      }
    }

    // Data Bean
  class ConsumableorderdetailsInfo implements Comparable {
    public Consumable_order__c order { get; set; }
    public Consumable_orderdetails__c orderdetails1 { get; set; }
    public Consumable_order_details2__c orderdetails2 { get; set; }
    public String orderName { get; set; }
    public String hospitalCode { get; set; }
    public String hospitalName { get; set; }
    public String agencyName { get; set; }
    public String productName { get; set; }
    public Decimal pieceCount { get; set; }
    // 取到的订单信息
    public ConsumableorderdetailsInfo(Consumable_order__c e) {
        order = e;
        hospitalCode = e.Order_Attachment__c;
        hospitalName = e.Order_Indication__c;
        agencyName = e.Invoice_Note__c;
        e.Order_Attachment__c = '';
        e.Order_Indication__c = '';
        e.Invoice_Note__c = '';
    }
    // 取到的订单明细
    public ConsumableorderdetailsInfo(Consumable_orderdetails__c e) {
        orderdetails1 = e;
        orderName = e.Remarks__c;
        productName = e.Lose_reason__c;
        e.Lose_reason__c = '';
        e.Remarks__c = '';
    }
    // 取到的产品明细
    public ConsumableorderdetailsInfo(Consumable_order_details2__c e) {
        orderdetails2 = e;
        orderName = e.TracingCode__c;
        productName = e.Return_reason__c;
        pieceCount = e.Rrturn_count__c;
        e.TracingCode__c = '';
        e.Return_reason__c = '';
        e.Rrturn_count__c = null;
    }
    public Integer compareTo(Object compareTo) {
        return null;
    }
  }
}