public without sharing class summonsCreatController {
    /*****************検索用******************/
    //经销商用户产品分类（ET、ENG）
    public String agencyProType {get;set;}
    public Consumable_order__c coc { get; set; }            // 画view用， 可能是 出库指示单， 也有可能是到货单， 也有可能 空instance
    public User localuser { get; set; }
    public String category1 { get; set; }
    Public Integer noOfRecords{get; set;}
    //public String category_Goods {get ; set;}
    public Boolean cansee{get;set;}
    Public Integer size{get;set;}
    //经销商定价查看权限
    public ApexPages.StandardSetController setCon { get; set; }
    public Boolean dealerPricesee {get;set;}
    /*****************画面初始化用********************************/
    /******20160313_add**************/
    public String IdCheck {get;set;}
    public Boolean editAble {get;set;}
    public String statusEdit {get;set;}
    public String alertMessage{set;get;}
    public String SearchDone {get;set;}
    List<String> zaikuId = new List<String>();
    List<String> orderzaikuId = new List<String>();
    //附件
    public List<ConsumableorderdetailsInfo> attachmentRecoeds { get; set; }
    public Boolean getExistarrive() {
        return (coc.Arrive_Order__c != null);
    }
    //总价格计算结果
    public Decimal sumPrice {get;set;}
    /******20160317_add**************/
    public String SummonsFlag {get;set;}         // 新規: hidden, 更新: visible
    public String category5 { get; set; }
    public String category4 { get; set; }
    public String category3 { get; set; }
    public List<SelectOption> categoryOptionList{get;set;}
    public List<SelectOption> category4OptionList{get;set;}
    public List<SelectOption> category5OptionList{get;set;}
    /*****************画面表示Bean******************/
    private List<ConsumableorderdetailsInfo> consumableorderdetailsSelectRecords = new List<ConsumableorderdetailsInfo>();
    public List<ConsumableorderdetailsInfo> pageRecords { get; set; }
    //public List<List<ConsumableorderdetailsInfo>> consumableorderdetailsRecordsview { get; set; }
    public List<ConsumableorderdetailsInfo> consumableorderdetails2Records { get; set; }
    public List<Consumable_order__c> consumableInvoiceRecords { get; set; }
    private List<ConsumableorderdetailsInfo> consumableproductdetailsRecords = new List<ConsumableorderdetailsInfo>();
    private List<Attachment> attachmentinfo = new List<Attachment>();
    List<Product2__c> product2Selected = new List<Product2__c>();
    //选择产品size
    public Integer consumableorderdetailsCount {
        get {
            return pageRecords == null ? 0 : pageRecords.size();
        }
    }
    //消耗品明细2数量
    public Integer consumableorderdetails2Count {
        get {
            return consumableorderdetails2Records == null ? 0 : consumableorderdetails2Records.size();
        }
    }
    //订货单号
    public String consumableorderId {
        get {
            return (coc.Arrive_Order__c);
        }
    }
    //选择框
    public List<SelectOption> provinceOpts  { get; set; }
    public String SecondDealer {get;set;}
    //public List<SelectOption> orderForHospitalOpts { get; set; }
    public String HospitalInfo {get;set;}
    public String HospitalName {get;set;}

    public Boolean EditDelCommitBtnDisabled {get; private set;}
    public Boolean saveBtnDisabled { get; private set; }
    public Boolean SorderBtnDisabled { get; private set; }
    // 保存后动作： 1.检索 2.排序
    public String sortKey { get; set; }
    public String preSortKey { get; private set; }
    public Boolean sortOrderAsc { get; private set; }
    public String[] sortOrder { get; private set; }
    private String[] columus = new String[]{ 'Consumable_Product__r.Name','Consumable_Product__r.Asset_Model_No__c','Consumable_Product__r.Intra_Trade_List_RMB__c','','','Consumable_Product__r.Category3__c','Consumable_Product__r.Category4__c','Consumable_Product__r.Category5__c'};
    private String[] columus_no = new String[]{ 'Product2__c.Name','Product2__c.Asset_Model_No__c','Product2__c.Intra_Trade_List_RMB__c','','','Category3__c','Category4__c','Category5__c'};

    //到货单明细1
    private List<Consumable_Orderdetails__c> consumableorderdetailsSelected = new List<Consumable_Orderdetails__c>();
    //到货单明细2
    private List<Consumable_order_details2__c> consumablearriveproductdetailsSelected = new List<Consumable_order_details2__c>();

    //出库单明细2
    private List<Consumable_order_details2__c> consumableorderdetails2RecordsList = new List<Consumable_order_details2__c>();
    /*****************ソート時再検索条件（画面からの入力条件を無視するため）******************/
    //private String cate1ForSort = null;
    private String accountid = null;
    private String accountName = null;

    // 产品 ID
    private String ESetId = '';
    public String arriveorder {get;set;}
    private String userId = '';
    //private String[] ProidListAll = new String[]{};

    // 登录者工作地
    private String userWorkLocation;

    //add by rentx 2021-01-29 
    public List<SelectOption> outOutPatternOptionList{get;set;}
    public String outOutPattern {get;set;}
    public Boolean hasHos {get;set;}
    public Boolean hasHosPro {get;set;}

    private Map<String,String> HosProMap = new Map<String,String>();
    //add by rentx 2021-01-29

    public summonsCreatController() {
        size = Integer.valueOf(System.Label.orderdetLimitsize);
        ESetId = ApexPages.currentPage().getParameters().get('esetId');
        arriveorder = ApexPages.currentPage().getParameters().get('arriveorder');
        statusEdit = ApexPages.currentPage().getParameters().get('KeyWords');
        provinceOpts = new List<SelectOption>();
        pageRecords = new List<ConsumableorderdetailsInfo>();
        consumableproductdetailsRecords = new List<ConsumableorderdetailsInfo>();
        consumableorderdetailsSelectRecords = new List<ConsumableorderdetailsInfo>();
        attachmentRecoeds = new List<ConsumableorderdetailsInfo>();
        consumableorderdetails2Records = new List<ConsumableorderdetailsInfo>();
        consumableInvoiceRecords = new List<Consumable_order__c>();
        categoryOptionList = new List<SelectOption>();
        category4OptionList = new List<SelectOption>();
        category5OptionList = new List<SelectOption>();
        outOutPatternOptionList = new List<SelectOption>();
        outOutPatternOptionList.add(new SelectOption('','-无-'));
        outOutPatternOptionList.add(new SelectOption('ishos','医院特价产品'));
        outOutPatternOptionList.add(new SelectOption('nothos','非医院特价产品'));

    }
    private void initStandardController(String soql){
        // init standard controller
        setCon = new ApexPages.StandardSetController(Database.getQueryLocator(soql));
        // sets the number of records in each page set
        setCon.setPageSize(size);
        //因为现在有区分医院特价和非医院特价,所以产品数应该为展示的数据长度
        // noOfRecords = setCon.getResultSize();
    }
    public List<Product2__c> product2s() {
         return (List<Product2__c>) setCon.getRecords();
    }
    //Changes the size of pagination
    public PageReference refreshPageSize() {
        setCon.setPageSize(size);
        product2Selected = product2s();
        makepagerecords();
        return null;
    }
    public List<ConsumableorderdetailsInfo> makepagerecords() {
        List<ConsumableorderdetailsInfo> reSet = new List<ConsumableorderdetailsInfo>();
        Map<String, String> selectedIdMap = new Map<String, String>();
        //取出选择的产品
        for (ConsumableorderdetailsInfo ass : pageRecords)  {
            //update by rentx 2021-2-26
            // if(ass.check == true){
                // selectedIdMap.put(ass.Prod.id,ass.Prod.id);
                // reSet.add(ass);
            // }
            if (ass.check == true) {
                if (ass.hospitalSpecialOffer == true) {
                    selectedIdMap.put(ass.Prod.Id +'ishos' , ass.Prod.Id);
                }else{
                    selectedIdMap.put(ass.Prod.Id +'nothos', ass.Prod.Id);
                }
                reSet.add(ass);
            }
            //update by rentx 2021-2-26 

        }
        pageRecords = new List<ConsumableorderdetailsInfo>();
        if (editAble && String.isBlank(arriveorder)){
            pageRecords = reSet;
        }
        Integer pagestartNo = (setCon.getPageNumber() * size)-size;
        Integer pageendNo = (setCon.getPageNumber() * size)>noOfRecords ? noOfRecords :(setCon.getPageNumber() * size-1);
        Integer addNo = 0;
        //update by rentx 2021-2-26 start
        for (ConsumableorderdetailsInfo info : consumableorderdetailsSelectRecords) {

            Consumable_Orderdetails__c orderdetails1 = new Consumable_Orderdetails__c();
            if ((info.hospitalSpecialOffer && selectedIdMap.containsKey(info.Prod.Id + 'ishos')) 
                || (info.hospitalSpecialOffer == false && selectedIdMap.containsKey(info.Prod.Id + 'nothos'))) {
                addNo++;

            }else{
                if(info.check == false){
                    info.orderdetails1 = orderdetails1;
                }
                pageRecords.add(info);
                addNo++;
            }
            // if(addNo >= size)break;
        }
        // for (Integer i = pagestartNo; i < consumableorderdetailsSelectRecords.size(); i++) {
        //     Consumable_Orderdetails__c orderdetails1 = new Consumable_Orderdetails__c();
        //     if(selectedIdMap.containsKey(consumableorderdetailsSelectRecords[i].Prod.Id)){
        //         addNo++;
        //         //continue;
        //     }else{
        //         //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '-----'));
        //         if(consumableorderdetailsSelectRecords[i].check == false){
        //             consumableorderdetailsSelectRecords[i].orderdetails1 = orderdetails1;
        //         }
        //         pageRecords.add(consumableorderdetailsSelectRecords[i]);
        //         addNo++;
        //     }
        //     if(addNo >= size)break;
        // }
        //update by rentx 2021-2-26 end
         return pageRecords;
    }
    //add by rentx 2021-2-26 start
    public void checkOutPattern(){
        //根据用户选中的产品给 出库单上的是否医院特价出库字段赋值
        Integer isHos = 0;
        for(ConsumableorderdetailsInfo CheckCount : pageRecords) {
            if (CheckCount.check == true && CheckCount.hospitalSpecialOffer == true) {
                ishos = ishos +1;
            }
        }
        if (isHos > 0) {
            coc.OutPattern__c = true;
        }else{
            coc.OutPattern__c = false;
        }
    }
    //add by rentx 2021-2-26 end
    // 画面初始化
    public   void init() {

        this.sortKey = '1';
        this.preSortKey = '1';
        this.sortOrderAsc = false;
        this.sortOrder = new String[8];
        this.sortOrder = new String[]{' ',' ',' ',' ','↓','','',''};
        //cate1ForSort = '';
        sumPrice = 0;
        IdCheck = EsetId;
        if(ESetId!=null&&ESetId!=''&&(statusEdit==''|| statusEdit==null)){
            editAble = false;
        }else if((ESetId == null||ESetId=='')&&(statusEdit==''||statusEdit==null)){
            editAble = true;
        }else if(ESetId != null&&ESetId!=''&&statusEdit!=''&&statusEdit!=null){
            editAble = true;
        }
        userId = UserInfo.getUserId();
        localuser = [select id, State_Hospital__c from User where id = :UserInfo.getUserId()];
        //userId = '00510000005QO75';
        user Useracc = [SELECT accountid, Work_Location__c,UserPro_Type__c FROM user WHERE id = :userId ];
        accountid = Useracc.accountid;
        userWorkLocation = Useracc.Work_Location__c;
        agencyProType = Useracc.UserPro_Type__c;
        if(String.isBlank(Useracc.UserPro_Type__c)){
            agencyProType = 'ET';
        }
        Account accountInfo = [SELECT Name FROM account WHERE id =:accountid];
        accountName = accountInfo.Name;
        //coc.Order_date__c = Date.today();
        list<Dealer_elationship__c> Dealerelationship = new list<Dealer_elationship__c>();
        Dealerelationship = [SELECT Dealer_subordinate__c,Dealer_subordinate__r.Name FROM Dealer_elationship__c WHERE Dealer_principal__c =:accountid ];

        List<Agency_Hospital_Link__c> AgencyHospitalLink = new List<Agency_Hospital_Link__c>();
        AgencyHospitalLink = [select Id,Hospital__c, Hospital__r.Name from Agency_Hospital_Link__c WHERE Agency__c = :accountid];

        //add by rentx 2021-3-1 start
        //判断当前经销商下是否有特价医院
        List<hospitalprice__c> hlist = [select id,product__c from hospitalprice__c where account__c = :accountid];
        if (hlist == null || hlist.size() == 0) {
            hasHos = false;
        }else{
            for (hospitalprice__c hp : hlist) {
                HosProMap.put(hp.product__c, '');
            }
            hasHos = true;
        }
        //add by rentx 2021-3-1 end


        saveBtnDisabled = false;
        SorderBtnDisabled = false;
        String sqlagencyProType = '%' + agencyProType + '%';
        coc = new Consumable_order__c();
        consumableorderdetailsSelectRecords = new List<ConsumableorderdetailsInfo>();
        Map<String,ConsumableorderdetailsInfo> MidMap = new Map<String,ConsumableorderdetailsInfo>();
        //add by rentx 2021-01-29
        Map<String,ConsumableorderdetailsInfo> MidMap2 = new Map<String,ConsumableorderdetailsInfo>();
        //add by rentx 2021-01-29

        List<AggregateResult> orderdetailCount = [SELECT count(id),Consumable_Product__c cpc,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 Cancellation_Flag__c = false
                                                    AND Bar_Code__c !=null
                                                    AND Isoverdue__c = 1
                                                    AND Product_Type__c like : sqlagencyProType
                                                    AND Dealer_Info_text__c = :accountName
                                                    AND Arrive_Owner_Work_Location__c =: userWorkLocation
                                                    group by Consumable_Product__c,Box_Piece__c ];
        for(AggregateResult orderdetail : orderdetailCount){
            zaikuId.add(String.valueOf(orderdetail.get('cpc')));
        }
        List<Consumable_order_details2__c> CountDel = [SELECT Id,
                                                        Bar_Code__c,
                                                        Name,
                                                        Inventory_date__c,
                                                        Consumable_Product__c,
                                                        Consumable_Product__r.Asset_Model_No__c,
                                                        Recordtypeid,
                                                        Box_Piece__c,ProductPacking_list_manual__c,
                                                        //add by rentx 2020-11-27 start
                                                        hospitalSpecialOffer__c 
                                                        //add by rentx 2020-11-27 end
                                                    FROM Consumable_order_details2__c
                                                    WHERE Dealer_Arrive__c = true
                                                    AND Dealer_Shipment__c = false
                                                    AND Dealer_Saled__c = false
                                                    AND Dealer_Returned__c = false
                                                    AND Lose_Flag__c = false
                                                    AND Cancellation_Flag__c = false
                                                    AND Bar_Code__c !=null
                                                    AND Isoverdue__c = 1
                                                    AND Product_Type__c like : sqlagencyProType
                                                    AND Arrive_Owner_Work_Location__c =: userWorkLocation
                                                    AND Dealer_Info_text__c = :accountName ];
        // 新規
        if (ESetId== NULL || ESetId=='') {
            SummonsFlag = 'hidden';
            String msoql = makeSoqlinventory();
            initStandardController(msoql);
            product2Selected = Database.query(msoql);
            //product2Selected = product2s();
            if (String.isBlank(arriveorder)) {
                EditDelCommitBtnDisabled = true;
                for (Integer i = 0; i < product2Selected.size(); i++) {
                    MidMap.put(product2Selected[i].Id, new ConsumableorderdetailsInfo(product2Selected[i]));
                }
                //update by rentx 2021-01-29
                /*for(Integer i = 0 ; i< CountDel.size();i++){
                    //然后循环CountDel去修改map里的allnumber
                    if(MidMap.containsKey(CountDel[i].Consumable_Product__c)){
                        ConsumableorderdetailsInfo Jstage = MidMap.get(CountDel[i].Consumable_Product__c);
                        Jstage.allnumber = Jstage.allnumber+1 ;
                        if(CountDel[i].Box_Piece__c == '盒'){
                            Jstage.Boxnumber = Jstage.Boxnumber + 1;
                        }else if(CountDel[i].Box_Piece__c == '个'){
                            Jstage.Piecenumber = Jstage.Piecenumber + 1;
                        }
                        //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                        MidMap.put(CountDel[i].Consumable_Product__c, Jstage);
                    }

                }*/
                for(Integer i = 0 ; i< CountDel.size();i++){
                    String str = '';
                    if (CountDel[i].hospitalSpecialOffer__c) {
                        str = 'isHos';
                    }else{
                        str = 'notHos';
                    }
                    //明细2对应的产品存在于MidMap中
                    if (MidMap.containsKey(CountDel[i].Consumable_Product__c)) {
                        //设置map中key的后缀 用于区分医院特价和非医院特价
                        if (MidMap2.containsKey(CountDel[i].Consumable_Product__c + str)) {
                            ConsumableorderdetailsInfo Jstage = MidMap2.get(CountDel[i].Consumable_Product__c+str);
                            Jstage.allnumber = Jstage.allnumber+1 ;
                            if(CountDel[i].Box_Piece__c == '盒'){
                                Jstage.Boxnumber = Jstage.Boxnumber + 1;
                            }else if(CountDel[i].Box_Piece__c == '个'){
                                Jstage.Piecenumber = Jstage.Piecenumber + 1;
                            }
                            if (CountDel[i].hospitalSpecialOffer__c) {
                                Jstage.hospitalSpecialOffer = true;
                            }else{
                                Jstage.hospitalSpecialOffer = false;
                            }
                            if (HosProMap.containsKey(Jstage.Prod.Id)) {
                                Jstage.hosPro = true;
                            }
                            MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                        }else{
                            //midmap2中没有对应的产品
                            ConsumableorderdetailsInfo Jstage = MidMap.get(CountDel[i].Consumable_Product__c).clone();
                            Jstage.allnumber = Jstage.allnumber+1 ;
                            if(CountDel[i].Box_Piece__c == '盒'){
                                Jstage.Boxnumber = Jstage.Boxnumber + 1;
                            }else if(CountDel[i].Box_Piece__c == '个'){
                                Jstage.Piecenumber = Jstage.Piecenumber + 1;
                            }
                            if (CountDel[i].hospitalSpecialOffer__c) {
                                Jstage.hospitalSpecialOffer = true;
                            }else{
                                Jstage.hospitalSpecialOffer = false;
                            }
                            if (HosProMap.containsKey(Jstage.Prod.Id)) {
                                Jstage.hosPro = true;
                            }
                            //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                            MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                        }
                    }
                    /*//然后循环CountDel去修改map里的allnumber
                    if(MidMap.containsKey(CountDel[i].Consumable_Product__c)){
                        ConsumableorderdetailsInfo Jstage = MidMap.get(CountDel[i].Consumable_Product__c);
                        Jstage.allnumber = Jstage.allnumber+1 ;
                        if(CountDel[i].Box_Piece__c == '盒'){
                            Jstage.Boxnumber = Jstage.Boxnumber + 1;
                        }else if(CountDel[i].Box_Piece__c == '个'){
                            Jstage.Piecenumber = Jstage.Piecenumber + 1;
                        }
                        if (CountDel[i].hospitalSpecialOffer__c) {
                            Jstage.hospitalSpecialOffer = true;
                        }else{
                            Jstage.hospitalSpecialOffer = false;
                        }
                        //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                        MidMap.put(CountDel[i].Consumable_Product__c+str, Jstage);
                    }*/

                }

                //update by rentx 2021-01-29 end


                //再把map里的值从新赋给ConsumableorderdetailsRecords
                //update by rentx 2021-01-29
                // for(ConsumableorderdetailsInfo bss : MidMap.values()){
                for(ConsumableorderdetailsInfo bss : MidMap2.values()){
                //update by rentx 2021-01-29
                    //if(bss.allnumber>0){
                        bss.packinglist = Integer.valueOf(bss.Prod.Product2__r.Packing_list_manual__c);
                        bss.approbation_No = bss.Prod.Product2__r.SFDA_Approbation_No__c;
                        bss.expiration_Date = bss.Prod.Product2__r.SFDA_Expiration_Date__c;
                        consumableorderdetailsSelectRecords.add(bss);
                    //}
                }
                
                Integer ishosnum = 0;
                for(ConsumableorderdetailsInfo ass : consumableorderdetailsSelectRecords){
                    ass.sortBy = this.sortOrderAsc;
                    //add by rentx 2021-3-10
                    if (ass.hospitalSpecialOffer) {
                        ishosnum = ishosnum +1;
                    }
                }
                if (ishosnum > 0) {
                    hasHosPro = true;
                }else{
                    hasHosPro = false;
                }
                consumableorderdetailsSelectRecords.sort();
                //add by rentx
                noOfRecords = consumableorderdetailsSelectRecords.size();
                //add by rentx
                makepagerecords();
                //listCut();


            } else {
                if(statusEdit=='' || statusEdit==null){
                    editAble = false;
                }else if(statusEdit!=''&&statusEdit!=null){
                    editAble = true;
                }
                // upadte start by vivek 2019-7-15
                // coc = [SELECT Id,Name,Summons_Order_type__c,SummonsStatus_c__c,Order_ForDealerText__c,
                //             Dealer_Info__c,Order_ForDealer__c,Order_ForDealer__r.Name,Order_ForDealerTextID__c,
                //             Order_ForHospital__c,SummonsForDirction__c,Order_date__c,Arrive_Order__c,
                //             Order_status__c,Shipment_total_amount__c,Offers_Price__c,
                //             Billed_Status__c,ShipmentAccount__c,Order_Dealer_Info__c,Order_ForCustomerText__c,ConInvoice_Code__c,Onchange_order__c
                //         FROM Consumable_order__c
                //         WHERE Id =:arriveorder AND Order_Owner_WorkLocal__c =: userWorkLocation
                //         AND recordtypeid = :System.Label.RT_ConOrder_Arrive];
                coc = [SELECT Id,Name,Summons_Order_type__c,NoConfirmedPrice__c,SummonsStatus_c__c,Order_ForDealerText__c,
                            Dealer_Info__c,Order_ForDealer__c,Order_ForDealer__r.Name,Order_ForDealerTextID__c,
                            Order_ForHospital__c,SummonsForDirction__c,Order_date__c,Arrive_Order__c,
                            Order_status__c,Shipment_total_amount__c,Offers_Price__c,
                            Billed_Status__c,ShipmentAccount__c,Order_Dealer_Info__c,Order_ForCustomerText__c,ConInvoice_Code__c,Onchange_order__c,OutPattern__c 
                        FROM Consumable_order__c
                        WHERE Id =:arriveorder AND Order_Owner_WorkLocal__c =: userWorkLocation
                        AND recordtypeid = :System.Label.RT_ConOrder_Arrive];
                // update end by vivek 2019-7-15
                //明细1获取
                consumableorderdetailsSelected = [SELECT Id,Dealer_Custom_Price__c,Delivery_List_RMB__c,
                                                    Consumable_Product__r.Name__c, Name, Consumable_order__c,
                                                    Consumable_Product__c,Consumable_Product__r.Name,Consumable_Product__r.Category3__c,
                                                    Consumable_Product__r.Category4__c,Consumable_Product__r.Category5__c,
                                                    Shipment_Count__c,Consumable_Product__r.Intra_Trade_List_RMB__c,
                                                    Consumable_Product__r.Asset_Model_No__c,Sum_of_money__c,Box_Piece__c,
                                                    ProductPacking_list_manual__c,Consumable_Product__r.SFDA_Status__c,
                                                    Consumable_count__c,Invoiced_Procount__c,
                                                    RrturnPro_count__c,
                                                    InvoiceProNot_count__c,
                                                    //Unitprice_To_agency__c,
                                                    Consumable_Product__r.Product2__r.SFDA_Approbation_No__c,
                                                    Consumable_Product__r.Product2__r.SFDA_Expiration_Date__c
                                                FROM Consumable_Orderdetails__c
                                                WHERE Consumable_order__c = :coc.Arrive_Order__c
                                                order by Name ];
                for (Consumable_Orderdetails__c cdc1 : consumableorderdetailsSelected) {
                    orderzaikuId.add(cdc1.Consumable_Product__c);
                }
                msoql = makeSoqlorderdet();
                product2Selected = Database.query(msoql);
                size = product2Selected.size();
                initStandardController(msoql);
                for (Integer i = 0; i < product2Selected.size(); i++) {
                    MidMap.put(product2Selected[i].Id, new ConsumableorderdetailsInfo(product2Selected[i]));
                }
                //update by rentx 2021-01-29 
                /*for(Integer i = 0 ; i< CountDel.size();i++){
                    //然后循环CountDel去修改map里的allnumber
                    if(MidMap.containsKey(CountDel[i].Consumable_Product__c)){
                        ConsumableorderdetailsInfo Jstage = MidMap.get(CountDel[i].Consumable_Product__c);
                        Jstage.allnumber = Jstage.allnumber+1 ;
                        if(CountDel[i].Box_Piece__c == '盒'){
                            Jstage.Boxnumber = Jstage.Boxnumber + 1;
                        }else if(CountDel[i].Box_Piece__c == '个'){
                            Jstage.Piecenumber = Jstage.Piecenumber + 1;
                        }
                        //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                        MidMap.put(CountDel[i].Consumable_Product__c, Jstage);
                    }

                }*/
                for (Integer i = 0; i<CountDel.size() ; i++) {
                    String str = '';
                    if (CountDel[i].hospitalSpecialOffer__c) {
                        str = 'isHos';
                    }else{
                        str = 'notHos';
                    }
                    //明细2对应的产品存在于MidMap中
                    if (MidMap.containsKey(CountDel[i].Consumable_Product__c)) {
                        //设置map中key的后缀 用于区分医院特价和非医院特价
                        if (MidMap2.containsKey(CountDel[i].Consumable_Product__c + str)) {
                            ConsumableorderdetailsInfo Jstage = MidMap2.get(CountDel[i].Consumable_Product__c+str);
                            Jstage.allnumber = Jstage.allnumber+1 ;
                            if(CountDel[i].Box_Piece__c == '盒'){
                                Jstage.Boxnumber = Jstage.Boxnumber + 1;
                            }else if(CountDel[i].Box_Piece__c == '个'){
                                Jstage.Piecenumber = Jstage.Piecenumber + 1;
                            }
                            if (CountDel[i].hospitalSpecialOffer__c) {
                                Jstage.hospitalSpecialOffer = true;
                            }else{
                                Jstage.hospitalSpecialOffer = false;
                            }

                            if (HosProMap.containsKey(Jstage.Prod.Id)) {
                                Jstage.hosPro = true;
                            }
                            MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                        }else{
                            //midmap2中没有对应的产品
                            ConsumableorderdetailsInfo Jstage = MidMap.get(CountDel[i].Consumable_Product__c).clone();
                            Jstage.allnumber = Jstage.allnumber+1 ;
                            if(CountDel[i].Box_Piece__c == '盒'){
                                Jstage.Boxnumber = Jstage.Boxnumber + 1;
                            }else if(CountDel[i].Box_Piece__c == '个'){
                                Jstage.Piecenumber = Jstage.Piecenumber + 1;
                            }
                            if (CountDel[i].hospitalSpecialOffer__c) {
                                Jstage.hospitalSpecialOffer = true;
                            }else{
                                Jstage.hospitalSpecialOffer = false;
                            }

                            if (HosProMap.containsKey(Jstage.Prod.Id)) {
                                Jstage.hosPro = true;
                            }
                            //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                            MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                        }
                    }
                }

                //再把map里的值从新赋给ConsumableorderdetailsRecords
                //update by rentx 2021-01-29 
                // for(ConsumableorderdetailsInfo bss : MidMap.values()){
                for(ConsumableorderdetailsInfo bss : MidMap2.values()){
                //update by rentx 2021-01-29 
                    bss.packinglist = Integer.valueOf(bss.Prod.Product2__r.Packing_list_manual__c);
                    bss.approbation_No = bss.Prod.Product2__r.SFDA_Approbation_No__c;
                    bss.expiration_Date = bss.Prod.Product2__r.SFDA_Expiration_Date__c;
                    consumableorderdetailsSelectRecords.add(bss);
                }
                //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'test11111' + consumableorderdetailsSelected.size()));
                //return;

                Integer ishosnum = 0;
                for(ConsumableorderdetailsInfo ass : consumableorderdetailsSelectRecords){
                    ass.sortBy = this.sortOrderAsc;
                    for (Consumable_Orderdetails__c cdc1 : consumableorderdetailsSelected) {
                        cdc1.Shipment_Count__c = cdc1.Consumable_count__c;
                        if(ass.prod.Id == cdc1.Consumable_Product__c){
                            ass.check = true;
                            ass.orderdetails1 = cdc1;
                        }
                    }
                    if (ass.hospitalSpecialOffer == true) {
                        ishosnum = ishosnum + 1;
                    }
                }
                if (ishosnum > 0) {
                    hasHosPro = true;
                }else{
                    hasHosPro = false;
                }

                consumableorderdetailsSelectRecords.sort();
                //add by rentx
                noOfRecords = consumableorderdetailsSelectRecords.size();
                //add by rentx
                makepagerecords();
                consumablearriveproductdetailsSelected = [
                        SELECT Id,
                            Name,
                            Intra_Trade_List_RMB__c,
                            Asset_Model_No__c,
                            Consumable_Product__c,
                            Consumable_Product__r.Name,
                            Consumable_Product__r.Name__c,
                            Consumable_Product__r.Category3__c,
                            Consumable_Product__r.Category4__c,
                            Consumable_Product__r.Category5__c,
                            Sterilization_limit__c,
                            Deliver_date__c,
                            Bar_Code__c,
                            Arrive_date__c,
                            Send_Date__c,
                            Consumable_order_minor__r.Name,
                            Consumable_order_minor__c,
                            Dealer_Arrive__c,
                            Delivery_List_RMB__c,
                            Box_Piece__c,ProductPacking_list_manual__c,
                            //add by rentx start
                            hospitalSpecialOffer__c
                            //add by rentx end
                        FROM Consumable_order_details2__c
                        WHERE Consumable_order_minor__c = :coc.Arrive_Order__c
                        AND recordtypeid = :System.Label.RT_ConOrderDetail2_Delivery
                        AND Dealer_Arrive__c = true
                        order by Name];
                for (Integer i = 0; i < consumablearriveproductdetailsSelected.size(); i++) {
                    if (consumablearriveproductdetailsSelected[i].hospitalSpecialOffer__c && HosProMap.containsKey(consumablearriveproductdetailsSelected[i].Consumable_product__c)) {
                        coc.OutPattern__c = true;
                    }
                    consumableproductdetailsRecords.add(new ConsumableorderdetailsInfo(consumablearriveproductdetailsSelected[i]));
                }
            }
        }
        // 更新、
        else {
            SummonsFlag = 'visible';
            // update start by vivek 2019-7-15 add “NoConfirmedPrice__c” in select
            consumableInvoiceRecords  = [SELECT Id,Name,Invoice_Date__c,NoConfirmedPrice__c,Invoice_total_amount__c,Invoice_status__c
                    FROM Consumable_order__c
                    WHERE Id in (select Invoice_Code_link__c FROM Consumable_order_LinkTable__c WHERE Outboundorder_Code_link__c = :ESetId)
                    AND Invoice_status__c != '草案中'];

            coc = [SELECT Id,Name,Summons_Order_type__c,NoConfirmedPrice__c,SummonsStatus_c__c,Order_ForDealerText__c,
                        Dealer_Info__c,Order_ForDealer__c,Order_ForDealer__r.Name,Order_ForDealerTextID__c,
                        Order_ForHospital__c,SummonsForDirction__c,Order_date__c,Arrive_Order__c,
                        Order_status__c,Shipment_total_amount__c,Offers_Price__c,
                        Billed_Status__c,ShipmentAccount__c,Order_Dealer_Info__c,Order_ForCustomerText__c,ConInvoice_Code__c,Onchange_order__c,OutPattern__c
                    FROM Consumable_order__c
                    WHERE Id =:ESetId AND Order_Owner_WorkLocal__c =: userWorkLocation
                    AND Order_type__c = '传票'];
            // update start by vivek 2019-7-15
            if(getExistarrive()){
                arriveorder = coc.Arrive_Order__c;
            }
            // 到货订单来的时候
            if (getExistarrive()) {
                if(editAble){
                    alertMessage = '到货订单直接出库，出库单明细不可编辑。';
                }
                if(coc.SummonsStatus_c__c == '已提交' || coc.SummonsStatus_c__c == '批准'){
                    system.debug('coc.SummonsStatus_c__c : ' + coc.SummonsStatus_c__c);
                    saveBtnDisabled = true;
                    SorderBtnDisabled = true;
                    EditDelCommitBtnDisabled = false;
                }
                //医院二级经销商分类
                Integer io = 0;
                while( io < Dealerelationship.size()){
                    if(coc.Order_ForDealer__c == Dealerelationship[io].Dealer_subordinate__c){
                        SecondDealer = Dealerelationship[io].Dealer_subordinate__c;
                        coc.Order_ForDealer__c = null;
                        io = io+Dealerelationship.size();
                     }
                     io++;
                }

                Integer ik = 0;
                while( ik < AgencyHospitalLink.size()){
                    if(coc.Order_ForHospital__c == AgencyHospitalLink[ik].Hospital__c){
                        HospitalInfo = AgencyHospitalLink[ik].Hospital__c;
                        HospitalName = AgencyHospitalLink[ik].Hospital__r.Name;
                        coc.Order_ForHospital__c = null;
                        ik = ik+AgencyHospitalLink.size();
                     }
                     ik++;
                }
                //出库单明细1取得
                consumableorderdetailsSelected = [SELECT Id,
                                                        Dealer_Custom_Price__c,
                                                        Delivery_List_RMB__c,
                                                        Consumable_Product__r.Name__c,
                                                        Consumable_Product__r.SFDA_Status__c,
                                                        Name, Consumable_order__c,
                                                        Consumable_Product__c,
                                                        Consumable_Product__r.Name,
                                                        Shipment_Count__c,
                                                        Consumable_Product__r.Intra_Trade_List_RMB__c,
                                                        Consumable_Product__r.Asset_Model_No__c,
                                                        Consumable_Product__r.Category3__c,
                                                        Consumable_Product__r.Category4__c,
                                                        Consumable_Product__r.Category5__c,
                                                        Shipment_amount__c,
                                                        //Unitprice_To_agency__c,
                                                        Box_Piece__c,ProductPacking_list_manual__c
                                                        ,Invoiced_Procount__c,
                                                        RrturnPro_count__c,
                                                        InvoiceProNot_count__c,
                                                        Consumable_Product__r.Product2__r.SFDA_Approbation_No__c,
                                                        Consumable_Product__r.Product2__r.SFDA_Expiration_Date__c
                                                        ,isOutPattern__c
                                                     FROM Consumable_orderdetails__c
                                                     WHERE Consumable_order__c = :ESetId
                                                     AND Consumable_order__r.Order_Owner_WorkLocal__c =: userWorkLocation
                                                     order by Name ];
                Map<String,Consumable_Orderdetails__c> cocMap = new Map<String,Consumable_Orderdetails__c>();

                for (Consumable_Orderdetails__c cdc1 : consumableorderdetailsSelected) {
                    sumPrice += cdc1.Shipment_amount__c;
                    orderzaikuId.add(cdc1.Consumable_Product__c);
                    //add by rentx 2021-2-26
                    String tempId = cdc1.Consumable_product__c;
                    if (cdc1.isOutPattern__c) {
                        cocMap.put(tempId+'ishos', cdc1);
                    }else{
                        cocMap.put(tempId+'nothos', cdc1);
                    }
                    //add by rentx 2021-2-26
                }
                String msoql = makeSoqlorderdet();
                product2Selected = Database.query(msoql);
                size = product2Selected.size();
                initStandardController(msoql);


                for (Integer i = 0; i < product2Selected.size(); i++) {
                    MidMap.put(product2Selected[i].Id, new ConsumableorderdetailsInfo(product2Selected[i]));
                }
                //update by rentx 2021-01-29
                /*for(Integer i = 0 ; i< CountDel.size();i++){
                    //然后循环CountDel去修改map里的allnumber
                    if(MidMap.containsKey(CountDel[i].Consumable_Product__c)){
                        ConsumableorderdetailsInfo Jstage =  MidMap.get(CountDel[i].Consumable_Product__c);
                        Jstage.allnumber = Jstage.allnumber+1 ;
                        if(CountDel[i].Box_Piece__c == '盒'){
                            Jstage.Boxnumber = Jstage.Boxnumber + 1;
                        }else if(CountDel[i].Box_Piece__c == '个'){
                            Jstage.Piecenumber = Jstage.Piecenumber + 1;
                        }
                        //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                        MidMap.put(CountDel[i].Consumable_Product__c, Jstage);
                    }
                }*/

                for (Integer i = 0; i < CountDel.size() ;i++ ) {
                    String str = '';
                    if (CountDel[i].hospitalSpecialOffer__c) {
                        str = 'isHos';
                    }else{
                        str = 'notHos';
                    }
                    //明细2对应的产品存在于MidMap中
                    if (MidMap.containsKey(CountDel[i].Consumable_Product__c)) {
                        //设置map中key的后缀 用于区分医院特价和非医院特价
                        if (MidMap2.containsKey(CountDel[i].Consumable_Product__c + str)) {
                            ConsumableorderdetailsInfo Jstage = MidMap2.get(CountDel[i].Consumable_Product__c+str);
                            Jstage.allnumber = Jstage.allnumber+1 ;
                            if(CountDel[i].Box_Piece__c == '盒'){
                                Jstage.Boxnumber = Jstage.Boxnumber + 1;
                            }else if(CountDel[i].Box_Piece__c == '个'){
                                Jstage.Piecenumber = Jstage.Piecenumber + 1;
                            }
                            if (CountDel[i].hospitalSpecialOffer__c) {
                                Jstage.hospitalSpecialOffer = true;
                            }else{
                                Jstage.hospitalSpecialOffer = false;
                            }

                            if (HosProMap.containsKey(Jstage.Prod.Id)) {
                                Jstage.hosPro = true;
                            }
                            MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                        }else{
                            //midmap2中没有对应的产品
                            ConsumableorderdetailsInfo Jstage = MidMap.get(CountDel[i].Consumable_Product__c).clone();
                            Jstage.allnumber = Jstage.allnumber+1 ;
                            if(CountDel[i].Box_Piece__c == '盒'){
                                Jstage.Boxnumber = Jstage.Boxnumber + 1;
                            }else if(CountDel[i].Box_Piece__c == '个'){
                                Jstage.Piecenumber = Jstage.Piecenumber + 1;
                            }
                            if (CountDel[i].hospitalSpecialOffer__c) {
                                Jstage.hospitalSpecialOffer = true;
                            }else{
                                Jstage.hospitalSpecialOffer = false;
                            }
                            if (HosProMap.containsKey(Jstage.Prod.Id)) {
                                Jstage.hosPro = true;
                            }
                            //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                            MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                        }
                    }
                }
                //update by rentx 2021-01-29
                consumableorderdetailsSelectRecords = new List<ConsumableorderdetailsInfo>();
                //再把map里的值从新赋给ConsumableorderdetailsRecords
                //update by rentx 2021-01-29 
                // for(ConsumableorderdetailsInfo bss : MidMap.values()){
                for(ConsumableorderdetailsInfo bss : MidMap2.values()){
                //update by rentx 2021-01-29 

                    //if(bss.allnumber > 0){
                    //bss.UnitpriceToagency = bss.orderdetails1.Unitprice_To_agency__c == null  || bss.orderdetails1.Unitprice_To_agency__c == 0 ? '' :bss.orderdetails1.Unitprice_To_agency__c.format();
                    bss.packinglist = Integer.valueOf(bss.Prod.Product2__r.Packing_list_manual__c);
                    bss.approbation_No = bss.Prod.Product2__r.SFDA_Approbation_No__c;
                    bss.expiration_Date = bss.Prod.Product2__r.SFDA_Expiration_Date__c;

                    //update by rentx 2021-2-26 start
                        if (cocMap.containsKey(bss.Prod.Id + 'ishos') && bss.hospitalSpecialOffer == true) {
                            consumableorderdetailsSelectRecords.add(bss);
                        }else if (cocMap.containsKey(bss.Prod.Id + 'nothos') && bss.hospitalSpecialOffer == false) {
                            consumableorderdetailsSelectRecords.add(bss);
                        }
                    //update by rentx 2021-2-26 end
                    // consumableorderdetailsSelectRecords.add(bss);
                    //}
                }
                Integer ishosnum = 0;
                for(ConsumableorderdetailsInfo ass : consumableorderdetailsSelectRecords){
                    for (Consumable_Orderdetails__c cdc1 : consumableorderdetailsSelected) {
                        //update by rentx 2012-3-1 start
                        // if(ass.prod.Id == cdc1.Consumable_Product__c){
                        //     ass.check = true;
                        //     ass.orderdetails1 = cdc1;
                        // }
                        if (ass.Prod.Id == cdc1.Consumable_Product__c && ass.hospitalSpecialOffer == cdc1.isOutPattern__c) {
                            ass.check = true;
                            ass.orderdetails1 = cdc1;
                        }
                        //update by rentx 2012-3-1 end
                    }
                    if (ass.hospitalSpecialOffer == true) {
                        ishosnum = ishosnum + 1;
                    }
                }
                 if (ishosnum > 0) {
                    hasHosPro = true;
                }else{
                    hasHosPro = false;
                }

                //add by rentx
                noOfRecords = consumableorderdetailsSelectRecords.size();
                //add by rentx
                makepagerecords();
                //listCut();
                // 消耗品明细2を取得
                consumableorderdetails2RecordsList = [SELECT Id,
                                                        Name,
                                                        SerialLotNo__c,
                                                        Consumable_Product__r.Name__c,
                                                        TracingCode__c,
                                                        Sterilization_limit__c,
                                                        Consumable_Product__c,
                                                        Consumable_Product__r.Name,
                                                        Consumable_Product__r.Category3__c,
                                                        Consumable_Product__r.Category4__c,
                                                        Consumable_Product__r.Category5__c,
                                                        Return_date__c,
                                                        Invoice_Date__c,
                                                        Box_Piece__c,ProductPacking_list_manual__c,
                                                        //add by rentx start
                                                        hospitalSpecialOffer__c
                                                        //add by rentx end
                                                        FROM Consumable_order_details2__c
                                                        WHERE Consumable_ZS_order__c = :ESetId
                                                        order by Name ];
                for (Integer i = 0; i < consumableorderdetails2RecordsList.size(); i++) {
                    consumableorderdetails2Records.add(new ConsumableorderdetailsInfo(consumableorderdetails2RecordsList[i]));
                }
                //产品明细取得
                consumablearriveproductdetailsSelected = [SELECT Id,Delivery_List_RMB__c,
                                                        Consumable_Product__r.Name__c, Name,
                                                        Consumable_Product__r.SFDA_Status__c,Consumable_Product__r.Category3__c,
                                                        Consumable_Product__r.Category4__c,Consumable_Product__r.Category5__c,
                                                        Consumable_Product__c,Consumable_Product__r.Name, Sterilization_limit__c,
                                                        Consumable_Product__r.Intra_Trade_List_RMB__c,
                                                        Consumable_Product__r.Asset_Model_No__c,Box_Piece__c,
                                                        ProductPacking_list_manual__c,
                                                        //add by rentx start
                                                        hospitalSpecialOffer__c
                                                        //add by rentx end
                                                        FROM Consumable_order_details2__c
                                                        WHERE Consumable_ZS_order__c = :ESetId
                                                        order by Name];
                for (Integer i = 0; i < consumablearriveproductdetailsSelected.size(); i++) {
                    consumableproductdetailsRecords.add(new ConsumableorderdetailsInfo(consumablearriveproductdetailsSelected[i]));
                }
            }
            // 不是到货订单来的时候
            else {
                if(coc.SummonsStatus_c__c == '已提交' || coc.SummonsStatus_c__c == '批准'){
                    system.debug('coc.SummonsStatus_c__c : ' + coc.SummonsStatus_c__c);
                    saveBtnDisabled = true;
                    SorderBtnDisabled = true;
                    EditDelCommitBtnDisabled = false;
                }
                //医院二级经销商分类
                Integer io = 0;
                while( io < Dealerelationship.size()){
                    if(coc.Order_ForDealer__c == Dealerelationship[io].Dealer_subordinate__c){
                        SecondDealer = Dealerelationship[io].Dealer_subordinate__c;
                        coc.Order_ForDealer__c = null;
                        io = io+Dealerelationship.size();
                     }
                     io++;
                }
                Integer ik = 0;
                while( ik < AgencyHospitalLink.size()){
                    if(coc.Order_ForHospital__c == AgencyHospitalLink[ik].Hospital__c){
                        HospitalInfo = AgencyHospitalLink[ik].Hospital__c;
                        HospitalName = AgencyHospitalLink[ik].Hospital__r.Name;
                        coc.Order_ForHospital__c = null;
                        ik = ik+AgencyHospitalLink.size();
                     }
                     ik++;
                }
                // 消耗品明细1を取得
                consumableorderdetailsSelected = [SELECT Id,
                                                        Dealer_Custom_Price__c,
                                                        Delivery_List_RMB__c,
                                                        Consumable_Product__r.Name__c,
                                                        Consumable_Product__r.SFDA_Status__c,
                                                        Name, Consumable_order__c,
                                                        Consumable_Product__c,
                                                        Consumable_Product__r.Name,
                                                        Shipment_Count__c,
                                                        Consumable_Product__r.Intra_Trade_List_RMB__c,
                                                        Consumable_Product__r.Asset_Model_No__c,
                                                        Shipment_amount__c,
                                                        Box_Piece__c,ProductPacking_list_manual__c
                                                        ,Invoiced_Procount__c,
                                                        RrturnPro_count__c,
                                                        //Unitprice_To_agency__c,
                                                        InvoiceProNot_count__c,
                                                        Consumable_Product__r.Category3__c,
                                                        Consumable_Product__r.Category4__c,Consumable_Product__r.Category5__c,
                                                        Consumable_Product__r.Product2__r.SFDA_Approbation_No__c,
                                                        Consumable_Product__r.Product2__r.SFDA_Expiration_Date__c
                                                        ,isOutPattern__c
                                                        FROM Consumable_orderdetails__c
                                                        WHERE Consumable_order__c = :ESetId
                                                        AND Consumable_order__r.Order_Owner_WorkLocal__c =: userWorkLocation
                                                        order by Name ];
                //add by rentx 202-2-26
                Map<String,Consumable_Orderdetails__c> cocMap = new Map<String,Consumable_Orderdetails__c>();

                for (Consumable_Orderdetails__c cdc1 : consumableorderdetailsSelected) {
                    sumPrice += cdc1.Shipment_amount__c;
                    orderzaikuId.add(cdc1.Consumable_Product__c);
                    //add by rentx 2021-2-26
                    String tempId = cdc1.Consumable_product__c;
                    if (cdc1.isOutPattern__c) {
                        cocMap.put(tempId+'ishos', cdc1);
                    }else{
                        cocMap.put(tempId+'nothos', cdc1);
                    }
                    //add by rentx 2021-2-26

                }

                String msoql = makeSoqlorderdet();
                product2Selected = Database.query(msoql);
                size = product2Selected.size();
                initStandardController(msoql);
                for (Integer i = 0; i < product2Selected.size(); i++) {
                    MidMap.put(product2Selected[i].Id, new ConsumableorderdetailsInfo(product2Selected[i]));
                }
                //update by rentx 2021-01-29
                /*for(Integer i = 0 ; i< CountDel.size();i++){
                    //然后循环CountDel去修改map里的allnumber
                    if(MidMap.containsKey(CountDel[i].Consumable_Product__c)){
                        ConsumableorderdetailsInfo Jstage = MidMap.get(CountDel[i].Consumable_Product__c);
                        Jstage.allnumber = Jstage.allnumber+1 ;
                        if(CountDel[i].Box_Piece__c == '盒'){
                            Jstage.Boxnumber = Jstage.Boxnumber + 1;
                        }else if(CountDel[i].Box_Piece__c == '个'){
                            Jstage.Piecenumber = Jstage.Piecenumber + 1;
                        }
                        //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                        MidMap.put(CountDel[i].Consumable_Product__c, Jstage);
                    }

                }
                */
                for (Integer i = 0; i<CountDel.size() ;i++ ) {
                    String str = '';
                    if (CountDel[i].hospitalSpecialOffer__c) {
                        str = 'isHos';
                    }else{
                        str = 'notHos';
                    }
                    //明细2对应的产品存在于MidMap中
                    if (MidMap.containsKey(CountDel[i].Consumable_Product__c)) {
                        //设置map中key的后缀 用于区分医院特价和非医院特价
                        if (MidMap2.containsKey(CountDel[i].Consumable_Product__c + str)) {
                            ConsumableorderdetailsInfo Jstage = MidMap2.get(CountDel[i].Consumable_Product__c+str);
                            Jstage.allnumber = Jstage.allnumber+1 ;
                            if(CountDel[i].Box_Piece__c == '盒'){
                                Jstage.Boxnumber = Jstage.Boxnumber + 1;
                            }else if(CountDel[i].Box_Piece__c == '个'){
                                Jstage.Piecenumber = Jstage.Piecenumber + 1;
                            }
                            if (CountDel[i].hospitalSpecialOffer__c) {
                                Jstage.hospitalSpecialOffer = true;
                            }else{
                                Jstage.hospitalSpecialOffer = false;
                            }
                            if (HosProMap.containsKey(Jstage.Prod.Id)) {
                                Jstage.hosPro = true;
                            }
                            MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                        }else{
                            //midmap2中没有对应的产品
                            ConsumableorderdetailsInfo Jstage = MidMap.get(CountDel[i].Consumable_Product__c).clone();
                            Jstage.allnumber = Jstage.allnumber+1 ;
                            if(CountDel[i].Box_Piece__c == '盒'){
                                Jstage.Boxnumber = Jstage.Boxnumber + 1;
                            }else if(CountDel[i].Box_Piece__c == '个'){
                                Jstage.Piecenumber = Jstage.Piecenumber + 1;
                            }
                            //add by rentx 202-2-26
                            //是医院特价出库产品
                            // if (cocMap.get(CountDel[i].Consumable_Product__c+'ishos') != null ) {

                            //     Jstage.hospitalSpecialOffer = true;
                            //     MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);

                            // }else if (cocMap.get(CountDel[i].Consumable_Product__c+'nothos') != null) {
                            //     Jstage.hospitalSpecialOffer = false;
                            //     MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                            
                            // }
                            //add by rentx 2021-2-26

                            if (CountDel[i].hospitalSpecialOffer__c) {
                                Jstage.hospitalSpecialOffer = true;
                            }else{
                                Jstage.hospitalSpecialOffer = false;
                            }
                            if (HosProMap.containsKey(Jstage.Prod.Id)) {
                                Jstage.hosPro = true;
                            }
                            Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                            MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                        }
                    }
                }



                //再把map里的值从新赋给ConsumableorderdetailsRecords
                //update by rentx 2021-01-29 
                // for(ConsumableorderdetailsInfo bss : MidMap.values()){
                for(ConsumableorderdetailsInfo bss : MidMap2.values()){

                //update by rentx 2021-01-29 

                    //if(bss.allnumber>0){
                        bss.packinglist = Integer.valueOf(bss.Prod.Product2__r.Packing_list_manual__c);
                        bss.approbation_No = bss.Prod.Product2__r.SFDA_Approbation_No__c;
                        bss.expiration_Date = bss.Prod.Product2__r.SFDA_Expiration_Date__c;

                        //update by rentx 2021-2-26 start
                        if (cocMap.containsKey(bss.Prod.Id + 'ishos') && bss.hospitalSpecialOffer == true) {
                            consumableorderdetailsSelectRecords.add(bss);
                        }else if (cocMap.containsKey(bss.Prod.Id + 'nothos') && bss.hospitalSpecialOffer == false) {
                            consumableorderdetailsSelectRecords.add(bss);
                        }
                        // consumableorderdetailsSelectRecords.add(bss);
                    //}
                }
        // return null;
                Integer ishosnum = 0;
                for(ConsumableorderdetailsInfo ass : consumableorderdetailsSelectRecords){
                    ass.sortBy = this.sortOrderAsc;
                    for (Consumable_Orderdetails__c cdc1 : consumableorderdetailsSelected) {
                        //update by rentx 2012-3-1 start
                        // if(ass.prod.Id == cdc1.Consumable_Product__c){
                        //     ass.check = true;
                        //     ass.orderdetails1 = cdc1;
                        // }
                        if (ass.Prod.Id == cdc1.Consumable_Product__c && ass.hospitalSpecialOffer == cdc1.isOutPattern__c) {
                            ass.check = true;
                            ass.orderdetails1 = cdc1;
                        }
                        //update by rentx 2012-3-1 end
                    }

                    if (ass.hospitalSpecialOffer == true) {
                        ishosnum = ishosnum + 1;
                    }
                }

                 if (ishosnum > 0) {
                    hasHosPro = true;
                }else{
                    hasHosPro = false;
                }

                consumableorderdetailsSelectRecords.sort();                    
                //add by rentx
                noOfRecords = consumableorderdetailsSelectRecords.size();
                //add by rentx
                makepagerecords();

                // 消耗品明细2を取得
                consumableorderdetails2RecordsList = [SELECT Id,
                                                        Name,
                                                        SerialLotNo__c,
                                                        Consumable_Product__r.Name__c,
                                                        TracingCode__c,
                                                        Sterilization_limit__c,
                                                        Consumable_Product__c,
                                                        Consumable_Product__r.Name,
                                                        Consumable_Product__r.Category3__c,
                                                        Consumable_Product__r.Category4__c,
                                                        Consumable_Product__r.Category5__c,
                                                        Return_date__c,
                                                        Invoice_Date__c,
                                                        Box_Piece__c,ProductPacking_list_manual__c,
                                                        //add by rentx start
                                                        hospitalSpecialOffer__c
                                                        //add by rentx end

                                                        FROM Consumable_order_details2__c
                                                        WHERE Consumable_ZS_order__c = :ESetId
                                                        order by Name ];
                for (Integer i = 0; i < consumableorderdetails2RecordsList.size(); i++) {
                    consumableorderdetails2Records.add(new ConsumableorderdetailsInfo(consumableorderdetails2RecordsList[i]));
                }
            }
        }
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'test++++++' + SecondDealer));
        if(SecondDealer==null||SecondDealer==''){
            provinceOpts.add(new SelectOption('', '-无-'));
            for(Integer i = 0; i < Dealerelationship.size(); i++){
                provinceOpts.add(new SelectOption(Dealerelationship[i].Dealer_subordinate__c, Dealerelationship[i].Dealer_subordinate__r.Name));
            }
        }else{
            provinceOpts.add(new SelectOption('', '-无-'));
            for(Integer i = 0; i < Dealerelationship.size(); i++){
                if(Dealerelationship[i].Dealer_subordinate__c == SecondDealer){
                    provinceOpts.add(new SelectOption(Dealerelationship[i].Dealer_subordinate__c, Dealerelationship[i].Dealer_subordinate__r.Name));
                }
            }
            for(Integer i = 0; i < Dealerelationship.size(); i++){
                if(Dealerelationship[i].Dealer_subordinate__c != SecondDealer){
                    provinceOpts.add(new SelectOption(Dealerelationship[i].Dealer_subordinate__c, Dealerelationship[i].Dealer_subordinate__r.Name));
                }
            }
        }

        /*if(HospitalInfo==null||HospitalInfo==''){
            orderForHospitalOpts.add(new SelectOption('', '-无-'));
            for(Integer i = 0; i < AgencyHospitalLink.size(); i++){
                orderForHospitalOpts.add(new SelectOption(AgencyHospitalLink[i].Hospital__c, AgencyHospitalLink[i].Hospital__r.Name));
            }
        }else{
            orderForHospitalOpts.add(new SelectOption('', '-无-'));
            for(Integer i = 0; i < AgencyHospitalLink.size(); i++){
                if(AgencyHospitalLink[i].Hospital__c == HospitalInfo){
                    orderForHospitalOpts.add(new SelectOption(AgencyHospitalLink[i].Hospital__c, AgencyHospitalLink[i].Hospital__r.Name));
                }
            }
            for(Integer i = 0; i < AgencyHospitalLink.size(); i++){
                if(AgencyHospitalLink[i].Hospital__c != HospitalInfo){
                    orderForHospitalOpts.add(new SelectOption(AgencyHospitalLink[i].Hospital__c, AgencyHospitalLink[i].Hospital__r.Name));
                }
            }
        }*/
        //listCut();

        Schema.DescribeFieldResult dfr = Product2__c.Intra_Trade_List_RMB__c.getDescribe();
        cansee = dfr.isAccessible();
        Schema.DescribeFieldResult dealerPrice = Consumable_orderdetails__c.Dealer_Custom_Price__c.getDescribe();
        dealerPricesee = dealerPrice.isAccessible();
        // 显示数据条数信息
        //    makeMessage();
        //附件
        attachmentinfo =[SELECT Id, Name,OwnerId FROM Attachment WHERE  parentid =:ESetId  ];
        if(attachmentinfo.size()>0){
            for (Integer i = 0; i < attachmentinfo.size(); i++) {
                attachmentRecoeds.add(new ConsumableorderdetailsInfo(attachmentinfo[i]));
            }
        }
        AggregateResult[] categoryList = [select Count(id), Category3_text__c c3c from Product2__c WHERE Category3_text__c != null group by Category3_text__c];
        
         categoryOptionList = new List<SelectOption>();
         categoryOptionList.add(new SelectOption('', '-无-'));
         for(AggregateResult category3Search : categoryList) {
            String deliverycnt = String.valueOf(category3Search.get('c3c'));
            categoryOptionList.add(new SelectOption(deliverycnt,deliverycnt));
         }

         category4OptionList = new List<SelectOption>();
         category4OptionList.add(new SelectOption('', '-无-'));
         /*for(AggregateResult category4Search : category4List) {
            String deliverycnt4 = String.valueOf(category4Search.get('c4c'));
            category4OptionList.add(new SelectOption(deliverycnt4,deliverycnt4));
         }*/
        
         category5OptionList = new List<SelectOption>();
         category5OptionList.add(new SelectOption('', '-无-'));
         /*for(AggregateResult category5Search : category5List) {
            String deliverycnt5 = String.valueOf(category5Search.get('c5c'));
            category5OptionList.add(new SelectOption(deliverycnt5,deliverycnt5));
         }*/
    }
  public void categoryAllload() {
         AggregateResult[] category4List = [select Count(id), Category4_text__c c4c from Product2__c WHERE Category3_text__c=:category3 AND Category4_text__c != null AND Category5_text__c != null group by Category4_text__c];
         category4OptionList = new List<SelectOption>();
         category4OptionList.add(new SelectOption('', '-无-'));
         for(AggregateResult category4Search : category4List) {
            String deliverycnt4 = String.valueOf(category4Search.get('c4c'));
            category4OptionList.add(new SelectOption(deliverycnt4,deliverycnt4));
         }

           AggregateResult[] category5List = [select Count(id), Category5_text__c c5c from Product2__c WHERE Category3_text__c=:category3 AND Category4_text__c != null AND Category5_text__c != null group by Category5_text__c];
        
         category5OptionList = new List<SelectOption>();
         category5OptionList.add(new SelectOption('', '-无-'));
         for(AggregateResult category5Search : category5List) {
            String deliverycnt5 = String.valueOf(category5Search.get('c5c'));
            category5OptionList.add(new SelectOption(deliverycnt5,deliverycnt5));
         }

    }
    
    public void categoryload() {
         AggregateResult[] category4List = [select Count(id), Category4_text__c c4c from Product2__c WHERE Category3_text__c=:category3 AND Category4_text__c != null AND Category5_text__c != null group by Category4_text__c];
         category4OptionList = new List<SelectOption>();
         category4OptionList.add(new SelectOption('', '-无-'));
         for(AggregateResult category4Search : category4List) {
            String deliverycnt4 = String.valueOf(category4Search.get('c4c'));
            category4OptionList.add(new SelectOption(deliverycnt4,deliverycnt4));
         }

           AggregateResult[] category5List = [select Count(id), Category5_text__c c5c from Product2__c WHERE Category3_text__c=:category3 AND Category4_text__c=:category4 AND Category5_text__c != null group by Category5_text__c];
        
         category5OptionList = new List<SelectOption>();
         category5OptionList.add(new SelectOption('', '-无-'));
         for(AggregateResult category5Search : category5List) {
            String deliverycnt5 = String.valueOf(category5Search.get('c5c'));
            category5OptionList.add(new SelectOption(deliverycnt5,deliverycnt5));
         }

    }
    //开票，保存出库单
    /*public void upchangeorder(){
        Consumable_order__c p = new Consumable_order__c();
        if(coc.ConInvoice_Code__c != null){
            p.ConInvoice_Code__c = coc.ConInvoice_Code__c;
            p.Onchange_order__c = true;
            update p;
        }
    }*/

    //库存排序
    /*public void SortStore(){
        if (this.sortKey == this.preSortKey) {
            // 方向が変わるのみ
            this.sortOrderAsc = !this.sortOrderAsc;
            this.sortOrder[Integer.valueOf(this.sortKey)] = (this.sortOrderAsc == true ? '↑' : '↓');
        } else {
            this.sortOrderAsc = true;
            this.sortOrder[Integer.valueOf(this.preSortKey)] = ' ';
            this.sortOrder[Integer.valueOf(this.sortKey)] = (this.sortOrderAsc == true ? '↑' : '↓');
        }
        this.preSortKey = this.sortKey;
        //取出被选中的部分
        List<ConsumableorderdetailsInfo> ConsumableorderdetailsChecked = new List<ConsumableorderdetailsInfo>();
        List<ConsumableorderdetailsInfo> ConsumableorderdetailsUnChecked = new List<ConsumableorderdetailsInfo>();
        for(ConsumableorderdetailsInfo Checked : consumableorderdetailsSelectRecords){
            if(Checked.Check == true){
                Checked.sortBy = this.sortOrderAsc;
                ConsumableorderdetailsChecked.add(Checked);
            }else{
                Checked.sortBy = this.sortOrderAsc;
                ConsumableorderdetailsUnChecked.add(Checked);
            }
        }
        //已选择的明细
        ConsumableorderdetailsChecked.sort();
        //未选择的明细
        ConsumableorderdetailsUnChecked.sort();

        consumableorderdetailsSelectRecords = new List<ConsumableorderdetailsInfo>();
        for(ConsumableorderdetailsInfo CheckedAdd : ConsumableorderdetailsChecked){
            consumableorderdetailsSelectRecords.add(CheckedAdd);
        }
        for(ConsumableorderdetailsInfo UncheckedAdd : ConsumableorderdetailsUnChecked){
            consumableorderdetailsSelectRecords.add(UncheckedAdd);
        }
        //makeMessage();
        //listCut();
    }*/

    /**
     * 選択済み／未選択製品の置き換え
     */
    /*public PageReference exchangeConsumableProduct() {
        List<ConsumableorderdetailsInfo> tmpChecked = new List<ConsumableorderdetailsInfo>();
        List<ConsumableorderdetailsInfo> tmpUnChecked = new List<ConsumableorderdetailsInfo>();
        for (ConsumableorderdetailsInfo ass : consumableorderdetailsSelectRecords) {
            if (ass.check) {
                tmpChecked.add(ass);
            } else {
                tmpUnChecked.add(ass);
            }
        }
        for (ConsumableorderdetailsInfo ass : consumableorderdetailsunSelectRecords) {
            if (ass.check) {
                tmpChecked.add(ass);
            } else {
                tmpUnChecked.add(ass);
            }
        }
        //选择明细
        consumableorderdetailsSelectRecords = new List<ConsumableorderdetailsInfo>();
        for (ConsumableorderdetailsInfo ass : tmpChecked) {
            consumableorderdetailsSelectRecords.add(ass);
        }
        //未选择明细
        consumableorderdetailsunSelectRecords = new List<ConsumableorderdetailsInfo>();
        consumableorderdetailsunSelectRecords.addAll(tmpUnChecked);
        listCut();
        System.debug('exchangeConsumableProduct end');
        return null;
    } */

    //打印PDF
    public PageReference PraseToPDF(){
        if(coc.SummonsStatus_c__c =='批准'){
            Consumable_order__c P = new Consumable_order__c();
            List<Consumable_order__c> cocinfo = New List<Consumable_order__c>();
            // update start by vivek 2019-7-15 add “NoConfirmedPrice__c” in select 
            cocinfo = [SELECT Id,Name,SummonsStatus_c__c,NoConfirmedPrice__c,Dealer_Info__c,Order_ForHospital__c,SummonsForDirction__c,Billed_Status__c FROM Consumable_order__c WHERE Id =:ESetId];
            // update end by vivek 2019-7-15
                if (cocinfo.size()>0){
                    p = cocinfo[0];
                }
            p.SummonsStatus_c__c = '出库单已打印';
            update p;
        }
        return UnabletoEdit();
    }
    //限制性排序
    public void SortLimited(){
        List<ConsumableorderdetailsInfo> reSet = new List<ConsumableorderdetailsInfo>();
        Map<String,ConsumableorderdetailsInfo> MidMap = new Map<String,ConsumableorderdetailsInfo>();
        //add by rentx 2021-01-29
        Map<String,ConsumableorderdetailsInfo> MidMap2 = new Map<String,ConsumableorderdetailsInfo>();
        //add by rentx 2021-01-29

        List<Consumable_order_details2__c> CountDel = [SELECT Id,
                                                            Bar_Code__c,
                                                            Name,Inventory_date__c,
                                                            Consumable_Product__c,
                                                            Consumable_Product__r.Asset_Model_No__c,
                                                            Recordtypeid,Box_Piece__c,ProductPacking_list_manual__c,
                                                            //add by rentx start
                                                            hospitalSpecialOffer__c
                                                            //add by rentx end
                                                        FROM Consumable_order_details2__c
                                                        WHERE Dealer_Arrive__c = true
                                                        AND Dealer_Shipment__c = false
                                                        AND Dealer_Saled__c = false
                                                        AND Dealer_Returned__c = false
                                                        AND Lose_Flag__c = false
                                                        AND Bar_Code__c !=null
                                                        AND Isoverdue__c = 1
                                                        AND Arrive_Owner_Work_Location__c =: userWorkLocation
                                                        //AND Consumable_order_minor__r.Dealer_Info__c = :accountid
                                                        AND Dealer_Info_text__c = :accountName];
        if (this.sortKey == this.preSortKey) {
            // 方向が変わるのみ
            this.sortOrderAsc = !this.sortOrderAsc;
            this.sortOrder[Integer.valueOf(this.sortKey)] = (this.sortOrderAsc == true ? '↑' : '↓');
        } else {
            this.sortOrderAsc = true;
            this.sortOrder[Integer.valueOf(this.preSortKey)] = '';
            this.sortOrder[Integer.valueOf(this.sortKey)] = (this.sortOrderAsc == true ? '↑' : '↓');
        }
        this.preSortKey = this.sortKey;
        // 所有产品取得
        if((EsetId==null||ESetId=='')||(EsetId!=null&&ESetId!=''&&statusEdit== 'Redirect'&&SearchDone=='SearchDone')){
            if(!String.isEmpty(arriveorder)){
                //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '00000'));
                //orderzaikuId.clear();
                String strProd = null;
                for (ConsumableorderdetailsInfo ass : pageRecords)  {
                    //orderzaikuId.add(ass.prod.Id);
                    if(strProd==null || strProd.length()==0){
                        strProd = '\'' + String.valueOf(ass.prod.Id) + '\'';
                    }
                    else{
                        strProd += ',\'' + String.valueOf(ass.prod.Id) + '\'';
                    }
                }
                String soql = 'SELECT Id, Name,Name__c,Intra_Trade_List_RMB__c,Asset_Model_No__c,Product2__r.Packing_list_manual__c,SFDA_Status__c,Product2__r.SFDA_Approbation_No__c,Product2__r.SFDA_Expiration_Date__c,Category3__c,Category4__c,Category5__c  FROM Product2__c ';
                //soql += ' WHERE Estimation_Entry_Possibility__c = \'○\'';
                soql += ' WHERE Id IN (' + strProd + ')';
                soql += ' order by ' + this.columus_no[Integer.valueOf(this.sortKey)] + ' ' + (this.sortOrderAsc == true ? 'asc nulls first' : 'desc nulls last');
                List<Product2__c> product2List = Database.query(soql);

                for (Integer i = 0; i < product2List.size(); i++) {
                    MidMap.put(product2List[i].Id, new ConsumableorderdetailsInfo(product2List[i]));
                }
                pageRecords= new List<ConsumableorderdetailsInfo>();

                //update by rentx 2021-01-29
                /*for(Integer i = 0 ; i< CountDel.size();i++){
                    //然后循环CountDel去修改map里的allnumber
                    if(MidMap.containsKey(CountDel[i].Consumable_Product__c)){
                        ConsumableorderdetailsInfo Jstage =  MidMap.get(CountDel[i].Consumable_Product__c);
                        Jstage.allnumber = Jstage.allnumber+1 ;
                        if(CountDel[i].Box_Piece__c == '盒'){
                            Jstage.Boxnumber = Jstage.Boxnumber + 1;
                        }else if(CountDel[i].Box_Piece__c == '个'){
                            Jstage.Piecenumber = Jstage.Piecenumber + 1;
                        }
                        MidMap.put(CountDel[i].Consumable_Product__c, Jstage);
                    }
                }*/
                for (Integer i = 0; i<CountDel.size() ; i++ ) {
                    String str = '';
                    if (CountDel[i].hospitalSpecialOffer__c) {
                        str = 'isHos';
                    }else{
                        str = 'notHos';
                    }
                    //明细2对应的产品存在于MidMap中
                    if (MidMap.containsKey(CountDel[i].Consumable_Product__c)) {
                        //设置map中key的后缀 用于区分医院特价和非医院特价
                        if (MidMap2.containsKey(CountDel[i].Consumable_Product__c + str)) {
                            ConsumableorderdetailsInfo Jstage = MidMap2.get(CountDel[i].Consumable_Product__c+str);
                            Jstage.allnumber = Jstage.allnumber+1 ;
                            if(CountDel[i].Box_Piece__c == '盒'){
                                Jstage.Boxnumber = Jstage.Boxnumber + 1;
                            }else if(CountDel[i].Box_Piece__c == '个'){
                                Jstage.Piecenumber = Jstage.Piecenumber + 1;
                            }
                            if (CountDel[i].hospitalSpecialOffer__c) {
                                Jstage.hospitalSpecialOffer = true;
                            }else{
                                Jstage.hospitalSpecialOffer = false;
                            }
                            if (HosProMap.containsKey(Jstage.Prod.Id)) {
                                Jstage.hosPro = true;
                            }
                            MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                        }else{
                            //midmap2中没有对应的产品
                            ConsumableorderdetailsInfo Jstage = MidMap.get(CountDel[i].Consumable_Product__c).clone();
                            Jstage.allnumber = Jstage.allnumber+1 ;
                            if(CountDel[i].Box_Piece__c == '盒'){
                                Jstage.Boxnumber = Jstage.Boxnumber + 1;
                            }else if(CountDel[i].Box_Piece__c == '个'){
                                Jstage.Piecenumber = Jstage.Piecenumber + 1;
                            }
                            if (CountDel[i].hospitalSpecialOffer__c) {
                                Jstage.hospitalSpecialOffer = true;
                            }else{
                                Jstage.hospitalSpecialOffer = false;
                            }
                            if (HosProMap.containsKey(Jstage.Prod.Id)) {
                                Jstage.hosPro = true;
                            }
                            //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                            MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                        }
                    }
                }
                //update by rentx 2021-01-29
                
                //再把map里的值从新赋给ConsumableorderdetailsRecords 
                //update by rentx 2021-01-29 
                // for(ConsumableorderdetailsInfo bss : MidMap.values()){
                for(ConsumableorderdetailsInfo bss : MidMap2.values()){
                //update by rentx 2021-01-29 

                    //if(selectedIdMap.containsKey(bss.orderdetails1.id)){
                    //    continue;
                    //}else{
                        //if(bss.allnumber > 0){
                    bss.packinglist = Integer.valueOf(bss.Prod.Product2__r.Packing_list_manual__c);
                    bss.approbation_No = bss.Prod.Product2__r.SFDA_Approbation_No__c;
                    bss.expiration_Date = bss.Prod.Product2__r.SFDA_Expiration_Date__c;
                    pageRecords.add(bss);
                        //}
                    //}
                }
                List<Consumable_orderdetails__c> queryList = [SELECT Id,Dealer_Custom_Price__c,Delivery_List_RMB__c,
                                                    Consumable_Product__r.Name__c, Name, Consumable_order__c,
                                                    Consumable_Product__c,Consumable_Product__r.Name,Consumable_Product__r.Category3__c,
                                                    Consumable_Product__r.Category4__c,Consumable_Product__r.Category5__c,
                                                    Shipment_Count__c,Consumable_Product__r.Intra_Trade_List_RMB__c,
                                                    Consumable_Product__r.Asset_Model_No__c,Sum_of_money__c,Box_Piece__c,
                                                    ProductPacking_list_manual__c,Consumable_Product__r.SFDA_Status__c,
                                                    Consumable_count__c,Invoiced_Procount__c,
                                                    RrturnPro_count__c,
                                                    InvoiceProNot_count__c,
                                                    //Unitprice_To_agency__c,
                                                    Consumable_Product__r.Product2__r.SFDA_Approbation_No__c,
                                                    Consumable_Product__r.Product2__r.SFDA_Expiration_Date__c
                                                FROM Consumable_Orderdetails__c
                                                WHERE Consumable_order__c = :consumableorderId
                                                AND Order_Owner_WorkLocal__c = : userWorkLocation
                                                order by Name ];


                /*String SqlOrder = 'SELECT Id,Dealer_Custom_Price__c,Delivery_List_RMB__c,Consumable_Product__r.Name__c, Name, Consumable_order__c,';
                SqlOrder += 'Consumable_Product__c,Consumable_Product__r.Name,Shipment_Count__c,Consumable_Product__r.Intra_Trade_List_RMB__c,';
                SqlOrder += 'Consumable_Product__r.Category3__c,Consumable_Product__r.Category4__c,Consumable_Product__r.Category5__c,Unitprice_To_agency__c,';
                SqlOrder += 'Consumable_Product__r.Asset_Model_No__c,Shipment_amount__c,Box_Piece__c,ProductPacking_list_manual__c,Consumable_Product__r.SFDA_Status__c,';
                SqlOrder += 'Invoiced_Procount__c,RrturnPro_count__c,InvoiceProNot_count__c,Consumable_Product__r.Category5__c ';
                SqlOrder += ' FROM Consumable_orderdetails__c WHERE Consumable_order__c = \''+consumableorderId+'\'';

                List<Consumable_orderdetails__c> queryList = Database.query(SqlOrder); */
                for(ConsumableorderdetailsInfo ass : pageRecords){
                    ass.sortBy = this.sortOrderAsc;
                    for (Consumable_Orderdetails__c cdc1 : queryList) {
                        cdc1.Shipment_Count__c = cdc1.Consumable_count__c;
                        if(ass.prod.Id == cdc1.Consumable_Product__c){
                            ass.check = true;
                            ass.orderdetails1 = cdc1;
                        }
                    }
                }
            }else{
                //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '11111'));
                //当前页消耗品取得
                /*String strProd = null;
                List<Product2__c> product2Selected =  setCon.getRecords();
                for (Integer i = 0; i < product2Selected.size(); i++) {
                    if(strProd==null || strProd.length()==0){
                        strProd = '\'' + String.valueOf(product2Selected[i].Id) + '\'';
                    }
                    else{
                        strProd += ',\'' + String.valueOf(product2Selected[i].Id) + '\'';
                    }
                }*/
                //orderzaikuId.clear();
                String strProd = null;
                for (ConsumableorderdetailsInfo ass : pageRecords)  {
                    //orderzaikuId.add(ass.prod.Id);
                    if(strProd==null || strProd.length()==0){
                        strProd = '\'' + String.valueOf(ass.prod.Id) + '\'';
                    }
                    else{
                        strProd += ',\'' + String.valueOf(ass.prod.Id) + '\'';
                    }
                }
                String soql = 'SELECT Id, Name,Name__c,Intra_Trade_List_RMB__c,Asset_Model_No__c,Product2__r.Packing_list_manual__c,SFDA_Status__c,Product2__r.SFDA_Approbation_No__c,Product2__r.SFDA_Expiration_Date__c,Category3__c,Category4__c,Category5__c  FROM Product2__c ';
                //soql += ' WHERE Estimation_Entry_Possibility__c = \'○\'';
                soql += ' WHERE Id IN (' + strProd + ')';
                soql += ' order by ' + this.columus_no[Integer.valueOf(this.sortKey)] + ' ' + (this.sortOrderAsc == true ? 'asc nulls first' : 'desc nulls last');
                List<Product2__c> queryList = Database.query(soql);
                // 選択済みの明细を取得
                Map<String, String> selectedIdMap = new Map<String, String>();
                for (ConsumableorderdetailsInfo ass : pageRecords)  {
                    if(ass.check == true){
                        selectedIdMap.put(ass.Prod.id,ass.Prod.id);
                        reSet.add(ass);
                    }
                }
                for (Integer i = 0; i < queryList.size(); i++) {
                    if (selectedIdMap.containsKey(queryList[i].Id)) {
                        // 跳过已经选择的消耗品明细
                        continue;
                        } else {
                        // 未选择的消耗品明细
                        MidMap.put(queryList[i].Id, new ConsumableorderdetailsInfo(queryList[i]));
                    }
                }
                pageRecords= new List<ConsumableorderdetailsInfo>();
                pageRecords = reSet;
                //update by rentx 2021-01-29
                /*for(Integer i = 0 ; i< CountDel.size();i++){
                    //然后循环CountDel去修改map里的allnumber
                    if(MidMap.containsKey(CountDel[i].Consumable_Product__c)){
                        ConsumableorderdetailsInfo Jstage =  MidMap.get(CountDel[i].Consumable_Product__c);
                        Jstage.allnumber = Jstage.allnumber+1 ;
                        if(CountDel[i].Box_Piece__c == '盒'){
                            Jstage.Boxnumber = Jstage.Boxnumber + 1;
                        }else if(CountDel[i].Box_Piece__c == '个'){
                            Jstage.Piecenumber = Jstage.Piecenumber + 1;
                        }
                        MidMap.put(CountDel[i].Consumable_Product__c, Jstage);
                    }
                }*/

                for (Integer i = 0; i< CountDel.size() ; i++ ) {
                    String str = '';
                    if (CountDel[i].hospitalSpecialOffer__c) {
                        str = 'isHos';
                    }else{
                        str = 'notHos';
                    }
                    //明细2对应的产品存在于MidMap中
                    if (MidMap.containsKey(CountDel[i].Consumable_Product__c)) {
                        //设置map中key的后缀 用于区分医院特价和非医院特价
                        if (MidMap2.containsKey(CountDel[i].Consumable_Product__c + str)) {
                            ConsumableorderdetailsInfo Jstage = MidMap2.get(CountDel[i].Consumable_Product__c+str);
                            Jstage.allnumber = Jstage.allnumber+1 ;
                            if(CountDel[i].Box_Piece__c == '盒'){
                                Jstage.Boxnumber = Jstage.Boxnumber + 1;
                            }else if(CountDel[i].Box_Piece__c == '个'){
                                Jstage.Piecenumber = Jstage.Piecenumber + 1;
                            }
                            if (CountDel[i].hospitalSpecialOffer__c) {
                                Jstage.hospitalSpecialOffer = true;
                            }else{
                                Jstage.hospitalSpecialOffer = false;
                            }
                            if (HosProMap.containsKey(Jstage.Prod.Id)) {
                                Jstage.hosPro = true;
                            }
                            MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                        }else{
                            //midmap2中没有对应的产品
                            ConsumableorderdetailsInfo Jstage = MidMap.get(CountDel[i].Consumable_Product__c).clone();
                            Jstage.allnumber = Jstage.allnumber+1 ;
                            if(CountDel[i].Box_Piece__c == '盒'){
                                Jstage.Boxnumber = Jstage.Boxnumber + 1;
                            }else if(CountDel[i].Box_Piece__c == '个'){
                                Jstage.Piecenumber = Jstage.Piecenumber + 1;
                            }
                            if (CountDel[i].hospitalSpecialOffer__c) {
                                Jstage.hospitalSpecialOffer = true;
                            }else{
                                Jstage.hospitalSpecialOffer = false;
                            }
                            if (HosProMap.containsKey(Jstage.Prod.Id)) {
                                Jstage.hosPro = true;
                            }
                            //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                            MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                        }
                    }
                }
                //update by rentx 2021-01-29


                //再把map里的值从新赋给ConsumableorderdetailsRecords
                //update by rentx 2021-01-29 
                // for(ConsumableorderdetailsInfo bss : MidMap.values()){
                for(ConsumableorderdetailsInfo bss : MidMap2.values()){
                //update by rentx 2021-01-29 

                    if(selectedIdMap.containsKey(bss.orderdetails1.id)){
                        continue;
                    }else{
                        //if(bss.allnumber > 0){
                        bss.packinglist = Integer.valueOf(bss.Prod.Product2__r.Packing_list_manual__c);
                        bss.approbation_No = bss.Prod.Product2__r.SFDA_Approbation_No__c;
                        bss.expiration_Date = bss.Prod.Product2__r.SFDA_Expiration_Date__c;
                        pageRecords.add(bss);
                        //}
                    }
                }
                //listCut();
            }
        }else if(SearchDone!='SearchDone'){
            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '22222'));
            String strProd = null;
            for (ConsumableorderdetailsInfo ass : pageRecords)  {
                //orderzaikuId.add(ass.prod.Id);
                if(strProd==null || strProd.length()==0){
                    strProd = '\'' + String.valueOf(ass.prod.Id) + '\'';
                }
                else{
                    strProd += ',\'' + String.valueOf(ass.prod.Id) + '\'';
                }
            }
            String SqlOrder = 'SELECT Id,  Name, Consumable_order__c, Consumable_Product__r.Name__c,Invoiced_Procount__c,RrturnPro_count__c,InvoiceProNot_count__c,';
            SqlOrder += 'Consumable_Product__c,Consumable_Product__r.Name,Consumable_Product__r.Category3__c,Consumable_Product__r.Category4__c,Consumable_Product__r.Category5__c,';
            SqlOrder += 'Shipment_Count__c,Consumable_Product__r.Intra_Trade_List_RMB__c,';
            SqlOrder += 'Consumable_Product__r.Asset_Model_No__c,Shipment_amount__c,Dealer_Custom_Price__c,Delivery_List_RMB__c,Box_Piece__c,ProductPacking_list_manual__c,';
            SqlOrder += 'Consumable_Product__r.SFDA_Status__c,Consumable_Product__r.Product2__r.Packing_list_manual__c,Consumable_Product__r.Product2__r.SFDA_Approbation_No__c,';
            SqlOrder += 'Consumable_Product__r.Product2__r.SFDA_Expiration_Date__c ';
            SqlOrder += ' FROM Consumable_orderdetails__c WHERE Consumable_order__c = \''+ESetId+'\'';
            SqlOrder += ' AND Order_Owner_WorkLocal__c = \'' + userWorkLocation + '\'';
            SqlOrder += ' AND Consumable_Product__c IN (' + strProd + ')';
            SqlOrder += ' order by ' + this.columus[Integer.valueOf(this.sortKey)] + ' ' + (this.sortOrderAsc == true ? 'asc nulls first' : 'desc nulls last');
            List<Consumable_orderdetails__c> queryList = Database.query(SqlOrder);
            // 選択済みの明细を取得

            for (Integer i = 0; i < queryList.size(); i++) {
                // 未选择的消耗品明细
                MidMap.put(queryList[i].Consumable_Product__c, new ConsumableorderdetailsInfo(queryList[i]));
            }
            pageRecords = new List<ConsumableorderdetailsInfo>();
            // 显示数据条数信息
            //update by rentx 2021-01-29
            /*for(Integer i = 0 ; i< CountDel.size();i++){
                //然后循环CountDel去修改map里的allnumber
                if(MidMap.containsKey(CountDel[i].Consumable_Product__c)){
                    ConsumableorderdetailsInfo Jstage =  MidMap.get(CountDel[i].Consumable_Product__c);
                    Jstage.allnumber = Jstage.allnumber+1 ;
                    if(CountDel[i].Box_Piece__c == '盒'){
                        Jstage.Boxnumber = Jstage.Boxnumber + 1;
                    }else if(CountDel[i].Box_Piece__c == '个'){
                        Jstage.Piecenumber = Jstage.Piecenumber + 1;
                    }
                    MidMap.put(CountDel[i].Consumable_Product__c, Jstage);
                }
            }*/
            for (Integer i = 0; i<CountDel.size() ; i++ ) {
                String str = '';
                if (CountDel[i].hospitalSpecialOffer__c) {
                    str = 'isHos';
                }else{
                    str = 'notHos';
                }
                //明细2对应的产品存在于MidMap中
                if (MidMap.containsKey(CountDel[i].Consumable_Product__c)) {
                    //设置map中key的后缀 用于区分医院特价和非医院特价
                    if (MidMap2.containsKey(CountDel[i].Consumable_Product__c + str)) {
                        ConsumableorderdetailsInfo Jstage = MidMap2.get(CountDel[i].Consumable_Product__c+str);
                        Jstage.allnumber = Jstage.allnumber+1 ;
                        if(CountDel[i].Box_Piece__c == '盒'){
                            Jstage.Boxnumber = Jstage.Boxnumber + 1;
                        }else if(CountDel[i].Box_Piece__c == '个'){
                            Jstage.Piecenumber = Jstage.Piecenumber + 1;
                        }
                        if (CountDel[i].hospitalSpecialOffer__c) {
                            Jstage.hospitalSpecialOffer = true;
                        }else{
                            Jstage.hospitalSpecialOffer = false;
                        }
                        if (HosProMap.containsKey(Jstage.Prod.Id)) {
                            Jstage.hosPro = true;
                        }
                        MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                    }else{
                        //midmap2中没有对应的产品
                        ConsumableorderdetailsInfo Jstage = MidMap.get(CountDel[i].Consumable_Product__c).clone();
                        Jstage.allnumber = Jstage.allnumber+1 ;
                        if(CountDel[i].Box_Piece__c == '盒'){
                            Jstage.Boxnumber = Jstage.Boxnumber + 1;
                        }else if(CountDel[i].Box_Piece__c == '个'){
                            Jstage.Piecenumber = Jstage.Piecenumber + 1;
                        }
                        if (CountDel[i].hospitalSpecialOffer__c) {
                            Jstage.hospitalSpecialOffer = true;
                        }else{
                            Jstage.hospitalSpecialOffer = false;
                        }
                        if (HosProMap.containsKey(Jstage.Prod.Id)) {
                            Jstage.hosPro = true;
                        }
                        //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                        MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                    }
                }
            }
            //update by rentx 2021-01-29

            //再把map里的值从新赋给ConsumableorderdetailsRecords 
            // for(ConsumableorderdetailsInfo bss : MidMap.values()){
            for(ConsumableorderdetailsInfo bss : MidMap2.values()){
                //if(bss.allnumber > 0){
                bss.packinglist = Integer.valueOf(bss.Prod.Product2__r.Packing_list_manual__c);
                bss.approbation_No = bss.Prod.Product2__r.SFDA_Approbation_No__c;
                bss.expiration_Date = bss.Prod.Product2__r.SFDA_Expiration_Date__c;
                pageRecords.add(bss);
                //}
            }
            //listCut();
        }
    }
    //上传附件
    public PageReference FilesUpload(){
        PageReference ref = new Pagereference('/p/attach/NoteAttach?pid='+ESetid+'&retURL=%2F' + '/summonsCreat?ESetid=' +ESetid);
        ref.setRedirect(true);
        return ref;
    }
    // 检索
    public void searchConsumableorderdetails() {
        SearchDone = 'SearchDone';
        Map<String, String> selectedIdMap = new Map<String, String>();
        List<ConsumableorderdetailsInfo> reSet = new List<ConsumableorderdetailsInfo>();
        Map<String,ConsumableorderdetailsInfo> MidMap = new Map<String,ConsumableorderdetailsInfo>();
        //update by rentx 2021-01-29
        Map<String,ConsumableorderdetailsInfo> MidMap2 = new Map<String,ConsumableorderdetailsInfo>();
        /*List<Consumable_order_details2__c> CountDel = [SELECT Id,
                                                            Bar_Code__c, 
                                                            Name,
                                                            Inventory_date__c,
                                                            Consumable_Product__c,
                                                            Consumable_Product__r.Asset_Model_No__c,
                                                            Recordtypeid,Box_Piece__c,ProductPacking_list_manual__c,
                                                            //add by rentx start
                                                            hospitalSpecialOffer__c
                                                            //add by rentx end
                                                        FROM Consumable_order_details2__c
                                                        WHERE Dealer_Arrive__c = true
                                                        AND Dealer_Shipment__c = false
                                                        AND Dealer_Saled__c = false
                                                        AND Dealer_Returned__c = false
                                                        AND Lose_Flag__c = false
                                                        AND Bar_Code__c !=null
                                                        AND Isoverdue__c = 1
                                                        AND Arrive_Owner_Work_Location__c = : userWorkLocation
                                                        //AND Consumable_order_minor__r.Dealer_Info__c = :accountid
                                                        AND Dealer_Info_text__c = :accountName];*/
        String countdelSoql = 'SELECT Id,Bar_Code__c,Name,Inventory_date__c,Consumable_Product__c,Consumable_Product__r.Asset_Model_No__c,Recordtypeid,Box_Piece__c,ProductPacking_list_manual__c,hospitalSpecialOffer__c FROM Consumable_order_details2__c WHERE  Dealer_Arrive__c = true AND Dealer_Shipment__c = false AND Dealer_Saled__c = false AND Dealer_Returned__c = false AND Lose_Flag__c = false AND Bar_Code__c != null AND Isoverdue__c = 1 AND Arrive_Owner_Work_Location__c =  :userWorkLocation AND Dealer_Info_text__c = :accountName ';
        if (String.isNotBlank(outOutPattern) && outOutPattern.equals('ishos')) {
            countdelSoql += ' AND hospitalSpecialOffer__c = true';
        }else if (String.isNotBlank(outOutPattern) && outOutPattern.equals('nothos')) {
            countdelSoql += ' AND hospitalSpecialOffer__c = false';
        }
        List<Consumable_order_details2__c> CountDel = Database.query(countdelSoql);
        //update by rentx 2021-01-29

        consumableorderdetailsSelectRecords = new List<ConsumableorderdetailsInfo>();
        //consumableorderdetailsSelectRecords = reSet;
        String soql = this.makeSoql(category1,category3,category4,category5);
        size = Integer.valueOf(System.Label.orderdetLimitsize);
        initStandardController(soql);
        product2Selected = Database.query(soql);
        for (Integer i = 0; i < product2Selected.size(); i++) {
            MidMap.put(product2Selected[i].Id, new ConsumableorderdetailsInfo(product2Selected[i]));
        }

        //update by rentx 2021-01-29
        /*for(Integer i = 0 ; i< CountDel.size();i++){
            //然后循环CountDel去修改map里的allnumber
            if(MidMap.containsKey(CountDel[i].Consumable_Product__c)){
                ConsumableorderdetailsInfo Jstage = MidMap.get(CountDel[i].Consumable_Product__c);
                Jstage.allnumber = Jstage.allnumber+1 ;
                if(CountDel[i].Box_Piece__c == '盒'){
                    Jstage.Boxnumber = Jstage.Boxnumber + 1;
                }else if(CountDel[i].Box_Piece__c == '个'){
                    Jstage.Piecenumber = Jstage.Piecenumber + 1;
                }
                //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                MidMap.put(CountDel[i].Consumable_Product__c, Jstage);
            }

        }*/

        for (Integer i = 0; i < CountDel.size() ;i++ ) {
            String str = '';
            if (CountDel[i].hospitalSpecialOffer__c) {
                str = 'isHos';
            }else{
                str = 'notHos';
            }
            //明细2对应的产品存在于MidMap中
            if (MidMap.containsKey(CountDel[i].Consumable_Product__c)) {
                //设置map中key的后缀 用于区分医院特价和非医院特价
                if (MidMap2.containsKey(CountDel[i].Consumable_Product__c + str)) {
                    ConsumableorderdetailsInfo Jstage = MidMap2.get(CountDel[i].Consumable_Product__c+str);
                    Jstage.allnumber = Jstage.allnumber+1 ;
                    if(CountDel[i].Box_Piece__c == '盒'){
                        Jstage.Boxnumber = Jstage.Boxnumber + 1;
                    }else if(CountDel[i].Box_Piece__c == '个'){
                        Jstage.Piecenumber = Jstage.Piecenumber + 1;
                    }
                    if (CountDel[i].hospitalSpecialOffer__c) {
                        Jstage.hospitalSpecialOffer = true;
                    }else{
                        Jstage.hospitalSpecialOffer = false;
                    }
                    if (HosProMap.containsKey(Jstage.Prod.Id)) {
                        Jstage.hosPro = true;
                    }
                    MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                }else{
                    //midmap2中没有对应的产品
                    ConsumableorderdetailsInfo Jstage = MidMap.get(CountDel[i].Consumable_Product__c).clone();
                    Jstage.allnumber = Jstage.allnumber+1 ;
                    if(CountDel[i].Box_Piece__c == '盒'){
                        Jstage.Boxnumber = Jstage.Boxnumber + 1;
                    }else if(CountDel[i].Box_Piece__c == '个'){
                        Jstage.Piecenumber = Jstage.Piecenumber + 1;
                    }
                    if (CountDel[i].hospitalSpecialOffer__c) {
                        Jstage.hospitalSpecialOffer = true;
                    }else{
                        Jstage.hospitalSpecialOffer = false;
                    }
                    if (HosProMap.containsKey(Jstage.Prod.Id)) {
                        Jstage.hosPro = true;
                    }
                    //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                    MidMap2.put(CountDel[i].Consumable_Product__c+str, Jstage);
                }
            }
        }
        //update by rentx 2021-01-29

        //再把map里的值从新赋给ConsumableorderdetailsRecords
        //update by rentx 2021-01-29
        // for(ConsumableorderdetailsInfo bss : MidMap.values()){
        Integer ishosnum = 0;
        for(ConsumableorderdetailsInfo bss : MidMap2.values()){
        //update by rentx 2021-01-29
            if(selectedIdMap.containsKey(bss.Prod.id)){
                continue;
            }else{
                bss.sortBy = false;
                bss.packinglist = Integer.valueOf(bss.Prod.Product2__r.Packing_list_manual__c);
                bss.approbation_No = bss.Prod.Product2__r.SFDA_Approbation_No__c;
                bss.expiration_Date = bss.Prod.Product2__r.SFDA_Expiration_Date__c;
                consumableorderdetailsSelectRecords.add(bss);

                if (bss.hospitalSpecialOffer == true) {
                    ishosnum = ishosnum + 1;
                }
            }
        }
         if (ishosnum > 0) {
            hasHosPro = true;
        }else{
            hasHosPro = false;
        }


        consumableorderdetailsSelectRecords.sort();
        //add by rentx
        noOfRecords = consumableorderdetailsSelectRecords.size();
        //add by rentx
        makepagerecords();
        this.sortKey = '1';
        this.preSortKey = '1';
        this.sortOrderAsc = false;
        this.sortOrder = new String[8];
        this.sortOrder = new String[]{' ',' ',' ',' ','↓','','',''};

        //cate1ForSort = category1;
        // 显示数据条数信息
        //makeMessage();
    }
    // 编辑按钮
    public PageReference seteditAble(){
        statusEdit = 'Redirect';
        PageReference ref = new Pagereference('/apex/summonsCreat?ESetid='+ESetid+'&KeyWords='+statusEdit);
        ref.setRedirect(true);
        return ref;
    }
    //删除按钮
    public PageReference DelConsumable(){
        List<Consumable_order__c> qs = New List<Consumable_order__c>();
        List<Consumable_orderdetails__c> Dqs= New List<Consumable_orderdetails__c>();
        Dqs = [SELECT Id FROM Consumable_orderdetails__c WHERE Consumable_order__c =:ESetId];
        qs  = [SELECT Id FROM Consumable_order__c WHERE Id =:ESetId];
         if (Dqs.size()>0||qs.size()>0){
                delete Dqs;
                delete qs;
            }
        PageReference ref = new Pagereference('/SaleAndDelivery');
        ref.setRedirect(true);
        return ref;
    }
    //出货
    public PageReference GoodsDelivery(){
        if(coc.SummonsForDirction__c =='互相调货'){
            List<Account> accList = [SELECT Id from Account WHERE Name = :coc.Order_ForDealerText__c AND RecordType.DeveloperName = 'Agency'];
            if(accList.size() < 1){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请输入二级经销商全称！'));
                return null;
            }
        }
        if(coc.SummonsStatus_c__c =='批准'){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请先打印指示单！'));
                return null;
        }
        for(ConsumableorderdetailsInfo ass : consumableorderdetailsSelectRecords){
            if(ass.orderdetails1.Shipment_Count__c > ass.allnumber){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '消耗品'+ ass.orderdetails1.Consumable_Product__r.Name__c + '库存不足')); 
                return null;
            }
        }

        PageReference ref = new Pagereference('/apex/SaleOrder?ESetid='+ESetid);
        ref.setRedirect(true);
        return ref;
    }
         // 提交按钮

    public void approval() {
        //判断库存
        for(ConsumableorderdetailsInfo ass : consumableorderdetailsSelectRecords){
            if(ass.orderdetails1.Box_Piece__c == '盒'){
                if(ass.orderdetails1.Shipment_Count__c > ass.Boxnumber){
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '消耗品'+ ass.orderdetails1.Consumable_Product__r.Name__c + '库存不足')); 
                    return;
                }
            }else if(ass.orderdetails1.Box_Piece__c == '个'){
                if(ass.orderdetails1.Shipment_Count__c > ass.Piecenumber){
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '消耗品'+ ass.orderdetails1.Consumable_Product__r.Name__c + '库存不足')); 
                    return;
                }
            }
            
        }

        Consumable_order__c P = new Consumable_order__c();
        List<Consumable_order__c> cocinfo = New List<Consumable_order__c>();
        //update start by vivek 2019-7-15 add “NoConfirmedPrice__c” in select
        cocinfo = [SELECT Id,Name,NoConfirmedPrice__c,SummonsStatus_c__c,Dealer_Info__c,Order_ForHospital__c,SummonsForDirction__c,Billed_Status__c FROM Consumable_order__c WHERE Id =:ESetId];
        // update end by vivek 2019-7-15
            if (cocinfo.size()>0){
                p = cocinfo[0];
            }
        system.debug(p.id);
        p.SummonsStatus_c__c = '出库单已打印';
        p.Order_date__c = date.today();
        update p;
        //update start by vivek 2019-7-15 add “NoConfirmedPrice__c” in select
        coc = [SELECT Id,Name,Summons_Order_type__c,NoConfirmedPrice__c,SummonsStatus_c__c,Order_ForDealerText__c,
                    Dealer_Info__c,Order_ForDealer__c,Order_ForDealer__r.Name,Order_ForDealerTextID__c,
                    Order_ForHospital__c,SummonsForDirction__c,Order_date__c,Arrive_Order__c,
                    Order_status__c,Shipment_total_amount__c,Offers_Price__c,
                    Billed_Status__c,ShipmentAccount__c,Order_Dealer_Info__c,Order_ForCustomerText__c,ConInvoice_Code__c,Onchange_order__c
                FROM Consumable_order__c
                WHERE Id =:ESetId
                AND Order_type__c = '传票'];
        // update end by vivek 2019-7-15
    }

    // 保存按钮
    public PageReference save() {
        //订单信息确认
        if(coc.SummonsForDirction__c  ==''||coc.SummonsForDirction__c  == null){
            coc.SummonsForDirction__c.addError('请输入指示单目的。');
            return null;
        }
        else if(coc.SummonsForDirction__c =='直接销售给医院'){
            if(String.isBlank(HospitalInfo) || String.isBlank(HospitalName)){
                coc.addError('请输入医院。');
                return null;
            }
            if(String.isBlank(coc.Order_ForCustomerText__c)){
                coc.Order_ForCustomerText__c.addError('请输入科室。');
                return null;
            }
            else if(String.isNotBlank(SecondDealer) || String.isNotBlank(coc.Order_ForDealerText__c)){
                coc.addError('不需要二级经销商和经销商(录入)信息。' );
                return null;
            }
        }else if(coc.SummonsForDirction__c =='医院试用'){
            if(String.isBlank(HospitalInfo) || String.isBlank(HospitalName)){
                coc.addError('请输入医院。');
                return null;
            }
            if(String.isBlank(coc.Order_ForCustomerText__c)){
                coc.Order_ForCustomerText__c.addError('请输入科室。');
                return null;
            }
            /*if(SecondDealer == null && coc.Order_ForDealerText__c ==null){
                coc.addError('必须输入二级经销商或经销商(录入)。');
                return null;
            }
            if(SecondDealer != null && coc.Order_ForDealerText__c !=null){
                coc.addError('请输入二级经销商或经销商(录入)。');
                return null;
            }*/
        }
        else if(coc.SummonsForDirction__c =='销售给二级经销商'){
            /*
            if(coc.Order_ForHospital__c!=null){
                coc.Order_ForHospital__c.addError('不需要输入医院。');
                return null;
            }
            if(coc.Order_ForCustomerText__c !=null){
                coc.Order_ForCustomerText__c.addError('不需要输入科室。');
                return null;
            }
            */
            if(String.isBlank(SecondDealer) && String.isBlank(coc.Order_ForDealerText__c)){
                coc.addError('必须输入二级经销商或经销商(录入)。');
                return null;
            }
            if(String.isBlank(HospitalInfo) || String.isBlank(HospitalName)){
                coc.addError('请输入医院。');
                return null;
            }
            if(String.isBlank(coc.Order_ForCustomerText__c)){
                coc.Order_ForCustomerText__c.addError('请输入科室。');
                return null;
            }
        }
        else if(coc.SummonsForDirction__c =='互相调货'){
            if(String.isNotBlank(HospitalInfo) || String.isNotBlank(HospitalName)){
                coc.addError('不需要输入医院。');
                return null;
            }
            if(String.isNotBlank(coc.Order_ForCustomerText__c)){
                coc.Order_ForCustomerText__c.addError('不需要输入科室。');
                return null;
            }
            if(String.isBlank(SecondDealer) && String.isBlank(coc.Order_ForDealerText__c)){
                coc.addError('必须输入二级经销商或经销商(录入)。');
                return null;
            }
        }

        Integer isHos = 0;

        Integer FLG = 0;
        Integer Count = 0;
        for(ConsumableorderdetailsInfo CheckCount : pageRecords) {
            FLG = FLG + 1;
            if(CheckCount.check == false){ 
                Count = Count + 1;
            }else{
                //add by rentx
                if (CheckCount.hospitalSpecialOffer) {
                    isHos = isHos+1;
                }
                //add by rentx
            }
        }
        if(Count == FLG){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请选择所需消耗品'));
            return null;
        }
        // gzw 注释 判断提前 20210308
        checkOutPattern();

        // add by rentx 2021-3-10 start
        //特价医院出库非本医院维护的特价商品时,报错 非特价医院出库维护在医院特价关系表的产品时 报错
        if(coc.SummonsForDirction__c !='互相调货'){
            //非特价医院出库特价产品时 报错(当前经销商下没有特价医院除外)
            List<hospitalprice__c> hopList = [select id,hospital__c,product__c from hospitalprice__c where account__c = :accountid];
            //经销商对应医院下的所有特价产品
            Map<String,String> proMap = new Map<String,String>();
            //经销商下的所有特价产品
            Map<String,String> allProMap = new Map<String,String>();

            if (hopList != null && hopList.size() > 0) {
                Boolean flag = false;
                if (HospitalInfo != null && HospitalInfo != '') {
                    for (hospitalprice__c hp : hopList) {
                        allProMap.put(hp.product__c, '');
                        //如果当前 医院特价关系中的医院对应出库单上出库的医院,则放产品id到map
                        if (hp.hospital__c == HospitalInfo) {
                            flag = true; 
                            proMap.put(hp.product__c, '');
                        }

                    }
                }
                for(ConsumableorderdetailsInfo ass : pageRecords){
                    if (ass.check == true) {
                        //判断选中的医院特价产品
                        if (ass.hospitalSpecialOffer == true) {
                            //用户选中了当前医院下的特价产品
                            if (proMap.containsKey(ass.Prod.Id)) {
                                continue;
                            //用户选中了没有维护特价医院的特价产品
                            }else if (!allProMap.containsKey(ass.Prod.Id)) {
                                continue;
                            }else{
                                //用户选中非当前医院维护的特价产品
                                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '当前医院没有维护 消耗品:'+ ass.Prod.Name__c +' 的特价'));
                                return null;
                            }
                        }//非医院特价产品可以出库给任意医院,所以不需要判断
                    }
                }
            }
        }else{
            //如果是互相调货,判断 经销商(录入) 是否维护了 当前选中的特价产品 
            List<hospitalprice__c> hopList = [select id,hospital__c,product__c from hospitalprice__c where account__c = :coc.Order_ForDealerTextID__c];
            Map<Id,String> proMap = new Map<Id,String>();
            if (hopList != null && hopList.size() > 0) {
                for (hospitalprice__c hpc : hopList) {
                    proMap.put(hpc.product__c, '');
                }

                String proStr = '';
                for(ConsumableorderdetailsInfo ass : pageRecords){
                    if (ass.check == true) {
                        if (ass.hospitalSpecialOffer == true) {
                            if (!proMap.containsKey(ass.Prod.Id)) {
                                proStr += ass.Prod.Name__c+',';
                            }
                        }
                    }
                }
                if (proStr != '') {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '经销商:'+coc.Order_ForDealerText__c +' 没有消耗品:'+proStr.substring(0,proStr.length()-1) + ' 的特价'));
                    return null;
                }
            }
        }
        

        // add by rentx 2021-3-10 end

        //注释 by rentx at2021-3-10
        /*//需要根据 出库医院特价产品,但出库的产品中包含非医院特价产品
        if (coc.OutPattern__c == true) {
            //add by rentx 2020-12-02 start  是  并且该医院维护在医院特价
            if (String.isNotBlank(HospitalInfo) && coc.SummonsForDirction__c !='互相调货') {
                //判断当前医院是否为特价医院
                List<hospitalprice__c> hlist = [select id from hospitalprice__c where account__c = :accountid and hospital__c = :HospitalInfo];
                // List<hospitalprice__c> hlist = [select id from hospitalprice__c where hospital__c = :HospitalInfo];
                if (hlist.size() == 0) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '出库商品到特价医院时,请选择医院特价产品'));
                    return null; 
                }else{
                    if (FLG - Count > isHos && ishos != 0) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '出库商品到特价医院时,请选择医院特价产品'));
                        return null; 
                    }
                }
            }
            
        }
        //add by rentx 2021-2-26 start
        //判断当前经销商下是否有特价医院
        List<hospitalprice__c> hlist = [select id from hospitalprice__c where account__c = :accountid];
        if (hlist == null || hlist.size() == 0) {
        }else {
            //add by rentx 2021-2-26 end
            if (coc.OutPattern__c == false) {
                if (isHos >0 ) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '出库商品到非特价医院时,请选择非医院特价产品'));
                    return null; 
                }
            }
            //add by rentx 2020-12-02 end
        }*/
        // gzw 注释 判断提前 20210308
        // checkOutPattern();
        Consumable_order__c P = new Consumable_order__c();
        List<Consumable_orderdetails__c> Ins = New List<Consumable_orderdetails__c>();
        List<Consumable_order_details2__c> InsProduct = New List<Consumable_order_details2__c>();
        Savepoint sp = Database.setSavepoint();
        try {
            //新建订单时
            if(String.isEmpty(ESetId)){
                p.Name = '*';
                p.Order_type__c = '传票';
                p.Order_ProType__c = agencyProType;
                if(coc.SummonsStatus_c__c ==null||String.isBlank(coc.SummonsStatus_c__c))coc.SummonsStatus_c__c ='草案中'; 
                // update strat by vivek 2019-7-12
                p.NoConfirmedPrice__c = coc.NoConfirmedPrice__c;
                // update end by vivek 2019-7-12
                p.SummonsStatus_c__c = coc.SummonsStatus_c__c;
                if(coc.Arrive_Order__c != null){
                    p.Arrive_Order__c = coc.Arrive_Order__c;
                }
                p.Offers_Price__c = coc.Offers_Price__c;
                p.Dealer_Info__c = accountid;
                if(SecondDealer==null){
                    p.Order_ForHospital__c =String.isNotBlank(HospitalInfo) ? HospitalInfo : null;
                    p.Order_ForCustomerText__c = coc.Order_ForCustomerText__c;
                }else {
                    p.Order_ForHospital__c = String.isNotBlank(HospitalInfo) ? HospitalInfo : null;
                    p.Order_ForCustomerText__c = coc.Order_ForCustomerText__c;
                    p.Order_ForDealer__c = SecondDealer;
                }
                P.Order_ForDealerText__c = coc.Order_ForDealerText__c;
                P.Order_ForDealerTextID__c = coc.Order_ForDealerTextID__c;
                p.Order_date__c = coc.Order_date__c;
                p.SummonsForDirction__c = coc.SummonsForDirction__c;
                p.RecordTypeid = System.Label.RT_ConOrder_Outboundorder;
                // update start by vivek 2019-7-15
                p.NoConfirmedPrice__c = coc.NoConfirmedPrice__c;
                // update end by vivek 2019-7-15
                //add by rentx 
                p.OutPattern__c = coc.OutPattern__c;
                //add by rentx
                //Map<String,String> ProductNewMap = new Map<String, String>();
                for(ConsumableorderdetailsInfo ass : pageRecords){
                    if(ass.check == true){
                        if(ass.orderdetails1.Delivery_List_RMB__c < 0){
                            ass.orderdetails1.Delivery_List_RMB__c.addError('请输入正确的出货单价 (元)。');
                            return null;
                        }
                        //if(ass.orderdetails1.Unitprice_To_agency__c < 0){
                        //    ass.orderdetails1.Delivery_List_RMB__c.addError('请输入正确的二级经销商给客户单价。');
                        //    return null;
                        //}
                        if(ass.orderdetails1.Delivery_List_RMB__c == null && coc.SummonsForDirction__c !='医院试用'){
                            ass.orderdetails1.Delivery_List_RMB__c.addError('请输入出货单价 (元)。');
                            return null;
                        }
                        if(ass.orderdetails1.Delivery_List_RMB__c == 0 && (coc.SummonsForDirction__c =='销售给二级经销商' || coc.SummonsForDirction__c =='直接销售给医院')){
                            ass.orderdetails1.Delivery_List_RMB__c.addError('请输入出货单价 (元)。');
                            return null;
                        }
                        //if(coc.SummonsForDirction__c =='互相调货' || coc.SummonsForDirction__c =='直接销售给医院' || coc.SummonsForDirction__c =='医院试用'){
                        //    if(ass.orderdetails1.Unitprice_To_agency__c != null && ass.orderdetails1.Unitprice_To_agency__c != 0){
                        //        ass.orderdetails1.Unitprice_To_agency__c.addError('不需要输入二级经销商给客户单价。');
                        //        return null;
                        //    }
                        //}
                        //销售给二级经销商 时，可以录入
                        /*else if(coc.SummonsForDirction__c =='销售给二级经销商'){
                            if(ass.orderdetails1.Unitprice_To_agency__c == null || ass.orderdetails1.Unitprice_To_agency__c == 0){
                                ass.orderdetails1.Unitprice_To_agency__c.addError('必须输入二级经销商给客户单价。');
                                return null;
                            }
                        }*/
                        if(ass.orderdetails1.Shipment_Count__c == null ||ass.orderdetails1.Shipment_Count__c ==0){
                            ass.orderdetails1.Shipment_Count__c.addError('请输入出货数量。');
                            return null;
                        }

                        if(ass.orderdetails1.Box_Piece__c == null ||ass.orderdetails1.Box_Piece__c ==''){
                            ass.orderdetails1.Box_Piece__c.addError('请输入单位。');
                            return null;
                        }
                        if(ass.orderdetails1.Box_Piece__c == '盒'){
                            if(ass.orderdetails1.Shipment_Count__c > ass.Boxnumber){
                                //ass.orderdetails1.Shipment_Count__c.addError('库存不足');
                                if(ass.oldCheck == false){
                                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '消耗品'+ ass.Prod.Name__c + '库存不足'));
                                }else{
                                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '消耗品'+ ass.orderdetails1.Consumable_Product__r.Name__c + '库存不足'));
                                }
                                return null;
                            }
                        }else if(ass.orderdetails1.Box_Piece__c == '个'){
                            if(ass.orderdetails1.Shipment_Count__c > ass.Piecenumber){
                                //ass.orderdetails1.Shipment_Count__c.addError('库存不足'); 
                                if(ass.oldCheck == false){
                                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '消耗品'+ ass.Prod.Name__c + '库存不足'));
                                }else{
                                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '消耗品'+ ass.orderdetails1.Consumable_Product__r.Name__c + '库存不足'));
                                }
                                return null;
                            }
                        }
                    }
                }
                insert p;
                ESetId = p.id;
                List<Consumable_order__c> detailName = new List<Consumable_order__c>();
                detailName = [SELECT id,Name FROM Consumable_order__c WHERE id =:ESetId];
                Integer i = 1;
                for (ConsumableorderdetailsInfo ass : pageRecords)  {
                    if(ass.check == true){
                        Consumable_orderdetails__c InsAfterDel = new Consumable_orderdetails__c();
                        String str = string.valueOf(i);
                        if(str.length() == 1){
                            str = '0' + str;
                        }
                        InsAfterDel.Name = detailName[0].name + '-'+ str;
                        InsAfterDel.Shipment_Count__c = ass.orderdetails1.Shipment_Count__c;
                        InsAfterDel.Consumable_order__c = p.id;
                        InsAfterDel.Consumable_Product__c = ass.Prod.id;
                        InsAfterDel.Intra_Trade_List_RMB__c =ass.Prod.Intra_Trade_List_RMB__c;
                        InsAfterDel.Delivery_List_RMB__c = ass.orderdetails1.Delivery_List_RMB__c;
                        // TODO 默认 盒 ，需要修正
                        InsAfterDel.Box_Piece__c = ass.orderdetails1.Box_Piece__c;
                        InsAfterDel.Out_unit__c = ass.orderdetails1.Box_Piece__c;
                        //InsAfterDel.Unitprice_To_agency__c = ass.orderdetails1.Unitprice_To_agency__c;
                        InsAfterDel.Dealer_Custom_Price__c = ass.orderdetails1.Dealer_Custom_Price__c;
                        InsAfterDel.RecordTypeId = System.Label.RT_ConOrderDetail1_Order;
                        //add by rentx 2021-2-26 start
                        InsAfterDel.isOutPattern__c = ass.hospitalSpecialOffer;
                        //add by rentx 2021-2-26 end
                        i++;
                        Ins.add(InsAfterDel);
                    }
                }
                // 如果 出库单 和 OCM发货Header连 的话，发货的Detail2 Copy到 出库单的Detail2里
                if (getExistarrive()) {
                    for (ConsumableorderdetailsInfo ass : consumableproductdetailsRecords)  {
                        //BlockForP;
                        Consumable_order_details2__c InsProductDet = new Consumable_order_details2__c();
                        InsProductDet.Id = ass.orderdetails2.Id;
                        InsProductDet.Consumable_ZS_order__c = p.id;
                        i++;
                        InsProduct.add(InsProductDet);
                    }
                }
                if(Ins.size()>0){
                    insert Ins;
                }
                if(InsProduct.size() >0){
                    ControllerUtil.updateOrderDetailsSatus(InsProduct);
                }
            }
            //修改之后 保存订单
            else if(ESetId != null || ESetId.length() >0 ){
                List<Consumable_order__c> cocinfo = New List<Consumable_order__c>();
                // update start by vivek 2019-7-15 add "NoConfirmedPrice__c" in select
                cocinfo = [SELECT Id,
                                Name,
                                SummonsStatus_c__c,
                                NoConfirmedPrice__c,
                                Dealer_Info__c,
                                Order_ForHospital__c,
                                SummonsForDirction__c
                            FROM Consumable_order__c
                            WHERE Id =:ESetId];
                // update end by vivek 2019-7-15
                if (cocinfo.size()>0){
                    p = cocinfo[0];
                }
                p.Name = coc.Name;
                p.Dealer_Info__c = accountid;
                p.Order_ProType__c = agencyProType;
                if(SecondDealer == null){
                    p.Order_ForHospital__c = String.isNotBlank(HospitalInfo) ? HospitalInfo : null;
                    p.Order_ForCustomerText__c = coc.Order_ForCustomerText__c;
                    p.Order_ForDealer__c = SecondDealer;
                }else {
                    p.Order_ForHospital__c = String.isNotBlank(HospitalInfo) ? HospitalInfo : null;
                    p.Order_ForCustomerText__c = coc.Order_ForCustomerText__c;
                    p.Order_ForDealer__c = SecondDealer;
                }
                P.Order_ForDealerText__c = coc.Order_ForDealerText__c;
                P.Order_ForDealerTextID__c = coc.Order_ForDealerTextID__c;
                p.Order_date__c = coc.Order_date__c;
                p.SummonsForDirction__c = coc.SummonsForDirction__c;
                //add by rentx
                p.OutPattern__c = coc.OutPattern__c;
                // update start by vivek 2019-7-15
                if(p.SummonsStatus_c__c== '价格未定'){
                    p.NoConfirmedPrice__c = false;
                    p.SummonsStatus_c__c= '已完成';
                }else{
                    p.SummonsStatus_c__c = '草案中';
                }
                // p.SummonsStatus_c__c = '草案中';
                // update end by vivek 2019-7-15
                Integer i = 1;
                //Map<String,String> ProductOldMap = new Map<String, String>();
                for (ConsumableorderdetailsInfo ass : pageRecords)  {
                    if(ass.check == true){
                        if(ass.orderdetails1.Delivery_List_RMB__c < 0){
                            ass.orderdetails1.Delivery_List_RMB__c.addError('请输入正确的出货单价 (元)。');
                            return null;
                        }
                        //if(ass.orderdetails1.Unitprice_To_agency__c < 0){
                        //    ass.orderdetails1.Delivery_List_RMB__c.addError('请输入正确的二级经销商给客户单价。');
                        //    return null;
                        //}
                        Consumable_orderdetails__c InsAfterDel = new Consumable_orderdetails__c();
                        if(ass.orderdetails1.Delivery_List_RMB__c == null && coc.SummonsForDirction__c !='医院试用'){
                            ass.orderdetails1.Delivery_List_RMB__c.addError('请输入出货单价 (元)。');
                            return null;
                        }
                        if(ass.orderdetails1.Delivery_List_RMB__c == 0 && (coc.SummonsForDirction__c =='销售给二级经销商' || coc.SummonsForDirction__c =='直接销售给医院')){
                            ass.orderdetails1.Delivery_List_RMB__c.addError('请输入出货单价 (元)。');
                            return null;
                        }
                        //if(coc.SummonsForDirction__c =='互相调货' || coc.SummonsForDirction__c =='直接销售给医院' || coc.SummonsForDirction__c =='医院试用'){
                        //    if(ass.orderdetails1.Unitprice_To_agency__c != null && ass.orderdetails1.Unitprice_To_agency__c != 0){
                        //        ass.orderdetails1.Unitprice_To_agency__c.addError('不需要输入二级经销商给客户单价。');
                        //        return null;
                        //    }
                        //}
                        //销售给二级经销商 时，二级经销商给客户单价可以录入
                        /*else if(coc.SummonsForDirction__c =='销售给二级经销商'){
                            if(ass.orderdetails1.Unitprice_To_agency__c == null || ass.orderdetails1.Unitprice_To_agency__c == 0){
                                ass.orderdetails1.Unitprice_To_agency__c.addError('必须输入二级经销商给客户单价。');
                                return null;
                            }
                        }*/
                        if(ass.orderdetails1.Box_Piece__c == null ||ass.orderdetails1.Box_Piece__c ==''){
                            ass.orderdetails1.Box_Piece__c.addError('请输入单位。');
                            return null;
                        }
                        if(ass.orderdetails1.Box_Piece__c == '盒'){
                            if(ass.orderdetails1.Shipment_Count__c > ass.Boxnumber){
                                //ass.orderdetails1.Shipment_Count__c.addError('库存不足');
                                if(ass.oldCheck == false){
                                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '消耗品'+ ass.Prod.Name__c + '库存不足'));
                                }else{
                                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '消耗品'+ ass.orderdetails1.Consumable_Product__r.Name__c + '库存不足'));
                                }
                                return null;
                            }
                        }else if(ass.orderdetails1.Box_Piece__c == '个'){
                            if(ass.orderdetails1.Shipment_Count__c > ass.Piecenumber){
                                if(ass.oldCheck == false){
                                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '消耗品'+ ass.Prod.Name__c + '库存不足'));
                                }else{
                                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '消耗品'+ ass.orderdetails1.Consumable_Product__r.Name__c + '库存不足'));
                                }
                                return null;
                            }
                        }
                        if(ass.orderdetails1.Shipment_Count__c == null||ass.orderdetails1.Shipment_Count__c==0){
                            ass.orderdetails1.Shipment_Count__c.addError('请输入出货数量。');
                            return null;
                        }else{

                            String str = string.valueOf(i);
                            if(str.length() == 1){
                                str = '0' + str;
                            }
                            InsAfterDel.Name = p.name + '-'+ str;
                            InsAfterDel.Shipment_Count__c = ass.orderdetails1.Shipment_Count__c;
                            InsAfterDel.Consumable_order__c = ESetId;
                            InsAfterDel.Consumable_Product__c = ass.Prod.id;
                            InsAfterDel.Intra_Trade_List_RMB__c =ass.Prod.Intra_Trade_List_RMB__c;
                            InsAfterDel.Delivery_List_RMB__c = ass.orderdetails1.Delivery_List_RMB__c;
                            InsAfterDel.Box_Piece__c = ass.orderdetails1.Box_Piece__c;
                            InsAfterDel.Out_unit__c = ass.orderdetails1.Box_Piece__c;
                            //InsAfterDel.Unitprice_To_agency__c = ass.orderdetails1.Unitprice_To_agency__c;
                            InsAfterDel.Dealer_Custom_Price__c = ass.orderdetails1.Dealer_Custom_Price__c;
                            InsAfterDel.RecordTypeId = System.Label.RT_ConOrderDetail1_Order;
                            //add by rentx 2021-2-26 start
                            InsAfterDel.isOutPattern__c = ass.hospitalSpecialOffer;
                            //add by rentx 2021-2-26 end
                            i++;
                            Ins.add(InsAfterDel);
                        }
                    }
                }
                update p;
                List<Consumable_orderdetails__c> qs = New List<Consumable_orderdetails__c>();
                qs = [SELECT Id FROM Consumable_orderdetails__c WHERE Consumable_order__c =:ESetId];
                if (qs.size()>0){
                    delete qs;
                }
                if(Ins.size()>0){
                    insert Ins;
                }

            }
        }catch (Exception ex) {
            Database.rollback(sp);
            ApexPages.addMessages(ex);
            return null;
        }
        return UnabletoEdit();
    }
    // 返回不可编辑状态
    public PageReference UnabletoEdit(){
        PageReference ref = new Pagereference('/apex/summonsCreat?ESetid='+ESetId);
        ref.setRedirect(true);
        return ref;
    }

    // 做成检索SQL文
    private String makeSoql(String CateName,String Category3,String Category4,String Category5){
        //String sqlTail = '(\'';
        //for(Integer i = 0 ; i< orderzaikuId.size();i++){
        //    if(i<orderzaikuId.size()-1){
        //        sqlTail += orderzaikuId[i]+'\',\'';
        //    }else{
        //        sqlTail += orderzaikuId[i]+'\')';
        //    }
        //}
        String sqlTail1 = '(\'';
        for(Integer i = 0 ; i< zaikuId.size();i++){
            if(i<zaikuId.size()-1){
                sqlTail1 += zaikuId[i]+'\',\'';
            }else{
                sqlTail1 += zaikuId[i];
            }
        }
        sqlTail1 += '\')';
        String soql = 'SELECT Id, Name,Name__c,Intra_Trade_List_RMB__c,Asset_Model_No__c,Product2__r.Packing_list_manual__c,SFDA_Status__c,Product2__r.SFDA_Approbation_No__c,Product2__r.SFDA_Expiration_Date__c,Category3__c,Category4__c,Category5__c  FROM Product2__c ';
        //soql += ' WHERE Estimation_Entry_Possibility__c = \'○\'';
        soql += ' WHERE Id in' + sqlTail1;
       /* if(!String.isBlank(CateCode)){
            soql += ' AND Asset_Model_No__c = \'' +  CateCode + '\'';
        }else*/ if(!String.isBlank(CateName)){
            soql += ' AND (Name__c like \'%' + String.escapeSingleQuotes(CateName.replaceAll('%', '\\%')) + '%\' or Asset_Model_No__c like \'%' + String.escapeSingleQuotes(CateName.replaceAll('%', '\\%')) + '%\')';
        }if(!String.isBlank(Category3)){
            soql += ' AND Category3__c = \'' +  Category3 + '\'';
        }if(!String.isBlank(Category4)){
            soql += ' AND Category4__c = \'' +  Category4 + '\'';
        }if(!String.isBlank(Category5)){
            soql += ' AND Category5__c = \'' +  Category5 + '\'';
        }
        //if(orderzaikuId.size() > 0){
        //    soql += ' AND Id not in' + sqlTail;
        //}
        //if(zaikuId.size() > 0){
            //soql += ' AND Id in' + sqlTail1;
        //}
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'soql ++++++' + soql));
        return soql;
    }

    private String makeSoqlinventory(){
        String sqlTail = '(\'';
        for(Integer i = 0 ; i< zaikuId.size();i++){
            if(i<zaikuId.size()-1){
                sqlTail += zaikuId[i]+'\',\'';
            }else{
                sqlTail += zaikuId[i];
            }
        }
        sqlTail += '\')';
        String msoql = 'SELECT Id, Name,Name__c,Intra_Trade_List_RMB__c,Asset_Model_No__c,Product2__r.Packing_list_manual__c,SFDA_Status__c,Product2__r.SFDA_Approbation_No__c,Product2__r.SFDA_Expiration_Date__c,Category3__c,Category4__c,Category5__c  FROM Product2__c ';
        //msoql += ' WHERE Estimation_Entry_Possibility__c = \'○\'';
        //if(zaikuId.size() > 0){
            msoql += ' WHERE Id in' + sqlTail;
        //}
        return msoql;
    }
    private String makeSoqlorderdet(){
        String sqlTail = '(\'';
        for(Integer i = 0 ; i< orderzaikuId.size();i++){
            if(i<orderzaikuId.size()-1){
                sqlTail += orderzaikuId[i]+'\',\'';
            }else{
                sqlTail += orderzaikuId[i];
            }
        }
        sqlTail += '\')';
        String msoql = 'SELECT Id, Name,Name__c,Intra_Trade_List_RMB__c,Asset_Model_No__c,Product2__r.Packing_list_manual__c,SFDA_Status__c,Product2__r.SFDA_Approbation_No__c,Product2__r.SFDA_Expiration_Date__c,Category3__c,Category4__c,Category5__c  FROM Product2__c ';
        //msoql += ' WHERE Estimation_Entry_Possibility__c = \'○\'';
        //if(orderzaikuId.size() > 0){
            msoql += ' WHERE Id in' + sqlTail;
        //}
        return msoql;
    }
    // 显示数据条数信息
    private void makeMessage() {
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '库存共有' + consumableorderdetailsCount + '可出货件产品'));
    }
    
    // Data Bean
    class ConsumableorderdetailsInfo implements Comparable {
        public Boolean check { get; set; }
        public Boolean oldCheck { get; set; }
        public Consumable_Orderdetails__c orderdetails1 { get; set; }
        public Consumable_order_details2__c orderdetails2 { get; set; }
        public Product2__c Prod { get; set; }
        //盒的个数
        public Decimal Boxnumber { get; set; }
        //个的个数
        public Decimal Piecenumber { get; set; }
        public Decimal allnumber { get; set; }
        public Decimal oldConsumableCount { get; set; }
        public Boolean canSelect { get; set; }
        public Boolean sortBy { get; set; }
        public Integer packinglist { get; set; }
        public String approbation_No { get; set; }
        public Date expiration_Date { get; set; }
        public String boxorpiecein {get;set;}
        public List<SelectOption> boxorpiece  { get; set; }
        public Attachment concc { get; set; }
        public String BoxPiece { get; set; }
        //public String UnitpriceToagency { get; set; }

        //add by rentx 
        public Boolean hospitalSpecialOffer {get;set;}
        public Boolean hosPro {get;set;}
        //add by rentx
        // 消耗品订货明细
        public ConsumableorderdetailsInfo(Consumable_Orderdetails__c e) {
            check = true;
            oldCheck = true;
            orderdetails1 = e;
            orderdetails2 = new Consumable_order_details2__c();
            Prod = e.Consumable_Product__r;
            oldConsumableCount = e.Shipment_Count__c;
            canSelect = true;
            allnumber = 0;
            Boxnumber = 0;
            Piecenumber = 0;
            BoxPiece = e.Box_Piece__c;
            boxorpiece = new List<SelectOption>();
            boxorpiece.add(new SelectOption('盒', '盒'));
            boxorpiece.add(new SelectOption('个', '个'));
            hospitalSpecialOffer = false;
            hosPro =false;
        }

        // 消耗品发货明细
        public ConsumableorderdetailsInfo(Consumable_order_details2__c e) {
            check = true;
            oldCheck = true;
            orderdetails1 = new Consumable_Orderdetails__c();
            orderdetails2 = e;
            Prod = e.Consumable_Product__r;
            canSelect = true;
            allnumber = 0;
            Boxnumber = 0;
            Piecenumber = 0;
            //boxorpiece = new List<SelectOption>();
            //boxorpiece.add(new SelectOption('盒', '盒'));
            //boxorpiece.add(new SelectOption('个', '个'));
            hospitalSpecialOffer = false;
            hosPro = false;
        }
        
        //附件
        public ConsumableorderdetailsInfo(Attachment e) {
            concc = e;
            hospitalSpecialOffer = false;
            hosPro = false;
        }
        public ConsumableorderdetailsInfo(Product2__c e) {
            check = false;
            oldCheck = false;
            orderdetails1 = new Consumable_Orderdetails__c();
            orderdetails2 = new Consumable_order_details2__c();
            Prod = e;
            //oldConsumableCount = null;
            canSelect = true;
            allnumber = 0;
            Boxnumber = 0;
            Piecenumber = 0;
            orderdetails1.Box_Piece__c = '盒';
            boxorpiece = new List<SelectOption>();
            boxorpiece.add(new SelectOption('盒', '盒'));
            boxorpiece.add(new SelectOption('个', '个'));
            hospitalSpecialOffer = false;
            hosPro = false;
        }
        
        // 排序
        public Integer compareTo(Object compareTo) {
            ConsumableorderdetailsInfo compareToorderdetails1 =(ConsumableorderdetailsInfo)compareTo;
            Integer returnValue = 0;
            if(sortBy == false){
                if (Boxnumber > compareToorderdetails1.Boxnumber) {
                    returnValue = -1;
                } else if (Boxnumber < compareToorderdetails1.Boxnumber) {
                    returnValue = 1;
                }
                return returnValue;
            }else{
                if (Boxnumber > compareToorderdetails1.Boxnumber) {
                    returnValue = 1;
                } else if (Boxnumber < compareToorderdetails1.Boxnumber) {
                    returnValue = -1;
                }
                return returnValue;
            }
        }
        
    }
}