public without sharing class SaleOrderController {
    //画面录入barcode取得
    public static boolean isRunning = false;
    public String barcode { get; set; }
    public Consumable_order__c coc { get; set; }
    /*****************画面表示Bean******************/
    //明细2
    public List<ConsumableorderdetailsInfo> consumableorderdetailsRecords { get; set; }
    public List<Consumable_order_details2__c> consumableorderdetails2Nobox= new List<Consumable_order_details2__c>();
    //错误明细
    public List<ConsumableorderdetailsInfo> consumableorderdetailsRecordserror { get; set; }

    Map<String, String> existIdMap = new Map<String, String>();
    Map<String, String> errorIdMap = new Map<String, String>();
    Map<String, String> allMap = new Map<String, String>();
    Map<String, String> orderpieceorboxMap = new Map<String, String>();
    Map<String, Decimal> orderpriceMap = new Map<String, Decimal>();
    Map<String, Decimal> orderagencypriceMap = new Map<String, Decimal>();
    Map<String, Decimal> orderdetCountMap = new Map<String, Decimal>();
    //存在的到货barcode数量（个）
    Map<String, Integer> BarcodeCntMap = new Map<String, Integer>();
    public String baseUrl {get;private set;}
    //指示单ID
    public String ESetId { get; set; }
    //经销商ID
    private String accountName = null;
    // 登录者工作地
    private String userWorkLocation;

    //add by rentx 2021-2-26 start
    private Boolean hasSpecialHos;
    private Map<String,Integer> msiMap = new Map<String,Integer>();
    //在2021-3-1日 将明细1 和明细2中所有的Consumable_product__c变为了 Product_Pattern__c  为了区分医院特价和非医院特价
    //add by rentx 2021-2-26 end

    public SaleOrderController(){
        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        ESetId = ApexPages.currentPage().getParameters().get('esetId');
        consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
        consumableorderdetailsRecordserror = new List<ConsumableorderdetailsInfo>();
    }
    List<Consumable_orderdetails__c> orderdetails = New List<Consumable_orderdetails__c>();

    //add by rentx 2021-3-10
    private String accountid;
    //add by rentx 2021-3-10
    
    //初始化
    public void init() {
        isRunning = true;
        String UserName = UserInfo.getUserId();
        user useracc = [SELECT Accountid, Work_Location__c FROM user WHERE id =:UserName];
        accountid = useracc.Accountid;
        userWorkLocation = useracc.Work_Location__c;
        Account accountInfo = [SELECT Name FROM account WHERE id =:accountid];
        accountName = accountInfo.Name;
        consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
        consumableorderdetailsRecordserror = new List<ConsumableorderdetailsInfo>();
        coc = new Consumable_order__c();
        List<Consumable_order_details2__c> arriveDat = new List<Consumable_order_details2__c>();
        if(String.isNotBlank(ESetId)){
            // update start by vivek 2019-7-16
            // coc = [select Id,Name,Order_ForDealer__r.Name,
            // Summons_Order_type__c,Order_status__c,Dealer_Info__c,
            // SummonsStatus_c__c,Deliver_date__c,Order_Reason__c,
            // Order_date__c,Order_ForHospital__c,SummonsForDirction__c,
            // Arrive_Order__c,
            // Arrive_Order__r.IsShipment__c,Outbound_Date__c,
            // Billed_Status__c,ShipmentAccount__c,Order_ForCustomerText__c
            // From Consumable_order__c
            // Where Id =:ESetId];
            coc = [select Id,Name,NoConfirmedPrice__c,Order_ForDealer__r.Name,
            Summons_Order_type__c,Order_status__c,Dealer_Info__c,Dealer_Info__r.Name,
            SummonsStatus_c__c,Deliver_date__c,Order_Reason__c,
            Order_date__c,Order_ForHospital__c,SummonsForDirction__c,
            Arrive_Order__c,
            Arrive_Order__r.IsShipment__c,Outbound_Date__c,
            Billed_Status__c,ShipmentAccount__c,Order_ForCustomerText__c,OutPattern__c 
            From Consumable_order__c
            Where Id =:ESetId];
            // update end by vivek 2019-7-16
            if(coc.Arrive_Order__c!= null){
                arriveDat = [select Id,  Name, recordtypeid,Used_account__c,
                                    Product_Pattern__c,Consumable_Product__r.Name, Sterilization_limit__c,
                                    Deliver_date__c,Bar_Code__c,Arrive_date__c,Send_Date__c,
                                    Consumable_order_minor__r.Name,Consumable_order_minor__c,Intra_Trade_List_RMB__c,
                                    Asset_Model_No__c,Isoverdue__c,Guarantee_period_for_products__c,Box_Piece__c
                                    // gzw add 20210308 报错修复
                                    ,hospitalSpecialOffer__c
                                from Consumable_order_details2__c
                                where Consumable_ZS_order__c = :ESetId];
                for(Integer j = 0; j < arriveDat.size(); j++){
                    consumableorderdetailsRecords.add(new ConsumableorderdetailsInfo(arriveDat[j]));
                }
            }
            orderdetails =[select Id,Name,Product_Pattern__c,Consumable_product__r.Name,
                                  Shipment_Count__c,Box_Piece__c,Delivery_List_RMB__c,Unitprice_To_agency__c,isOutPattern__c 
                             from Consumable_orderdetails__c
                             where Consumable_order__c = :ESetId  AND Order_Owner_WorkLocal__c = : userWorkLocation ];
            for(Integer i = 0; i < orderdetails.size(); i++){
                orderpieceorboxMap.put(orderdetails[i].Product_Pattern__c,orderdetails[i].Box_Piece__c);
                if(orderdetails[i].Unitprice_To_agency__c != null && orderdetails[i].Unitprice_To_agency__c !=0){
                    orderagencypriceMap.put(orderdetails[i].Product_Pattern__c, orderdetails[i].Unitprice_To_agency__c);
                }
                orderpriceMap.put(orderdetails[i].Product_Pattern__c,orderdetails[i].Delivery_List_RMB__c);
                orderdetCountMap.put(orderdetails[i].Product_Pattern__c,orderdetails[i].Shipment_Count__c);
            }

            //add by rentx 2021-2-26
            List<hospitalprice__c> hlist = [select id from hospitalprice__c where hospital__c = :coc.ShipmentAccount__c and account__c = :accountid];
            if (hlist == null || hlist.size() == 0) {
                hasSpecialHos = false;
            }else {
                hasSpecialHos = true;
            }
            // add by rentx 2021-2-26 end   
        }
    }
    // 去的页面上的barcode，转换成List
    public List<String> ParseBarCode(String Code){
        String[] Cache = new String[]{};
        Cache = Code.split('\n');
        List <String> Buff = new List<String>();
        for(String A : Cache){
            A = A.trim();
            Buff.add(A.toUpperCase());
        }
        return Buff;
    }
    //检索时明细做成
    public void SearchPro() {

         //判断是否和订单联动
        if(coc.Arrive_Order__c!= null){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'无需到货确认，请直接出库。'));
            return;
        }
        //判断barcode是否为空
        if(barcode == null || barcode ==''){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'请输BarCode号。'));
            return;
        }
        list<String> exitlist = new List<String>();
        list<String> notexitlist = new List<String>();
        existIdMap = new Map<String, String>();
        errorIdMap = new Map<String, String>();
        allMap = new Map<String, String>();
        consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
        consumableorderdetailsRecordserror = new List<ConsumableorderdetailsInfo>();
        List<String> barCodeListP = new List<String>();
        List<Consumable_order_details2__c> reSet = new List<Consumable_order_details2__c>();
        List<Consumable_order_details2__c> reSet1 = new List<Consumable_order_details2__c>();

        //BarCodelist做成
        barCodeListP = ParseBarCode(barcode);
        //针对所有商品到货确认
        reSet1 = [select Id,
                        Name,
                        recordtypeid,
                        Used_account__c,
                        Product_Pattern__c,
                        Consumable_Product__r.Name,
                        Sterilization_limit__c,
                        Deliver_date__c,
                        Bar_Code__c,
                        Arrive_date__c,
                        Send_Date__c,
                        Consumable_order_minor__r.Name,
                        Consumable_order_minor__c,
                        Intra_Trade_List_RMB__c,
                        Asset_Model_No__c,
                        Isoverdue__c,
                        Box_Piece__c,
                        ProductPacking_list_manual__c,
                        Guarantee_period_for_products__c,
                        hospitalSpecialOffer__c ,
                        exchangeOutPattern__c 
                    from Consumable_order_details2__c
                    WHERE Dealer_Arrive__c = true
                    AND Dealer_Returned__c = false
                    //AND Dealer_Shipment__c = false
                    //AND Dealer_Saled__c = false
                    //AND Lose_Flag__c = false
                    AND Bar_Code__c !=null
                    AND Dealer_Info_text__c = :accountName
                    AND Bar_Code__c in :barCodeListP
                    AND Arrive_Owner_Work_Location__c =: userWorkLocation
                    order by  RemoveBox_No__c desc];
        List<Consumable_order_details2__c> newdet2 = new List<Consumable_order_details2__c>();

        //add by rentx 2021-3-10 start
        //如果明细2对应的产品存在医院特价关系表但是出库单上的客户不存在 报错
        //判断当前明细2对应的产品是否存在医院特价关系表 不存在就可以出库
        // for(String barcode :barCodeListP){
        //     Integer idx = 0;
        //     for(Consumable_order_details2__c cod2 : reSet1){
        //         if(cod2.Bar_Code__c == barcode){
        //             newdet2.add(cod2);
        //             reSet1.remove(idx);
        //             break;
        //         }
        //         idx++;
        //     }
        // }
        Set<Id> proIds = new Set<Id>();

        for(String barcode :barCodeListP){
            Integer idx = 0;
            for(Consumable_order_details2__c cod2 : reSet1){
                if(cod2.Bar_Code__c == barcode){
                    newdet2.add(cod2);
                    reSet1.remove(idx);
                    proIds.add(cod2.Consumable_product__c);
                    break;
                }
                idx++;
            }
        }
        Map<String,String> proHosMap = new Map<String,String>();
        Map<String,String> proIdMap = new Map<String,String>();
        List<hospitalprice__c> hpList = [select id,hospital__c,product__c from hospitalprice__c where account__c = :accountid];
        if (hpList!= null && hpList.size() > 0) {
            for (hospitalprice__c hp : hpList) {
                if(hp.product__c!=null && String.valueof(hp.product__c).length()>=15){//Add by Li Jun for issue fix 20230403 
                    proIdMap.put((''+hp.product__c).subString(0,15)+'是', '');
                    if (hp.hospital__c ==coc.Order_ForHospital__c) {
                        proHosMap.put((''+hp.product__c).subString(0,15)+'是', '');
                    }
                }               
            }
        }

        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'proIdMap '+ proIdMap));
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'proHosMap '+ proHosMap));

        
        //add by rentx 2021-3-10 end

        for(Integer i = 0; i < orderdetails.size(); i++){
            for(Integer j = 0; j < newdet2.size(); j++){
                if(newdet2[j].Product_Pattern__c == orderdetails[i].Product_Pattern__c && newdet2[j].Box_Piece__c != orderdetails[i].Box_Piece__c){
                    String str = '该商品出货单位错误';
                    consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                    errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                }

                //add by rentx 2021-3-10 start
                /*
                如果当前经销商下有特价医院的话
                判断 如果医院和特价产品都维护在医院特价关系表中 可以正常出库
                如果 医院特价关系表中没有再维护该产品 可以正常出库
                else  报错  产品维护在医院特价关系表中 但是医院没有
                */
                //判断当前出库单是否为医院特价出库单
                if (coc.OutPattern__c == true) {
                    if (newdet2[j].Product_Pattern__c == orderdetails[i].Product_Pattern__c) {
                        //add by rentx 2021-03-22 start
                        if (newdet2[j].exchangeOutPattern__c == true) {
                            //如果当前经销商下没有维护对应的特价产品 报错
                            if (!proIdMap.containsKey(newdet2[j].Product_Pattern__c)) {
                                String str = '没有维护该产品的特价医院';
                                consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                                errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                            }
                        }
                        //add by rentx 2021-03-22 end

                        if (hpList != null && hpList.size() > 0) {
                            if (proHosMap.containsKey(newdet2[j].Product_Pattern__c)) {
                                continue;
                            }else if (!proIdMap.containsKey(newdet2[j].Product_Pattern__c)) {
                                continue;
                            }else{
                                String str = '该商品出库医院错误';
                                consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                                errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                            }
                        }
                    }
                }
                
                //add by rentx 2021-3-10 end

                

                /*//===========================add by rentx 2020-12-10
                //判断如果是医院特价 或不是医院特价
                //1.如果需要出库/销售 医院特价的产品 
                //add by rentx 2021-2-26 start
                //先判断当前经销商下有没有特价医院
                if (hasSpecialHos == false) {
                    // //没有特价医院,判断明细1 和明细2是否都是或都不是医院特价
                    // if(newdet2[j].Product_Pattern__c == orderdetails[i].Product_Pattern__c  ){
                    //     if (newdet2[j].hospitalSpecialOffer__c == true && orderdetails[i].isOutPattern__c == false) {
                    //         String str = '该商品是医院特价入库的商品,请选择非医院特价入库的商品';
                    //         consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                    //         errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                    //     }else if (newdet2[j].hospitalSpecialOffer__c == false && orderdetails[i].isOutPattern__c == true) {
                    //         String str = '该商品是非医院特价入库的商品,请选择医院特价入库的商品';
                    //         consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                    //         errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                    //     }
                    // }
                    //add by rentx 2021-2-26 end
                }else{
                    if (coc.OutPattern__c == true) {
                        //1.判断明细1,明细2 是否都是医院特价
                        if (orderdetails[i].isOutPattern__c == true) {
                            if (newdet2[j].hospitalSpecialOffer__c == false) {
                                String str = '该商品是非医院特价入库的商品,无法出库';
                                consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                                errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                            }
                        }else{
                            String str = '该商品无法出库,请重新确认明细1与明细2的入库方式';
                            consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                            errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                        }
                    }
                    //2.如果需要出库/销售 非医院特价的产品
                    if (coc.OutPattern__c == false) {
                        //1.判断明细1,明细2 是否都是医院特价
                        if (orderdetails[i].isOutPattern__c == false) {
                            if (newdet2[j].hospitalSpecialOffer__c == true) {
                                String str = '该商品是医院特价入库的商品,无法出库';
                                consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                                errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                            }
                        }else{
                            String str = '该商品无法出库,请重新确认明细1与明细2的入库方式';
                            consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                            errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                        }
                    }
                } 
                //add by rentx 2021-2-26 end
                
                //===========================add by rentx 2020-12-10*/
            }
        }


        //管理编码为空时，报错
        reSet1 = [select Id,
                        Name,
                        Product_Pattern__c,
                        Consumable_Product__r.Name,
                        Sterilization_limit__c,
                        Deliver_date__c,
                        Bar_Code__c,
                        Arrive_date__c,
                        Send_Date__c,
                        Consumable_order_minor__r.Name,
                        Consumable_order_minor__c,
                        recordtypeid,
                        Consumable_order_minor__r.Arrive_Order__c,
                        Box_Piece__c,
                        Arrive_Owner_Work_Location__c
                        ,hospitalSpecialOffer__c
                    from Consumable_order_details2__c
                    where Bar_Code__c in :barCodeListP
                    AND Bar_Code__c !=null
                    AND Dealer_Arrive__c = true
                    AND Dealer_Info_text__c = :accountName
                    AND Arrive_Owner_Work_Location__c =: userWorkLocation
                    AND (TracingCode__c = null
                         OR TracingCode__c = '')
                    order by Name ];
        if(reSet1.size()>0){
            for (Integer i = 0; i < reSet1.size(); i++) {
                if(errorIdMap.containsKey(reSet1[i].Bar_Code__c) || existIdMap.containsKey(reSet1[i].Bar_Code__c)){
                    // 跳过已经处理的消耗品明细
                    continue;
                }else{
                    String str = '该产品没有管理编码，无法出库，请与特约经销商管理部人员联系，修正数据';
                    consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(reSet1[i],str));
                    errorIdMap.put(reSet1[i].Bar_Code__c,reSet1[i].Bar_Code__c);
                }
            }
        }
        reSet1 = [select Id,
                        Name,
                        Product_Pattern__c,
                        Consumable_Product__r.Name,
                        Sterilization_limit__c,
                        Deliver_date__c,
                        Bar_Code__c,
                        Arrive_date__c,
                        Send_Date__c,
                        Consumable_order_minor__r.Name,
                        Consumable_order_minor__c,
                        recordtypeid,
                        Consumable_order_minor__r.Arrive_Order__c,
                        Box_Piece__c,
                        Arrive_Owner_Work_Location__c
                        ,hospitalSpecialOffer__c
                    from Consumable_order_details2__c
                    where Bar_Code__c in :barCodeListP
                    AND Bar_Code__c !=null
                    AND Dealer_Arrive__c = true
                    AND Dealer_Info_text__c = :accountName
                    AND Arrive_Owner_Work_Location__c =: userWorkLocation
                    AND Cancellation_Flag__c = true
                    order by Name ];
        if(reSet1.size()>0){
            for (Integer i = 0; i < reSet1.size(); i++) {
                if(errorIdMap.containsKey(reSet1[i].Bar_Code__c) || existIdMap.containsKey(reSet1[i].Bar_Code__c)){
                    // 跳过已经处理的消耗品明细
                    continue;
                }else{
                    String str = '该商品已经取消';
                    consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(reSet1[i],str));
                    errorIdMap.put(reSet1[i].Bar_Code__c,reSet1[i].Bar_Code__c);
                }
            }
        }

        //不是本出库单的出库产品
        reSet1 = [select Id,
                        Name,
                        Product_Pattern__c,
                        Consumable_Product__r.Name,
                        Sterilization_limit__c,
                        Deliver_date__c,
                        Bar_Code__c,
                        Arrive_date__c,
                        Send_Date__c,
                        Consumable_order_minor__r.Name,
                        Consumable_order_minor__c,
                        recordtypeid,
                        Consumable_order_minor__r.Arrive_Order__c,
                        Box_Piece__c,
                        Arrive_Owner_Work_Location__c
                        ,hospitalSpecialOffer__c
                    from Consumable_order_details2__c
                    where Bar_Code__c in :barCodeListP
                    AND Bar_Code__c !=null
                    AND Dealer_Arrive__c = true
                    AND Dealer_Info_text__c = :accountName
                    AND Arrive_Owner_Work_Location__c =: userWorkLocation
                    order by Name ];
        if(reSet1.size()>0){
            for (Integer i = 0; i < reSet1.size(); i++) {
                if(errorIdMap.containsKey(reSet1[i].Bar_Code__c) || existIdMap.containsKey(reSet1[i].Bar_Code__c)){
                    // 跳过已经处理的消耗品明细
                    continue;
                }else if(!orderpieceorboxMap.containsKey(reSet1[i].Product_Pattern__c)){
                    String str = '不是本出库单的出库产品';
                    consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(reSet1[i],str));
                    errorIdMap.put(reSet1[i].Bar_Code__c,reSet1[i].Bar_Code__c);
                }
            }
        }

        reSet1 = [select Id,
                        Name,
                        Product_Pattern__c,
                        Consumable_Product__r.Name,
                        Sterilization_limit__c,
                        Deliver_date__c,
                        Bar_Code__c,
                        Arrive_date__c,
                        Send_Date__c,
                        Consumable_order_minor__r.Name,
                        Consumable_order_minor__c,
                        recordtypeid,
                        Consumable_order_minor__r.Arrive_Order__c,
                        Box_Piece__c,Dealer_Info_text__c,
                        Arrive_Owner_Work_Location__c
                        ,hospitalSpecialOffer__c
                    from Consumable_order_details2__c
                    where Bar_Code__c in :barCodeListP
                    AND Bar_Code__c !=null
                    AND Dealer_Arrive__c = true
                    AND ((Dealer_Info_text__c = :accountName
                            AND Arrive_Owner_Work_Location__c !=: userWorkLocation)
                        OR Dealer_Info_text__c != :accountName)
                    AND Cancellation_Flag__c = false
                    AND  Dealer_Shipment__c= FALSE
                    AND  Dealer_Saled__c = FALSE
                    AND Lose_Flag__c = false
                    AND Dealer_Returned__c = false
                    order by Name ];
        if(reSet1.size()>0){
            for (Integer i = 0; i < reSet1.size(); i++) {
                if(errorIdMap.containsKey(reSet1[i].Bar_Code__c) || existIdMap.containsKey(reSet1[i].Bar_Code__c)){
                    // 跳过已经处理的消耗品明细
                    continue;
                }else{
                    // 当前经销商是否存在此产品判断
                    boolean containsFlg = false;
                    for(Consumable_order_details2__c cod2 : newdet2){
                        if(cod2.Bar_Code__c == reSet1[i].Bar_Code__c){
                            containsFlg = true;
                            break;
                        }
                    }
                    if (containsFlg == false) {
                        String str = '该商品是' + reSet1[i].Arrive_Owner_Work_Location__c + '的库存';
                        if (reSet1[i].Dealer_Info_text__c != accountName) {
                            str = '该商品在其他经销商库存';
                        }
                        consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(reSet1[i],str));
                        errorIdMap.put(reSet1[i].Bar_Code__c,reSet1[i].Bar_Code__c);
                    }
                }
            }
        }
        
        reSet1 = [select Id,
                        Name,
                        Product_Pattern__c,
                        Consumable_Product__r.Name,
                        Sterilization_limit__c,
                        Deliver_date__c,
                        Bar_Code__c,
                        Arrive_date__c,
                        Send_Date__c,
                        Consumable_order_minor__r.Name,
                        Consumable_order_minor__c,
                        recordtypeid,
                        Consumable_order_minor__r.Arrive_Order__c,
                        Box_Piece__c
                        ,hospitalSpecialOffer__c
                    from Consumable_order_details2__c
                    where Dealer_Saled__c = true
                    AND Box_Piece__c = '盒'
                    AND Dealer_Info_text__c = :accountName
                    and Dealer_Returned__c = false
                    and  Bar_Code__c in :barCodeListP
                    AND Arrive_Owner_Work_Location__c =: userWorkLocation
                    order by Name ];
        if(reSet1.size()>0){
            for (Integer i = 0; i < reSet1.size(); i++) {
                if(errorIdMap.containsKey(reSet1[i].Bar_Code__c) || existIdMap.containsKey(reSet1[i].Bar_Code__c)){
                    // 跳过已经处理的消耗品明细
                    continue;
                }else{
                    String str = '该商品已经销售';
                    consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(reSet1[i],str));
                    errorIdMap.put(reSet1[i].Bar_Code__c,reSet1[i].Bar_Code__c);
                }
            }
        }
       reSet1 = [select Id,
                        Name,
                        Product_Pattern__c,
                        Consumable_Product__r.Name,
                        Sterilization_limit__c,
                        Deliver_date__c,
                        Bar_Code__c,
                        Arrive_date__c,
                        Send_Date__c,
                        Consumable_order_minor__r.Name,
                        Consumable_order_minor__c,
                        recordtypeid,
                        Consumable_order_minor__r.Arrive_Order__c,
                        Box_Piece__c
                        ,hospitalSpecialOffer__c
                    from Consumable_order_details2__c
                    where Dealer_Shipment__c = true
                    AND Box_Piece__c = '盒'
                    AND Dealer_Info_text__c = :accountName
                    AND Dealer_Returned__c = false
                    and  Bar_Code__c in :barCodeListP
                    AND Arrive_Owner_Work_Location__c =: userWorkLocation
                    order by Name ];
        if(reSet1.size()>0){
            for (Integer i = 0; i < reSet1.size(); i++) {
                if(errorIdMap.containsKey(reSet1[i].Bar_Code__c) || existIdMap.containsKey(reSet1[i].Bar_Code__c)){
                    // 跳过已经处理的消耗品明细
                    continue;
                }else{
                    String str = '该商品已经出库';
                    consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(reSet1[i],str));
                    errorIdMap.put(reSet1[i].Bar_Code__c,reSet1[i].Bar_Code__c);
                }
            }
        }
        reSet1 = [select Id,
                        Name,
                        Product_Pattern__c,
                        Consumable_Product__r.Name,
                        Sterilization_limit__c,
                        Deliver_date__c,
                        Bar_Code__c,
                        Arrive_date__c,
                        Send_Date__c,
                        Consumable_order_minor__r.Name,
                        Consumable_order_minor__c,
                        recordtypeid,
                        Consumable_order_minor__r.Arrive_Order__c,
                        Box_Piece__c
                        ,hospitalSpecialOffer__c
                    from Consumable_order_details2__c
                    where Lose_Flag__c = true
                    AND Box_Piece__c = '盒'
                    AND Dealer_Info_text__c = :accountName
                    and  Bar_Code__c in :barCodeListP
                    AND Arrive_Owner_Work_Location__c =: userWorkLocation
                    order by Name ];
        if(reSet1.size()>0){
            for (Integer i = 0; i < reSet1.size(); i++) {
                if(errorIdMap.containsKey(reSet1[i].Bar_Code__c) || existIdMap.containsKey(reSet1[i].Bar_Code__c)){
                    // 跳过已经处理的消耗品明细
                    continue;
                }else{
                    String str = '该商品已经丢失';
                    consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(reSet1[i],str));
                    errorIdMap.put(reSet1[i].Bar_Code__c,reSet1[i].Bar_Code__c);
                }
            }
        }
        reSet = [select Id,
                        Name,
                        recordtypeid,
                        Used_account__c,
                        Product_Pattern__c,
                        Consumable_Product__r.Name,
                        Sterilization_limit__c,
                        Deliver_date__c,
                        Bar_Code__c,
                        Arrive_date__c,
                        Send_Date__c,
                        Consumable_order_minor__r.Name,
                        Consumable_order_minor__c,
                        Intra_Trade_List_RMB__c,
                        Asset_Model_No__c,
                        Isoverdue__c,
                        Box_Piece__c,
                        ProductPacking_list_manual__c,
                        Guarantee_period_for_products__c,
                        TracingCode__c,
                        Transfer_Time__c,
                        Frist_Transfer_Agency__c
                        ,hospitalSpecialOffer__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 Dealer_Returned__c = false
                    AND Bar_Code__c !=null
                    AND Dealer_Info_text__c = :accountName
                    and  Bar_Code__c in :barCodeListP
                    AND Arrive_Owner_Work_Location__c =: userWorkLocation
                    order by  RemoveBox_No__c desc];
        //对应录入barcode数量的检索结果
        newdet2 = new List<Consumable_order_details2__c>();
        for(String barcode :barCodeListP){
            Integer idx = 0;
            for(Consumable_order_details2__c cod2 : reSet){
                if(cod2.Bar_Code__c == barcode){
                    newdet2.add(cod2);
                    reSet.remove(idx);
                    break;
                }
                idx++;
            }
        }
        Map<String,String>  checkBarcodeResult  =   new Map<String,String>();
        for(Integer i = 0; i < orderdetails.size(); i++){
            Integer a = 0;
            for(Integer j = 0; j < newdet2.size(); j++){
                if(newdet2[j].Product_Pattern__c == orderdetails[i].Product_Pattern__c  && a< orderdetails[i].Shipment_Count__c){
                    if((existIdMap.containsKey(newdet2[j].Bar_Code__c) && newdet2[j].Bar_Code__c == '盒') || errorIdMap.containsKey(newdet2[j].Bar_Code__c)){
                        // 跳过已经处理的消耗品明细
                        continue;
                    }else if(newdet2[j].Isoverdue__c == 0){
                        String str = '该商品已经超出减菌有效期的有效范围';
                        consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                        errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                    }else if(newdet2[j].Box_Piece__c != orderdetails[i].Box_Piece__c){
                        String str = '该商品出货单位错误';
                        consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                        errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                    }else if(!checkBarcodeResult.containsKey(newdet2[j].Bar_Code__c)) {
                        Matcher n = Pattern.compile('[0-9]').matcher(newdet2[j].TracingCode__c);
                        if(n.find()){
                            // gzw DB202305352696 入库管理编码验证程序调整 start
                            if (newdet2[j].TracingCode__c.length() == 5) {
                                String tr = newdet2[j].TracingCode__c;
                                String Ctr = tr.substring(tr.length() - 3,tr.length());
                                String Btr = tr.substring(tr.length() - 4,tr.length()-3);
                                String Atr = tr.substring(tr.length() - 5,tr.length()-4);
                                if (Pattern.compile('[0-9]').matcher(Atr).find() || Pattern.compile('[0-9]').matcher(Ctr).find()) {
                                    String str = '管理编码有误，请检查条形码数据。';
                                    consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                                    errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                                    continue;
                                }
                            }
                            // String str = '管理编码中有数字，请与管理员确认是否错误。';
                            // consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                            // errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                            // continue;
                            // gzw DB202305352696 入库管理编码验证程序调整 end
                        }
                        checkBarcodeResult.put(newdet2[j].Bar_Code__c, newdet2[j].Bar_Code__c);
                        consumableorderdetailsRecords.add(new ConsumableorderdetailsInfo(newdet2[j]));
                        a++;
                        existIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                    }
                }else if(newdet2[j].Product_Pattern__c == orderdetails[i].Product_Pattern__c){
                    if(a >= orderdetails[i].Shipment_Count__c && orderdetails[i].Box_Piece__c == '个'){
                        // 跳过超过数量的消耗品明细
                        continue;
                    }else if(errorIdMap.containsKey(newdet2[j].Bar_Code__c)){
                        // 跳过已经处理的消耗品明细
                        continue;
                    }else{
                        //CHAN-C23BWX update by rentx 2021-04-28 start
                        // String str = '该商品超出订货数量';
                        String str = '该产品超出出库单产品范围';
                        //CHAN-C23BWX update by rentx 2021-04-28 end
                        consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(newdet2[j],str));
                        errorIdMap.put(newdet2[j].Bar_Code__c,newdet2[j].Bar_Code__c);
                    }
                }
            }
        }

        reSet1 = [select Id,
                        Name,
                        Product_Pattern__c,
                        Consumable_Product__r.Name,
                        Sterilization_limit__c,
                        Deliver_date__c,
                        Bar_Code__c,
                        Arrive_date__c,
                        Send_Date__c,
                        Consumable_order_minor__r.Name,
                        Consumable_order_minor__c,
                        recordtypeid,
                        Consumable_order_minor__r.Arrive_Order__c,
                        Box_Piece__c
                        ,hospitalSpecialOffer__c
                    from Consumable_order_details2__c
                    where recordtypeid = :System.Label.RT_ConOrderDetail2_Delivery
                    and  Bar_Code__c in :barCodeListP
                    AND Dealer_Arrive__c = false
                    AND Dealer_Shipment__c = false
                    AND Dealer_Saled__c = false
                    AND Lose_Flag__c = false
                    AND Bar_Code__c !=null
                    AND Dealer_Info_text__c = :accountName
                    AND ((Consumable_order_minor__c != null
                            AND Consumable_order_minor__r.Order_Owner_WorkLocal__c = :userWorkLocation)
                        OR (Consumable_order_minor__c = null AND Cancellation_Flag__c = FALSE))
                    order by Name ];
        if(reSet1.size()>0){
            for (Integer i = 0; i < reSet1.size(); i++) {
                if(errorIdMap.containsKey(reSet1[i].Bar_Code__c) || existIdMap.containsKey(reSet1[i].Bar_Code__c)){
                    // 跳过已经处理的消耗品明细
                    continue;
                }else{
                    String str = '该商品未到货确认';
                    consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(reSet1[i],str));
                    errorIdMap.put(reSet1[i].Bar_Code__c,reSet1[i].Bar_Code__c);
                }
            }
        }

        allMap.putAll(errorIdMap);
        allMap.putAll(existIdMap);
        //得到不存在的BarCode
        for(Integer i = 0; i < barCodeListP.size(); i++){
            if(allMap.containsKey(barCodeListP[i])){
                continue;
            }else{
                exitlist.add(barCodeListP[i]);
            }
        }
        reSet1 = [select Id,
                        Name,
                        Product_Pattern__c,
                        Consumable_Product__r.Name,
                        Sterilization_limit__c,
                        Deliver_date__c,
                        Bar_Code__c,
                        Arrive_date__c,
                        Send_Date__c,
                        Consumable_order_minor__r.Name,
                        Consumable_order_minor__c,
                        recordtypeid,
                        Consumable_order_minor__r.Arrive_Order__c,
                        Box_Piece__c
                        ,hospitalSpecialOffer__c
                    from Consumable_order_details2__c
                    where (Dealer_Saled__c = true
                    or Dealer_Shipment__c = true)
                    and Dealer_Returned__c = false
                    and  Bar_Code__c in :exitlist
                    order by Name ];
        if(reSet1.size()>0){
            for (Integer i = 0; i < reSet1.size(); i++) {
                if(errorIdMap.containsKey(reSet1[i].Bar_Code__c) || existIdMap.containsKey(reSet1[i].Bar_Code__c)){
                    // 跳过已经处理的消耗品明细
                    continue;
                }else{
                    String str = '该商品已经出货';
                    consumableorderdetailsRecordserror.add(new ConsumableorderdetailsInfo(reSet1[i],str));
                    errorIdMap.put(reSet1[i].Bar_Code__c,reSet1[i].Bar_Code__c);
                }
            }
        }
        allMap.putAll(errorIdMap);
        for(Integer i = 0; i < barCodeListP.size(); i++){
            if(allMap.containsKey(barCodeListP[i])){
                continue;
            }else{
                notexitlist.add(barCodeListP[i]);
            }
        }
        if(notexitlist.size()>0){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'BarCode号'+ notexitlist + '不存在。'));
        }
    }

    // 单位为个的Barcode对应的出库单
    public integer Getconsumableorderdetails2Nobox(){
        if(String.isBlank(barcode)){
            return 0;
        }
        List<String> barCodeListP = ParseBarCode(barcode);
        consumableorderdetails2Nobox = new List<Consumable_order_details2__c>();
        BarcodeCntMap.clear();
        consumableorderdetails2Nobox =
                 [  select Id,
                        Name,
                        recordtypeid,
                        Used_account__c,
                        Product_Pattern__c,
                        Consumable_Product__r.Name,
                        Sterilization_limit__c,
                        Deliver_date__c,
                        Bar_Code__c,
                        Arrive_date__c,
                        Send_Date__c,
                        Consumable_order_minor__r.Name,
                        Consumable_order_minor__c,
                        Intra_Trade_List_RMB__c,
                        Asset_Model_No__c,
                        Isoverdue__c,
                        Box_Piece__c,
                        ProductPacking_list_manual__c,
                        Guarantee_period_for_products__c
                        ,hospitalSpecialOffer__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 !=null
                    AND Dealer_Info_text__c = :accountName
                    and Bar_Code__c in :barCodeListP
                    AND Arrive_Owner_Work_Location__c =: userWorkLocation
                    AND Box_Piece__c = '个'
                    order by  RemoveBox_No__c desc];

         AggregateResult[] results = [SELECT  Bar_Code__c,count(Id) recordCount 
                                      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 !=null
                                        AND Dealer_Info_text__c = :accountName
                                        and Bar_Code__c in :barCodeListP
                                        AND Arrive_Owner_Work_Location__c =: userWorkLocation
                                        AND Box_Piece__c = '个'
                                      GROUP BY Bar_Code__c];

        for(AggregateResult ar: results){
            String key ='' + ar.get('Bar_Code__c');
            BarcodeCntMap.put(key, Integer.valueOf(ar.get('recordCount')));
        }
        return consumableorderdetails2Nobox.size();
    }

    // 销售
    public PageReference ProSale() {
        if(consumableorderdetailsRecords.size()<1){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '无销售明细'));
            return null;
        }
        if(coc.Arrive_Order__r.IsShipment__c == true){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '订单已经销售'));
            return null;
        }
        Getconsumableorderdetails2Nobox();

        for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords)  {
            String key = '' + ass.orderdetails2.Bar_Code__c;
            Integer deliverycnt = BarcodeCntMap.get(key);
            if (ass.orderdetails2.Box_Piece__c =='个' && (
                ass.outboundCount == null ||
                String.valueof(ass.outboundCount) =='' ||
                ass.outboundCount <= 0)){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请输入产品 '+ ass.Prod.Name +' 的出货数量'));
                return null;
            }
            if(ass.outboundCount > deliverycnt){
                ass.orderdetails2.Rrturn_count__c.addError('超出出库数量');
                return null;
            }
        }


        for(Integer i = 0; i < orderdetails.size(); i++){

            Decimal a = 0;
            for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords)  {
                if(ass.orderdetails2.Product_Pattern__c == orderdetails[i].Product_Pattern__c){
                    a = a + ass.outboundCount;
                }
            }
            if(a< orderdetails[i].Shipment_Count__c){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'商品'+orderdetails[i].Consumable_product__r.Name +'数量小于出货数量'));
                return null;
            }else if(a > orderdetails[i].Shipment_Count__c){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'商品'+orderdetails[i].Consumable_product__r.Name +'超出出货数量'));
                return null;
            }
        
        }

        Savepoint sp = Database.setSavepoint();
        List<Consumable_orderdetails__c> orderdetails1List = [SELECT Id,
                                                                      Used_date__c 
                                                                from Consumable_orderdetails__c
                                                                WHERE Consumable_order__c =:ESetId
                                                                      ];
        try{
            if(orderdetails1List.size()>0){
                for(Integer i = 0; i < orderdetails1List.size(); i++){
                    orderdetails1List[i].RecordTypeId = System.Label.RT_ConOrderDetail1_Sale;
                    orderdetails1List[i].Used_date__c = Date.today();
                }
                ControllerUtil.updateOrderDetails1Satus(orderdetails1List);
            }
            //coc.Order_type__c = '销售';
            coc.RecordTypeId = System.Label.RT_ConOrder_Sale;
            // update start by vivek 2019-7-15
            // coc.SummonsStatus_c__c = '已完成';
            if(coc.NoConfirmedPrice__c){
                coc.SummonsStatus_c__c= '价格未定';
            }else{
                coc.SummonsStatus_c__c= '已完成';
            }
            // update start by vivek 2019-7-15
            coc.Outbound_Date__c = Date.today();
            update coc;
            //销售明细
            List<Consumable_order_details2__c> Ins = New List<Consumable_order_details2__c>();
            for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords)  {
                if(ass.orderdetails2.Box_Piece__c == '个'){
                    Decimal cnt = 1;
                    for(Consumable_order_details2__c codctmp    :   consumableorderdetails2Nobox){
                        Consumable_order_details2__c insDetails = new Consumable_order_details2__c();
                        if(codctmp.Bar_Code__c == ass.orderdetails2.Bar_Code__c){
                            insDetails.Id = codctmp.Id;
                            insDetails.Consumable_Shipment_order__c = null;
                            insDetails.Consumable_Return_order__c = null;
                            insDetails.Consumable_ZS_order__c = ESetId;
                            insDetails.Return_date__c = null;
                            insDetails.Delivery_List_RMB__c = orderpriceMap.get(ass.orderdetails2.Product_Pattern__c);
                            if(orderagencypriceMap.containsKey(ass.orderdetails2.Product_Pattern__c) == true){
                                insDetails.Unitprice_To_agency__c = orderagencypriceMap.get(ass.orderdetails2.Product_Pattern__c);
                            }
                            insDetails.Return_reason__c = null;
                            insDetails.Used_date__c = Date.today();
                            insDetails.Consumable_Sale_order__c = ESetId;
                            cnt++;
                            Ins.add(insDetails);
                            if(cnt > ass.outboundCount) break;
                        }
                    }
                }else{
                    Consumable_order_details2__c insDetails = new Consumable_order_details2__c();
                    insDetails.Id = ass.orderdetails2.Id;
                    insDetails.Consumable_Shipment_order__c = null;
                    insDetails.Consumable_Return_order__c = null;
                    insDetails.Consumable_ZS_order__c = ESetId;
                    insDetails.Return_date__c = null;
                    insDetails.Delivery_List_RMB__c = orderpriceMap.get(ass.orderdetails2.Product_Pattern__c);
                    if(orderagencypriceMap.containsKey(ass.orderdetails2.Product_Pattern__c) == true){
                        insDetails.Unitprice_To_agency__c = orderagencypriceMap.get(ass.orderdetails2.Product_Pattern__c);
                    }
                    insDetails.Return_reason__c = null;
                    insDetails.Used_date__c = Date.today();
                    insDetails.Consumable_Sale_order__c = ESetId;
                    Ins.add(insDetails);
                }
            }
            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'consumableorderdetails2Nobox +++'+consumableorderdetails2Nobox.size()));
            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Ins +++'+Ins));
            //return null;
            if(Ins.size()>0){
                ControllerUtil.updateOrderDetailsSatus(Ins);
            }
            if(coc.Arrive_Order__c!= null){
                Consumable_order__c orderUps = New Consumable_order__c();
                orderUps.Id = coc.Arrive_Order__c;
                orderUps.IsShipment__c = true;
                update orderUps;
            }
        }catch(Exception ex){
            Database.rollback(sp);
            ApexPages.addMessages(ex);
        }
        //return null;
        return ProS();
    }

    // 出货
    public PageReference ProdElivery() {

        if(coc.Arrive_Order__r.IsShipment__c == true){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '订单已经出货'));
            return null;
        }

        if(consumableorderdetailsRecords.size()<1){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '无出货明细'));
            return null;
        }

        Getconsumableorderdetails2Nobox();

        for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords)  {
            String key = '' + ass.orderdetails2.Bar_Code__c;
            Integer deliverycnt = BarcodeCntMap.get(key);
            if (ass.orderdetails2.Box_Piece__c =='个' && (
                ass.outboundCount == null ||
                String.valueof(ass.outboundCount) =='' ||
                ass.outboundCount <= 0)){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请输入产品 '+ ass.Prod.Name +' 的出货数量'));
                return null;
            }
            if(ass.outboundCount > deliverycnt){
                ass.orderdetails2.Rrturn_count__c.addError('超出出库数量');
                return null;
            }
        }

        for(Integer i = 0; i < orderdetails.size(); i++){
            Decimal a = 0;
            for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords)  {
                if(ass.orderdetails2.Product_Pattern__c == orderdetails[i].Product_Pattern__c){
                    a = a + ass.outboundCount;
                }
            }
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'商品'+a));

            if(a< orderdetails[i].Shipment_Count__c){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'商品'+orderdetails[i].Consumable_product__r.Name +'数量小于出货数量'));
                return null;
            }else if(a > orderdetails[i].Shipment_Count__c){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'商品'+orderdetails[i].Consumable_product__r.Name +'超出出货数量'));
                return null;
            }
        }
        List<Consumable_order_details2__c> Ins = New List<Consumable_order_details2__c>();
        Savepoint sp = Database.setSavepoint();
        List<Consumable_orderdetails__c> orderdetails1List = [SELECT Id,
                                                                      Used_date__c 
                                                                from Consumable_orderdetails__c
                                                                WHERE Consumable_order__c =:ESetId
                                                                      ];
        try{
            if(orderdetails1List.size()>0){
                for(Integer i = 0; i < orderdetails1List.size(); i++){
                    orderdetails1List[i].RecordTypeId = System.Label.RT_ConOrderDetail1_Shipment;
                    orderdetails1List[i].Used_date__c = Date.today();
                }
                ControllerUtil.updateOrderDetails1Satus(orderdetails1List);
            }
            //coc.Order_type__c = '出货';
            coc.RecordTypeId = System.Label.RT_ConOrder_Shipment;
            // update start by vivek 2019-7-15
            // coc.SummonsStatus_c__c = '已完成';
            if(coc.NoConfirmedPrice__c){
                coc.SummonsStatus_c__c= '价格未定';
            }else{
                coc.SummonsStatus_c__c= '已完成';
            }
            // update start by vivek 2019-7-15
            coc.Outbound_Date__c = Date.today();
            update coc;
            for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecords)  {
                if(ass.orderdetails2.Box_Piece__c == '个'){
                    Decimal cnt = 1;
                    for(Consumable_order_details2__c codctmp    :   consumableorderdetails2Nobox){
                        Consumable_order_details2__c insDetails = new Consumable_order_details2__c();
                        if(codctmp.Bar_Code__c == ass.orderdetails2.Bar_Code__c){
                            insDetails.Id = codctmp.Id;
                            insDetails.Consumable_Sale_order__c = null;
                            insDetails.Consumable_Return_order__c = null;
                            insDetails.Consumable_ZS_order__c = ESetId;
                            insDetails.Delivery_List_RMB__c = orderpriceMap.get(ass.orderdetails2.Product_Pattern__c);
                            insDetails.Return_date__c = null;
                            insDetails.Return_reason__c = null;
                            insDetails.Consumable_Shipment_order__c = ESetId;
                            insDetails.Send_Date__c = Date.today();
                            if (coc.SummonsForDirction__c == '互相调货') {
                                insDetails.Transfer_Time__c = ass.orderdetails2.Transfer_Time__c == null ? 1 : ass.orderdetails2.Transfer_Time__c + 1;
                                insDetails.Frist_Transfer_Agency__c = ass.orderdetails2.Frist_Transfer_Agency__c == null ? coc.Dealer_Info__r.Name : ass.orderdetails2.Frist_Transfer_Agency__c;
                                insDetails.Agency_Transfer__c = true;
                            }
                            cnt++;
                            Ins.add(insDetails);
                            if(cnt > ass.outboundCount) break;
                        }
                    }
                }else{
                    Consumable_order_details2__c insDetails = new Consumable_order_details2__c();
                    insDetails.Id = ass.orderdetails2.Id;
                    insDetails.Consumable_Sale_order__c = null;
                    insDetails.Consumable_Return_order__c = null;
                    insDetails.Consumable_ZS_order__c = ESetId;
                    insDetails.Delivery_List_RMB__c = orderpriceMap.get(ass.orderdetails2.Product_Pattern__c);
                    insDetails.Return_date__c = null;
                    insDetails.Return_reason__c = null;
                    insDetails.Consumable_Shipment_order__c = ESetId;
                    insDetails.Send_Date__c = Date.today();
                    if (coc.SummonsForDirction__c == '互相调货') {
                        insDetails.Transfer_Time__c = ass.orderdetails2.Transfer_Time__c == null ? 1 : ass.orderdetails2.Transfer_Time__c + 1;
                        insDetails.Frist_Transfer_Agency__c = ass.orderdetails2.Frist_Transfer_Agency__c == null ? coc.Dealer_Info__r.Name : ass.orderdetails2.Frist_Transfer_Agency__c;
                        insDetails.Agency_Transfer__c = true;
                    }
                    Ins.add(insDetails);
                }
            }
            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'consumableorderdetails2Nobox +++'+consumableorderdetails2Nobox.size()));
            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Ins +++'+Ins));
            //return null;
            if(Ins.size()>0){
                ControllerUtil.updateOrderDetailsSatus(Ins);
            }
            if(coc.Arrive_Order__c!= null){
                Consumable_order__c OrderUps = New Consumable_order__c();
                OrderUps.Id = coc.Arrive_Order__c;
                OrderUps.IsShipment__c = true;
                update OrderUps;
            }
        }catch(Exception ex){
            Database.rollback(sp);
            ApexPages.addMessages(ex);
            return null;
        }
        //return null;
        return  ProS();
    }
    /*
    // 返回按钮
    public PageReference cancel() {
        // 返回备品set
        PageReference ref = new Pagereference('/SaleAndDelivery');
        ref.setRedirect(true);
        return ref;
    }*/
    // 返回按钮
    public PageReference ProS() {
        // 返回备品set
        PageReference ref = new Pagereference('/SaleAndDelivery');
        ref.setRedirect(true);
        return ref;
    }

    class ConsumableorderdetailsInfo implements Comparable {
        public Consumable_orderdetails__c orderdetails1 { get; set; }
        public Consumable_order_details2__c orderdetails2 { get; set; }
        public Product2__c Prod { get; set; }
        public String oldConsumableCount { get; set; }
        public String ErrorReason { get; set; }
        public Decimal outboundCount { get; set; }


        public ConsumableorderdetailsInfo(Consumable_order_details2__c e,string str) {
            orderdetails1 = new Consumable_orderdetails__c();
            orderdetails2 = e;
            Prod = e.Consumable_Product__r;
            oldConsumableCount = e.name;
            ErrorReason = str;
        }

        public ConsumableorderdetailsInfo(Consumable_order_details2__c e) {
            orderdetails1 = new Consumable_orderdetails__c();
            orderdetails2 = e;
            Prod = e.Consumable_Product__r;
            if(e.Box_Piece__c == '盒'){
                outboundCount = 1;
            }
            oldConsumableCount = e.name;
        }
        public ConsumableorderdetailsInfo(Consumable_orderdetails__c e) {
            orderdetails1 = e;
            Prod = e.Consumable_Product__r;
            outboundCount = e.Shipment_Count__c;
        }
        // 排序
        public Integer compareTo(Object compareTo) {
            return null;
        }
    }

    public void testUtil() {
        Integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
    }
}