public without sharing class ConsumableController {

    /*****************検索用******************/
    public Consumable_order__c coc { get; set; }            // FIMXE Consumable_order__c のインスタンス、sql多すぎ
    public String category1 { get; set; }
    public String category5 { get; set; }
    public String category4 { get; set; }
    public String category3 { get; set; }
    public String category_Goods {get ; set;}
    public Boolean specialCampaign {get ; set;}
    public Boolean cansee{get;set;}
    //经销商合同名称
    public String contractName {get ; set;}
    //经销商合同ID
    public String contractId {get; set;}
    //经销商定价查看权限
    public Boolean dealerPricesee{get;set;}
    /*****************画面初始化用********************************/
    /******20160313_add**************/
    //public String idCheck {get;set;}
    public Boolean editAble {get;set;}
    public Boolean edoffersPrice {get;set;}
    public String statusEdit {get;set;}
    public Boolean returnOrder {get;set;}
    public String searchDone{get;set;}
    //暂用20160323
    public Decimal disCount = 0;
    //总价格计算结果
    public Decimal sumPrice{get;set;}
    //自定义特价金额
    public Decimal bargainPrice{get;set;}
    //产品上下限
    String[] proLimitAndDate =new String[]{};
    /*****************画面表示Bean******************/
    
    private List<ConsumableorderdetailsInfo> consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
    public List<ConsumableorderdetailsInfo> consumableorderdetailsRecordsview { get; set; }
    public Integer ConsumableorderdetailsCount { 
        get {
            return consumableorderdetailsRecords == null ? 0 : consumableorderdetailsRecords.size();
        }
    }
    public Integer ConsumableorderdetailsviewCount { 
        get {
            return consumableorderdetailsRecordsview == null ? 0 : consumableorderdetailsRecordsview.size();
        }
    }
    public List<String> lower = new List<String>();
    //附件
    public List<ConsumableorderdetailsInfo> attachmentRecoeds { get; set; }
    public List<String> DealerProductId { get; set; }
    public Boolean editDelCommitBtnDisabled {get; private set;}
    public Boolean saveBtnDisabled { get; private set; }
    public Boolean sorderBtnDisabled { get; private set; }
    public String decisionCode {get;set;}
    // 保存后动作： 1.检索 2.排序
    public String baseUrl {get;private set;}

    public String sortKey { get; set; }
    public String preSortKey { get; private set; }
    public Boolean sortOrderAsc { get; private set; }
    public String[] sortOrder { get; private set; }
    //public String[] ProidList =new String[]{};
    private List<String> contactDealer  = new List<String>();
    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'};

    // 已选择产品明细
    private List<Attachment> attachmentinfo = new List<Attachment>();
    //private List<Product2__c> Product2Selected = new List<Product2__c>();

    /*****************ソート時再検索条件（画面からの入力条件を無視するため）******************/
    private String cate1ForSort = null;
    private String accountid = null;
    private String accountName = null;
    // 产品 ID
    public String ESetId  { get; set; }
    private String userId = '';
    //private String[] ProidListAll = new String[]{};
    public List<SelectOption> categoryOptionList{get;set;}
    public List<SelectOption> category4OptionList{get;set;}
    public List<SelectOption> category5OptionList{get;set;}
    private Map<Id,Dealer_Product__c> DealerProductMap = new Map<Id,Dealer_Product__c>();
    //private Map<String,Decimal> dealerPDiscountMap = new Map<String,Decimal>();
    List<String> orderzaikuId = new List<String>();

    //分页功能
    //public List<SelectOption> paginationSizeOptions{get;set;}
    public Integer size{get;set;}
    public Integer pageLimit{get;set;}
    public Integer noOfRecords{get; set;}
    public ApexPages.StandardSetController con { get; set; }
    public String soql {get;set;}

    private Boolean OSHFLG;//lt 20230517 安徽两票制 add

    // 登录者工作地
    private String userWorkLocation;
    
    //
    public String agencyProType {get;set;}
    public String agencyProType1 {get;set;}  //lt 20230526 安徽两票制 add

    public String methodType {get;set;}
    public String hospitalName {get;set;}
    public String hospitalId {get;set;}
    public String tempidHp {get; set;}
    public String tempidPp {get; set;}
    private List<String> hpids = new List<String>();
    private Boolean isfirst = false;
    
    public ConsumableController() {
        integer i = 1;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        ESetId = ApexPages.currentPage().getParameters().get('esetId');
        statusEdit = ApexPages.currentPage().getParameters().get('KeyWords');
        consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
        DealerProductId = new List<String>();
        attachmentRecoeds = new List<ConsumableorderdetailsInfo>();
        consumableorderdetailsRecordsview = new List<ConsumableorderdetailsInfo>();
        editAble = false;
        this.edoffersPrice = false;
        returnOrder = false;
        categoryOptionList = new List<SelectOption>();
        category4OptionList = new List<SelectOption>();
        category5OptionList = new List<SelectOption>();

        size = Integer.valueOf(System.Label.orderdetLimitsize);
        pageLimit = Integer.valueOf(System.Label.orderdetPageLimitsize);
    }


    private void initStandardController(){
        con = new ApexPages.StandardSetController(Database.getQueryLocator( soql ) );
 
        con.setPageSize(size);
        noOfRecords = con.getResultSize();
    }

    public List<Product2__c> product2s() {
         return (List<Product2__c>) con.getRecords();
    }

    public PageReference refreshPageSize() {
        con.setPageSize(size);
        //product2Selected = product2s();
        getPageInfo();
        return null;
    }
    

    private List<ConsumableorderdetailsInfo> getPageInfo(){
        List<ConsumableorderdetailsInfo> reSet = new List<ConsumableorderdetailsInfo>();
        Map<String, String> selectedIdMap = new Map<String, String>();

        for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecordsview)  {
            if(ass.check == true){
                selectedIdMap.put(ass.Prod.id,ass.Prod.id);
                reSet.add(ass);
            }
        }

        consumableorderdetailsRecordsview = new List<ConsumableorderdetailsInfo>();
        if (editAble){
            consumableorderdetailsRecordsview = reSet;
        }
        Integer pagestartNo = (con.getPageNumber() * size)-size;
        Integer pageendNo = (con.getPageNumber() * size)>noOfRecords? noOfRecords:(con.getPageNumber() * size-1);
        Integer addNo = 0;
        for(Integer i = pagestartNo; i < consumableorderdetailsRecords.size(); i++){
            
            Consumable_Orderdetails__c orderdetails1 = new Consumable_Orderdetails__c();
            if(selectedIdMap.containsKey(consumableorderdetailsRecords[i].Prod.Id)){
                addNo++;
                //continue;
            }else if(consumableorderdetailsRecordsview.size() >= pageLimit + size){
                break;
            }else{
                if(consumableorderdetailsRecords[i].check == false){
                    consumableorderdetailsRecords[i].esd = orderdetails1;
                }
                //consumableorderdetailsRecords[i].esd.Dealer_Custom_Price__c = consumableorderdetailsRecords[i].Prod.Intra_Trade_List_RMB__c * disCount / 100;
                consumableorderdetailsRecordsview.add(consumableorderdetailsRecords[i]);
                addNo++;
            }
            if(addNo >= size)break;
        }
        return consumableorderdetailsRecordsview;
    }



    // 画面初始化
    public void init() {

        this.methodType =  ApexPages.currentPage().getParameters().get('type');
        this.sortKey = '1';
        this.preSortKey = '1';
        this.sortOrderAsc = false;
        this.sortOrder = new String[8];
        this.sortOrder = new String[]{' ',' ',' ',' ','↓','','',''};
        cate1ForSort = '';

        decisionCode = '';
        sumPrice = 0;
        specialCampaign = false;
        //yuanP = '元';
        //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();
        //userId = '0050l000001dLbc';
        List<user> Useracc = New List<user>();
        //lt 20230517 安徽两票制 add ,OSHFLG__c
        Useracc = [SELECT accountid, Work_Location__c,UserPro_Type__c,OSHFLG__c FROM user WHERE id = :userId ];
        accountid = Useracc[0].accountid;
        userWorkLocation = Useracc[0].Work_Location__c;
        agencyProType = Useracc[0].UserPro_Type__c;
        agencyProType1 = Useracc[0].UserPro_Type__c; //lt 20230526 安徽两票制 add
        
        //lt 20230526 安徽两票制 start
        OSHFLG = Useracc[0].OSHFLG__c; //lt 20230517 安徽两票制 add
        if(OSHFLG){
            agencyProType1 = 'OSH';
        }
        else if(String.isBlank(Useracc[0].UserPro_Type__c)){
            agencyProType1 = 'ET';
        }
        //lt 20230526 安徽两票制 end

        if(String.isBlank(Useracc[0].UserPro_Type__c)){
            agencyProType = 'ET';
        }
        //错误信息提示
        // DB202309406949 gzw start
        // if (String.isNotBlank(methodType) && methodType.equals('hospitalorder') && agencyProType == 'ET') {
        //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '您没有订货医院特价产品的权限!'));
        // }
        // DB202309406949 gzw end
        


        contactDealer = new list<String>();
        Date dateToday = Date.today();
        //查该经销商下所有有效合同
        List<Account> contractList = [select Id,Name,RecordType.DeveloperName
                                        from Account
                                        where RecordType.DeveloperName ='AgencyContract'
                                        and Contract_Decide_Start_Date__c <= :dateToday
                                        and Contract_Decide_End_Date__c >= :dateToday
                                        and Contact_Type__c like :agencyProType1//lt 20230517 安徽两票制 add 1
                                        and Agent_Ref__c =:accountid
                                        and OSH_Dealer__c =: OSHFLG  //lt 20230517 安徽两票制 add
                                    ];

        for(Account contract : contractList){
            contactDealer.add(contract.Id);
        }
        DealerProductMap = new Map<Id,Dealer_Product__c>();
        DealerProductId = this.getDealerProductId();
        Account accountInfo = [SELECT Name,Dealer_discount__c,Product_Limit_Date__c,Product_Limit_DateENG__c FROM account WHERE id =:accountid];
        accountName = accountInfo.Name;
        // contractId = accountInfo.Id;
        String product_Limit;
        if(agencyProType == 'ET'){
            product_Limit = accountInfo.Product_Limit_Date__c;
        }else{
            product_Limit = accountInfo.Product_Limit_DateENG__c;
        }
        
        if(product_Limit != null && product_Limit !=''){
            proLimitAndDate = product_Limit.split(',');
        }
        saveBtnDisabled = false;
        sorderBtnDisabled = false;

        coc = new Consumable_order__c();
        consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
        if(String.isBlank(agencyProType)){
            //return ;
        }
        List<Product2__c> Product2Selected = new List<Product2__c>();
        Map<String,ConsumableorderdetailsInfo> MidMap = 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,
                                                           hospitalSpecialOffer__c,
                                                           promotionorder__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 Cancellation_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(ESetId== NULL || ESetId==''){
            //获取经销商默认的一个合同
            List<Account> contract = [SELECT id,Name,State_Master__c,State_Master__r.Name 
                                        FROM Account 
                                        WHERE ParentId = :accountid 
                                        AND Contact_Type__c like :agencyProType1 //lt 20230517 安徽两票制 add 1
                                        AND Contract_Decide_Start_Date__c <= :Date.Today()
                                        AND Contract_Decide_End_Date__c >= :Date.Today()
                                        AND OSH_Dealer__c =: OSHFLG  //lt 20230517 安徽两票制 add
                                      ];

            if(contract.size() == 1){
                contractName = contract[0].Name;
                contractId = contract[0].Id;
            }

            
            editDelCommitBtnDisabled = true;
            List<String> DealerProductId = new List<String>();
            soql = this.makeSoql('','','','','',false,DealerProductId);
            size = Integer.valueOf(System.Label.orderdetLimitsize);
            initStandardController();
            product2Selected = Database.query(soql);
            
            for (Integer i = 0; i < product2Selected.size(); i++) {
                consumableorderdetailsRecords.add(new ConsumableorderdetailsInfo(product2Selected[i]));
                MidMap.put(product2Selected[i].Id, new ConsumableorderdetailsInfo(product2Selected[i]));
            }
            //只有在协议订货时会走这个for循环 其他两种订货模式都走的searchorderdetails方法
            if (String.isBlank(methodType) || (!methodType.equals('promotionorder') && !methodType.equals('hospitalorder'))) {
                for(Integer i = 0 ; i< countDel.size();i++){
                    if (countDel[i].promotionorder__c == false && countDel[i].hospitalSpecialOffer__c == false) {
                        if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }
                //然后循环CountDel去修改map里的allnumber
                /*if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                    ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                    if (countDel[i].Box_Piece__c == '盒'){
                        Jstage.allnumber = Jstage.allnumber+1 ;
                    }
                    else{
                        Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                    }
                    MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                }*/
            }
            consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
            //经销商定价 计算
            for(ConsumableorderdetailsInfo bss : MidMap.values()){
                bss.sortBy = this.sortOrderAsc;
                bss.packing_list = 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;
                if(DealerProductMap.containsKey(bss.Prod.Id)){
                    bss.SpecialCampaignPrice  = DealerProductMap.get(bss.Prod.Id).Special_Campaign_Price__c;
                    bss.Campaign_EndDate = DealerProductMap.get(bss.Prod.Id).Campaign_EndDate__c;
                    bss.orderGoods_Limit = DealerProductMap.get(bss.Prod.Id).OrderGoods_Limit__c;
                }

                consumableorderdetailsRecords.add(bss);
            }
            consumableorderdetailsRecords.sort();
            if (methodType  != null && methodType != '' &&(methodType.equals('hospitalorder')||methodType.equals('promotionorder'))) {
                searchorderdetails();
                isfirst = true;
            }
            getPageInfo();
            /*移到上面去了
            //获取经销商默认的一个合同
            List<Account> contract = [SELECT id,Name,State_Master__c,State_Master__r.Name 
                                        FROM Account 
                                        WHERE ParentId = :accountid 
                                        AND Contact_Type__c like :agencyProType
                                        AND Contract_Decide_Start_Date__c <= :Date.Today()
                                        AND Contract_Decide_End_Date__c >= :Date.Today()];
            if(contract.size() == 1){
                contractName = contract[0].Name;
            }*/
        }else{

            if (methodType != null && methodType.equals('hospitalorder')) {
                List<Consumable_order__c> oclist = [Select orderPattern__c,Order_ForHospital__c,Order_ForHospital__r.Name from Consumable_order__c where id = :ESetid];

                if (oclist.get(0).orderPattern__c.equals('hospitalorder')) {
                    hospitalName = oclist.get(0).Order_ForHospital__r.Name;
                    hospitalId = oclist.get(0).Order_ForHospital__c;
                }    
            }
            List<Consumable_Orderdetails__c> ConsumableorderdetailsSelected = new List<Consumable_Orderdetails__c>();
            //修改
            List<Consumable_order__c> qs = New List<Consumable_order__c>();
            qs = [SELECT Id,Name,Order_status__c,Consumable_pdf_insert_day__c,
                        Dealer_Info__c,Deliver_date__c,Order_Reason__c,Order_date__c,
                        Contract_application_decision__c,Total_amount__c,Offers_Price__c,Order_effective_contact__c,
                        Order_effective_contact__r.Name
                   FROM Consumable_order__c
                   WHERE Id =:ESetId AND Order_Owner_WorkLocal__c =: userWorkLocation];

            if (qs.size()>0){
                coc = qs[0];
                decisionCode = coc.Contract_application_decision__c;
                contractName = coc.Order_effective_contact__r.Name;
                //bargainPrice = coc.Offers_Price__c;
                contractId = coc.Order_effective_contact__r.Id;
            }
            if(qs[0].Order_status__c == '已提交' || qs[0].Order_status__c == '批准'|| qs[0].Order_status__c == '附件上传完成'){
                saveBtnDisabled = true;
                sorderBtnDisabled = true;
                editDelCommitBtnDisabled = false;
            }
            // 選択済みの明细を取得
            ConsumableorderdetailsSelected = [SELECT Id,  Name, Consumable_order__c,
                        Consumable_Product__r.Name__c, Consumable_Product__c,Consumable_Product__r.Name,
                        Consumable_Count__c,Consumable_Product__r.Category3__c,Consumable_Product__r.Category4__c,Consumable_Product__r.Category5__c,
                        Consumable_Product__r.Intra_Trade_List_RMB__c,Consumable_Product__r.Asset_Model_No__c,
                        Sum_of_money__c,
                        Consumable_Product__r.SFDA_Status__c,
                        Consumable_Product__r.Product2__r.Packing_list_manual__c,
                        Consumable_Product__r.Product2__r.SFDA_Approbation_No__c,
                        Consumable_Product__r.Product2__r.SFDA_Expiration_Date__c
                    FROM Consumable_Orderdetails__c
                    WHERE recordtypeid = :System.Label.RT_ConOrderDetail1_Order
                      AND Consumable_order__c = :ESetId
                      AND Order_Owner_WorkLocal__c =: userWorkLocation
                      AND Consumable_order__r.Dealer_Info__c = :accountid
                    ];

            for (Consumable_Orderdetails__c cdc1 : ConsumableorderdetailsSelected) {
                orderzaikuId.add(cdc1.Consumable_Product__c);
            }
            
            soql = this.makeSoqlorderdet();
            size = orderzaikuId.size();
            initStandardController();
            product2Selected = Database.query(soql);

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

            for(Integer i = 0 ; i< countDel.size();i++){
                //add by rentx 2020-12-09
                if (String.isNotBlank(methodType) && methodType.equals('hospitalorder')) {
                    if (countDel[i].hospitalSpecialOffer__c == true ) {
                        //然后循环CountDel去修改map里的allnumber
                        if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }else if (String.isBlank(methodType) || methodType.equals('promotionorder')) {
                    if (countDel[i].promotionorder__c == true) {
                        if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }else if (String.isBlank(methodType) || (!methodType.equals('promotionorder') && !methodType.equals('hospitalorder'))) {
                    if (countDel[i].promotionorder__c == false && countDel[i].hospitalSpecialOffer__c == false) {
                        if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }
                //add by rentx 2020-12-09
                /*
                //然后循环CountDel去修改map里的allnumber
                if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                    ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                    if(countDel[i].Box_Piece__c == '盒'){
                        Jstage.allnumber = Jstage.allnumber+1 ;
                    }else{
                        Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                    }
                    //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                    MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                }*/

            }
            consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
            //再把map里的值从新赋给ConsumableorderdetailsRecords
            for(ConsumableorderdetailsInfo bss : MidMap.values()){
                //if(bss.allnumber>0){
                    bss.packing_list = 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;
                    if(DealerProductMap.containsKey(bss.Prod.Id)){
                        bss.SpecialCampaignPrice  = DealerProductMap.get(bss.Prod.Id).Special_Campaign_Price__c;
                        bss.Campaign_EndDate = DealerProductMap.get(bss.Prod.Id).Campaign_EndDate__c;
                        bss.orderGoods_Limit = DealerProductMap.get(bss.Prod.Id).OrderGoods_Limit__c;
                    }
                    //if(bss.esd.Dealer_Custom_Price__c == null){
                    //    bss.esd.Dealer_Custom_Price__c = bss.Prod.Intra_Trade_List_RMB__c * disCount / 100;
                    //}
                    //if(bss.esd.Dealer_Custom_Price__c == null){
                    //    bss.esd.Dealer_Custom_Price__c = bss.Prod.Intra_Trade_List_RMB__c * disCount / 100;
                    //}
                    consumableorderdetailsRecords.add(bss);
                //}
            }
            for(ConsumableorderdetailsInfo ass : consumableorderdetailsRecords){
                ass.sortBy = this.sortOrderAsc;
                for (Consumable_Orderdetails__c cdc1 : ConsumableorderdetailsSelected) {
                    sumPrice += cdc1.Sum_of_money__c;
                    if(ass.prod.Id == cdc1.Consumable_Product__c){
                        ass.check = true;
                        ass.esd = cdc1;
                    }
                }
            }
            //consumableorderdetailsRecords.sort();

            //附件
            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]));
                }
            }
            consumableorderdetailsRecords.sort();
            getPageInfo();
        }


        //计算库存上、下限
        productLimtAndDate();
        lowerRecord();
        //明细排序
        List<String> upper = new List<String>();
        if(String.isNotBlank(ESetid)){
            for(ConsumableorderdetailsInfo bss : consumableorderdetailsRecords){
                if(bss.esd.Consumable_count__c + bss.allnumber > bss.upperlimit){
                    upper.add(bss.esd.Consumable_Product__r.Name__c);

                }
            }
        }
        if(upper.size() > 0){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '存在以下产品订货数量超出库存上限!'));
            for(Integer i = 0; i < upper.size(); i++){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, upper[i]));
            }
        }

        if(lower.size() > 0){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '存在以下产品订货数量低于库存下限!'));
            for(Integer i = 0; i < lower.size(); i++){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, lower[i]));
            }
        }
        //consumableorderdetailsRecords.sort();
        
        //ConsumableorderdetailsCount = consumableorderdetailsRecords.size();

        //价格查看权限
        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();
        
        AggregateResult[] categoryList = [select Count(id), Category3_text__c c3c from Product2__c WHERE Estimation_Entry_Possibility__c = '○' AND Product_Type__c like :agencyProType AND 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('', '-无-'));

        category5OptionList = new List<SelectOption>();
        category5OptionList.add(new SelectOption('', '-无-'));

    }
  public void categoryAllload() {
         AggregateResult[] category4List = [select Count(id), Category4_text__c c4c from Product2__c WHERE Estimation_Entry_Possibility__c = '○' AND Product_Type__c like :agencyProType AND 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 Estimation_Entry_Possibility__c = '○' AND Product_Type__c like :agencyProType AND 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 Estimation_Entry_Possibility__c = '○' AND Product_Type__c like :agencyProType AND 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 Estimation_Entry_Possibility__c = '○' AND Product_Type__c like :agencyProType AND 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 lowerRecord() {
        List<ConsumableorderdetailsInfo> lowerRecord = new List<ConsumableorderdetailsInfo>();
        //库存明细取得
        Map<String,ConsumableorderdetailsInfo> midMaprecord = new Map<String,ConsumableorderdetailsInfo>();
        List<Product2__c> product2Selected = [SELECT Id, Name,Name__c,Intra_Trade_List_RMB__c,Asset_Model_No__c
                FROM Product2__c
                WHERE Pro2_Dealer_Object__c = true
                AND Estimation_Entry_Possibility__c = '○' ];
        for (Integer i = 0; i < product2Selected.size(); i++) {
            lowerRecord.add(new ConsumableorderdetailsInfo(product2Selected[i]));
            //先把ConsumableorderdetailsRecords 做成map
            midMaprecord.put(product2Selected[i].Id, new ConsumableorderdetailsInfo(product2Selected[i]));
        }
        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,
                                                            Guarantee_period_for_products__c,
                                                            Isoverdue__c,
                                                            Box_Piece__c,
                                                            hospitalSpecialOffer__c,
                                                            promotionorder__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 Consumable_order_minor__r.Dealer_Info__c = :accountid
                                                        AND  Dealer_Info_text__c = :accountName];
        for(Integer i = 0 ; i< countDel.size();i++){
            //add by rentx 2020-12-09
                if (String.isNotBlank(methodType) && methodType.equals('hospitalorder')) {
                    if (countDel[i].hospitalSpecialOffer__c == true ) {
                        //然后循环CountDel去修改map里的allnumber
                        if(midMaprecord.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage = midMaprecord.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                            midMaprecord.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }else if (String.isBlank(methodType) || methodType.equals('promotionorder')) {
                    if (countDel[i].promotionorder__c == true) {
                        if(midMaprecord.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage =  midMaprecord.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            midMaprecord.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }else if (String.isBlank(methodType) || (!methodType.equals('promotionorder') && !methodType.equals('hospitalorder'))) {
                    if (countDel[i].promotionorder__c == false && countDel[i].hospitalSpecialOffer__c == false) {
                        if(midMaprecord.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage =  midMaprecord.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            midMaprecord.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }
                //add by rentx 2020-12-09
                /*
            //然后循环CountDel去修改map里的allnumber
            if(midMaprecord.containsKey(countDel[i].Consumable_Product__c)){
                ConsumableorderdetailsInfo Jstage =  midMaprecord.get(countDel[i].Consumable_Product__c);
                if (countDel[i].Box_Piece__c == '盒'){
                    Jstage.allnumber = Jstage.allnumber+1 ;
                }
                else{
                    Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                }
                
                midMaprecord.put(countDel[i].Consumable_Product__c, Jstage);
            }*/
        }
        lowerRecord = new List<ConsumableorderdetailsInfo>();
        //再把map里的值从新赋给ConsumableorderdetailsRecords
        for(ConsumableorderdetailsInfo bss : midMaprecord.values()){
            //if(bss.allnumber>0){
            lowerRecord.add(bss);
            //}
        }
        allProductLimt(lowerRecord);
        for(ConsumableorderdetailsInfo bss : lowerRecord){
            if(bss.allnumber < bss.lowerlimit){
                lower.add(bss.Prod.Name__c);
            }
        }
    }

    //库存排序
    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> selectedSort = new List<ConsumableorderdetailsInfo>();
        List<ConsumableorderdetailsInfo> noselectedSort = new List<ConsumableorderdetailsInfo>();
        for(ConsumableorderdetailsInfo ass :consumableorderdetailsRecordsview){
            ass.sortBy = this.sortOrderAsc;
            if(ass.check == true){
                selectedSort.add(ass);
            }else{
                noselectedSort.add(ass);
            }
        }
        consumableorderdetailsRecordsview = new List<ConsumableorderdetailsInfo>();
        if(selectedSort.size() > 0){
            if(searchDone != 'searchDone'){
                selectedSort.sort();
            }
            consumableorderdetailsRecordsview.addAll(selectedSort);
        }
        
        if(noselectedSort.size() > 0){
            noselectedSort.sort();
            consumableorderdetailsRecordsview.addAll(noselectedSort);
        }
        
        //list分割
        //listCut();
    }
    //限制性排序
    public void SortLimited(){        
        List<ConsumableorderdetailsInfo> reSet = new List<ConsumableorderdetailsInfo>();
        Map<String,ConsumableorderdetailsInfo> MidMap = 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,
                                                            hospitalSpecialOffer__c,
                                                            promotionorder__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 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')){

            String strProd = null;
            for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecordsview)  {
                //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 soqll = 'SELECT Id, Name,Name__c,Intra_Trade_List_RMB__c,Asset_Model_No__c,SFDA_Status__c,Product2__r.SFDA_Approbation_No__c,Product2__r.SFDA_Expiration_Date__c,Product2__r.Packing_list_manual__c,Category3__c,Category4__c,Category5__c FROM Product2__c WHERE Estimation_Entry_Possibility__c = \'○\' ';
            //update by rentx 2020-12-31 start
            // soqll += ' AND Pro2_Dealer_Object__c = true AND Intra_Trade_List_RMB__c > 0 ' ;
            if(agencyProType == 'ET'){
                soqll += ' AND Pro2_Dealer_Object__c = true';
            }
            if(agencyProType == 'ENG'){
                soqll += ' AND Pro2_Dealer_ENG__c = true';
            }
            soqll += ' AND Intra_Trade_List_RMB__c > 0 ' ;
            //update by rentx 2020-12-31 end

            soqll += ' AND Id IN (' + strProd + ')';
            soqll += ' order by ' + this.columus_no[Integer.valueOf(this.sortKey)] + ' ' + (this.sortOrderAsc == true ? 'asc nulls first' : 'desc nulls last');
            /*String soql = this.makeSoql(category1,category_Goods,category3,category4,category5,specialCampaign,DealerProductId);
            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(soqll);

            // 選択済みの明细を取得
            Map<String, String> selectedIdMap = new Map<String, String>();
            for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecordsview)  {
                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]));
                }
            }
            consumableorderdetailsRecordsview = new List<ConsumableorderdetailsInfo>();
            consumableorderdetailsRecordsview = reSet;
            for(Integer i = 0 ; i< countDel.size();i++){
                if (String.isNotBlank(methodType) && methodType.equals('hospitalorder')) {
                    if (countDel[i].hospitalSpecialOffer__c == true) {

                        //然后循环CountDel去修改map里的allnumber
                        if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }else if (String.isBlank(methodType) || methodType.equals('promotionorder')) {
                    if (countDel[i].promotionorder__c == true) {
                        if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }else if (String.isBlank(methodType) || (!methodType.equals('promotionorder') && !methodType.equals('hospitalorder'))) {
                    if (countDel[i].promotionorder__c == false && countDel[i].hospitalSpecialOffer__c == false) {
                        if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }
                //然后循环CountDel去修改map里的allnumber
                /*if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                    ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                    if (countDel[i].Box_Piece__c == '盒'){
                        Jstage.allnumber = Jstage.allnumber + 1 ;
                    }
                    else{
                        Jstage.allnumber_piece = Jstage.allnumber_piece + 1 ;
                    }
                    
                    MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                }*/
            }
            
            //把map里的值从新赋给ConsumableorderdetailsRecords
            for(ConsumableorderdetailsInfo bss : MidMap.values()){
                   if(selectedIdMap.containsKey(bss.Prod.Id)){
                    continue;
                }else{
                    if(DealerProductMap.containsKey(bss.Prod.Id)){
                        bss.SpecialCampaignPrice  = DealerProductMap.get(bss.Prod.Id).Special_Campaign_Price__c;
                        bss.Campaign_EndDate = DealerProductMap.get(bss.Prod.Id).Campaign_EndDate__c;
                        bss.orderGoods_Limit = DealerProductMap.get(bss.Prod.Id).OrderGoods_Limit__c;
                    }
                    bss.packing_list = 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;
                    //if(bss.esd.Dealer_Custom_Price__c == null){
                    //    bss.esd.Dealer_Custom_Price__c = bss.Prod.Intra_Trade_List_RMB__c * disCount / 100;
                    //}
                    consumableorderdetailsRecordsview.add(bss);
                }
            }
        }else  if(searchDone!='searchDone'){
            String strProd = null;
            for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecordsview)  {
                //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,';
            SqlOrder += ' Consumable_Product__c,Consumable_Product__r.Name,';
            SqlOrder += 'Consumable_Count__c,Consumable_Product__r.Intra_Trade_List_RMB__c,';
            SqlOrder += 'Consumable_Product__r.Asset_Model_No__c,Sum_of_money__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,Consumable_Product__r.Category3__c,Consumable_Product__r.Category4__c,Consumable_Product__r.Category5__c ';
            SqlOrder += 'FROM Consumable_orderdetails__c WHERE recordtypeid != \'' + System.Label.RT_ConOrderDetail1_Sale +'\' AND  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);
            // 選択済みの明细を取得
            
            Map<String, String> selectedIdMap = new Map<String, String>();
            for (Integer i = 0; i < queryList.size(); i++) {
                // 未选择的消耗品明细
                //reSet.add(new ConsumableorderdetailsInfo(queryList[i]));
                MidMap.put(queryList[i].Consumable_Product__c, new ConsumableorderdetailsInfo(queryList[i]));
            }
            //consumableorderdetailsRecordsview = reSet;
            for(Integer i = 0 ; i< countDel.size();i++){
                if (String.isNotBlank(methodType) && methodType.equals('hospitalorder')) {
                    if (countDel[i].hospitalSpecialOffer__c == true) {

                        //然后循环CountDel去修改map里的allnumber
                        if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }else if (String.isBlank(methodType) || methodType.equals('promotionorder')) {
                    if (countDel[i].promotionorder__c == true) {
                        if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }else if (String.isBlank(methodType) || (!methodType.equals('promotionorder') && !methodType.equals('hospitalorder'))) {
                    if (countDel[i].promotionorder__c == false && countDel[i].hospitalSpecialOffer__c == false) {
                        if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }
                //然后循环CountDel去修改map里的allnumber
                /*if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                    ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                    if (countDel[i].Box_Piece__c == '盒'){
                        Jstage.allnumber = Jstage.allnumber + 1 ;
                    }
                    else{
                        Jstage.allnumber_piece = Jstage.allnumber_piece + 1 ;
                    }
                    
                    MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                }*/
            }
            consumableorderdetailsRecordsview = new List<ConsumableorderdetailsInfo>();
            //把map里的值从新赋给ConsumableorderdetailsRecords
            for(ConsumableorderdetailsInfo bss : MidMap.values()){
                /*if(selectedIdMap.containsKey(bss.Prod.Id)){
                    continue;
                }else{*/
                    if(DealerProductMap.containsKey(bss.Prod.Id)){
                        bss.SpecialCampaignPrice  = DealerProductMap.get(bss.Prod.Id).Special_Campaign_Price__c;
                        bss.Campaign_EndDate = DealerProductMap.get(bss.Prod.Id).Campaign_EndDate__c;
                        bss.orderGoods_Limit = DealerProductMap.get(bss.Prod.Id).OrderGoods_Limit__c;
                    }
                    bss.packing_list = 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;
                    //if(bss.esd.Dealer_Custom_Price__c == null){
                    //    bss.esd.Dealer_Custom_Price__c = bss.Prod.Intra_Trade_List_RMB__c * disCount / 100;
                    //}
                    consumableorderdetailsRecordsview.add(bss);
                //}
            }
        }

        productLimtAndDateView();
        //for (Integer i = 0; i < consumableorderdetailsRecordsview.size(); i++) {
        //    if(consumableorderdetailsRecordsview[i].esd.Dealer_Custom_Price__c == null){
        //        consumableorderdetailsRecordsview[i].esd.Dealer_Custom_Price__c = consumableorderdetailsRecordsview[i].Prod.Intra_Trade_List_RMB__c * disCount / 100;
        //    }

        //}
        //list分割
        //listCut();
    }

    //库存上下限
    public void productLimtAndDateView (){
        String nowName = null, nowRightAsstModelNo = null;
        Map<String,String> productLimt = new Map<String,String>();
        for(Integer i = 0; i < proLimitAndDate.size(); i++){
            nowName = proLimitAndDate[i];
            if( nowName.indexOf( '|') >= 0) {
                nowRightAsstModelNo = nowName.subString( 0, nowName.indexOf( '|'));
                nowName = nowName.subString( nowName.indexOf( '|')+1);
            }
            productLimt.put(nowRightAsstModelNo, nowName);
        }
        for(ConsumableorderdetailsInfo ass : consumableorderdetailsRecordsview){
            if(productLimt.containsKey(ass.Prod.Asset_Model_No__c)){
                ass.lowerlimit = decimal.valueOf(productLimt.get(ass.Prod.Asset_Model_No__c).subString(0, productLimt.get(ass.Prod.Asset_Model_No__c).indexOf( '|')));
                ass.upperlimit = decimal.valueOf(productLimt.get(ass.Prod.Asset_Model_No__c).subString(productLimt.get(ass.Prod.Asset_Model_No__c).indexOf( '|')+1));
           }
        }
    }

    //库存上下限
    public void productLimtAndDate (){        
        String nowName = null, nowRightAsstModelNo = null;
        Map<String,String> productLimt = new Map<String,String>();
        for(Integer i = 0; i < proLimitAndDate.size(); i++){
            nowName = proLimitAndDate[i];
            if( nowName.indexOf( '|') >= 0) {
                nowRightAsstModelNo = nowName.subString( 0, nowName.indexOf( '|'));
                nowName = nowName.subString( nowName.indexOf( '|')+1);
            }
            productLimt.put(nowRightAsstModelNo, nowName);
        }
        for(ConsumableorderdetailsInfo ass : consumableorderdetailsRecords){
            if(productLimt.containsKey(ass.Prod.Asset_Model_No__c)){
                ass.lowerlimit = decimal.valueOf(productLimt.get(ass.Prod.Asset_Model_No__c).subString(0, productLimt.get(ass.Prod.Asset_Model_No__c).indexOf( '|')));
                ass.upperlimit = decimal.valueOf(productLimt.get(ass.Prod.Asset_Model_No__c).subString(productLimt.get(ass.Prod.Asset_Model_No__c).indexOf( '|')+1));
           }
        }
    }

    //全部库存上下限
    private void allProductLimt (List<ConsumableorderdetailsInfo> lowerRecord) {
        String nowName = null, nowRightAsstModelNo = null;
        Map<String,String> productLimt = new Map<String,String>();
        for(Integer i = 0; i < proLimitAndDate.size(); i++){
            nowName = proLimitAndDate[i];
            if( nowName.indexOf( '|') >= 0) {
                nowRightAsstModelNo = nowName.subString( 0, nowName.indexOf( '|'));
                nowName = nowName.subString( nowName.indexOf( '|')+1);
            }
            productLimt.put(nowRightAsstModelNo, nowName);
        }
        for(ConsumableorderdetailsInfo ass : lowerRecord){
            if(productLimt.containsKey(ass.Prod.Asset_Model_No__c)){
                ass.lowerlimit = decimal.valueOf(productLimt.get(ass.Prod.Asset_Model_No__c).subString(0, productLimt.get(ass.Prod.Asset_Model_No__c).indexOf( '|')));
                ass.upperlimit = decimal.valueOf(productLimt.get(ass.Prod.Asset_Model_No__c).subString(productLimt.get(ass.Prod.Asset_Model_No__c).indexOf( '|')+1));
           }
        }
    }

    // 检索
    public void searchConsumableorderdetails() {
        searchDone = 'searchDone';
        this.sortKey = '1';
        this.preSortKey = '1';
        this.sortOrderAsc = false;
        this.sortOrder = new String[7];
        this.sortOrder = new String[]{' ',' ',' ',' ','↓','','',''};
        Map<String, String> selectedIdMap = new Map<String, String>();
        List<ConsumableorderdetailsInfo> derdetailsRecords = new List<ConsumableorderdetailsInfo>();
        Map<String,ConsumableorderdetailsInfo> MidMap = new Map<String,ConsumableorderdetailsInfo>();
        List<ConsumableorderdetailsInfo> reSet = new List<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,
                                                            //add by rentx 2020-12-09
                                                            hospitalSpecialOffer__c,
                                                            promotionorder__c 
                                                            //add by rentx 2020-12-09
                                                        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 Arrive_Owner_Work_Location__c = :userWorkLocation
                                                        //AND Consumable_order_minor__r.Dealer_Info__c = :accountid
                                                        AND  Dealer_Info_text__c = :accountName];

        List<Product2__c> product2Selected = new List<Product2__c>();
        consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();
        //consumableorderdetailsRecords = reSet;
        soql = this.makeSoql(category1,category_Goods,category3,category4,category5,specialCampaign,DealerProductId);
        
        size = Integer.valueOf(System.Label.orderdetLimitsize);
        initStandardController();
        product2Selected = Database.query(soql);

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

        for(Integer i = 0 ; i< countDel.size();i++){
            //然后循环CountDel去修改map里的allnumber
            if (String.isNotBlank(methodType) && methodType.equals('hospitalorder')) {
                if (countDel[i].hospitalSpecialOffer__c == true) {
                    if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                        ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                        if (countDel[i].Box_Piece__c == '盒'){
                            Jstage.allnumber = Jstage.allnumber+1 ;
                        }
                        else{
                            Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                        }
                        //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                        MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                    }
                }
            }else if (String.isBlank(methodType) || methodType.equals('promotionorder')) {
                    if (countDel[i].promotionorder__c == true) {
                        if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }else if (String.isBlank(methodType) || (!methodType.equals('promotionorder') && !methodType.equals('hospitalorder'))) {
                    if (countDel[i].promotionorder__c == false && countDel[i].hospitalSpecialOffer__c == false) {
                        if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                            ConsumableorderdetailsInfo Jstage =  MidMap.get(countDel[i].Consumable_Product__c);
                            if (countDel[i].Box_Piece__c == '盒'){
                                Jstage.allnumber = Jstage.allnumber+1 ;
                            }
                            else{
                                Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                            }
                            MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                        }
                    }
                }
            /*if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                if (countDel[i].Box_Piece__c == '盒'){
                    Jstage.allnumber = Jstage.allnumber+1 ;
                }
                else{
                    Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                }
                //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                MidMap.put(countDel[i].Consumable_Product__c, Jstage);
            }*/
        }

        //再把map里的值从新赋给ConsumableorderdetailsRecordsa0l0l0000000byXAAQ
        for(ConsumableorderdetailsInfo bss : MidMap.values()){

            if(selectedIdMap.containsKey(bss.Prod.id)){
                continue;
            }else{
                if(DealerProductMap.containsKey(bss.Prod.Id)){
                    bss.SpecialCampaignPrice  = DealerProductMap.get(bss.Prod.Id).Special_Campaign_Price__c;
                    bss.Campaign_EndDate = DealerProductMap.get(bss.Prod.Id).Campaign_EndDate__c;
                    bss.orderGoods_Limit = DealerProductMap.get(bss.Prod.Id).OrderGoods_Limit__c;
                }
                bss.sortBy = this.sortOrderAsc;
                bss.packing_list = 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;
                consumableorderdetailsRecords.add(bss);
            }
        }

        //consumableorderdetailsRecords.addAll(derdetailsRecords);
        consumableorderdetailsRecords.sort();
        productLimtAndDate();

        //for (Integer i = 0; i < consumableorderdetailsRecords.size(); i++) {
        //    if(consumableorderdetailsRecords[i].esd.Dealer_Custom_Price__c == null){
        //        consumableorderdetailsRecords[i].esd.Dealer_Custom_Price__c = consumableorderdetailsRecords[i].Prod.Intra_Trade_List_RMB__c * disCount / 100;
        //    }
        //}
        getPageInfo();

        this.sortKey = '1';
        this.preSortKey = '1';
        this.sortOrderAsc = false;
        this.sortOrder = new String[7];
        this.sortOrder = new String[]{'  ','  ','　', '','','','',''};
        cate1ForSort = category1;

        // 显示数据条数信息
        makeMessage();

    }

    //add by rentx 2020-12-03 start =====================================================================================================================
    //医院--检索
    public void searchorderdetails(){

        String soql = 'SELECT Id, Name,Name__c,Intra_Trade_List_RMB__c,Asset_Model_No__c,SFDA_Status__c,Product2__r.SFDA_Approbation_No__c,Product2__r.SFDA_Expiration_Date__c,Product2__r.Packing_list_manual__c,Category3__c,Category4__c,Category5__c FROM Product2__c WHERE Estimation_Entry_Possibility__c = \'○\' ';
        if (methodType.equals('hospitalorder')) {
            //医院id 有值
            // DB202309406949 gzw start
            // List<hospitalprice__c> hplist = [select id,product__c from hospitalprice__c where account__c = :accountid AND hospital__c = :hospitalId];
            List<hospitalprice__c> hplist = [select id,product__c from hospitalprice__c where account__c = :accountid AND hospital__c = :hospitalId and Product_Type_F__c = :agencyProType];
            // DB202309406949 gzw start
            if (hplist != null && hplist.size() > 0) {
                List<String> hpids = new List<String>();
                for (hospitalprice__c hc : hplist) {
                    hpids.add(hc.product__c);
                }


                if (hpids != null && hpids.size() > 0) {
                    soql += ' AND Id in : hpids ';
                }
            }else{
                //该医院下没有符合医院特价的产品
                soql += ' AND Id = null ';
            }
        }else if (methodType.equals('promotionorder')) {
            List<Dealer_Product__c> dpclist =[select Id,Dealer_Product2__c from Dealer_Product__c
                                                    where Dealer_Contact__c = :contractId 
                                                    AND (Special_Discount__c <> null
                                                        or Special_Campaign_Price__c <> null)];

            if (dpclist != null && dpclist.size() > 0) {
                String ids = '(';
                for (Dealer_Product__c hc : dpclist) {
                    hpids.add(hc.Dealer_Product2__c);
                    ids += '\''+ hc.Dealer_Product2__c+'\',';
                }
                ids = ids.substring(0,ids.length()-1)+')';
                if (hpids != null && hpids.size() > 0) {
                    // soql += ' AND Id in : hpids ';
                    soql += ' AND Id in '+ids;
                }
            }else{
                //该经销商下没有促销价格的产品
                soql += ' AND Id = null ';
            } 
        }
        
        size = Integer.valueOf(System.Label.orderdetLimitsize);
        initStandardController();
        List<Product2__c> product2Selected = new List<Product2__c>();
        Map<String,ConsumableorderdetailsInfo> MidMap = new Map<String,ConsumableorderdetailsInfo>();
        Map<String, String> selectedIdMap = new Map<String, String>();
        consumableorderdetailsRecords = new List<ConsumableorderdetailsInfo>();

        product2Selected = Database.query(soql);
        for (Integer i = 0; i < product2Selected.size(); i++) {
            MidMap.put(product2Selected[i].Id, new ConsumableorderdetailsInfo(product2Selected[i]));
        }
        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,
                                                            hospitalSpecialOffer__c,
                                                            promotionorder__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 Arrive_Owner_Work_Location__c = :userWorkLocation
                                                        //AND Consumable_order_minor__r.Dealer_Info__c = :accountid
                                                        AND  Dealer_Info_text__c = :accountName];


        for(Integer i = 0 ; i< countDel.size();i++){
            if (methodType.equals('hospitalorder')) {
                if (countDel[i].hospitalSpecialOffer__c == true ) {
                    //然后循环CountDel去修改map里的allnumber
                    if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                        ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                        if (countDel[i].Box_Piece__c == '盒'){
                            Jstage.allnumber = Jstage.allnumber+1 ;
                        }
                        else{
                            Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                        }
                        //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                        MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                    }
                }
            }else if (methodType.equals('promotionorder')) {
                 if (countDel[i].promotionorder__c == true ) {
                    //然后循环CountDel去修改map里的allnumber
                    if(MidMap.containsKey(countDel[i].Consumable_Product__c)){
                        ConsumableorderdetailsInfo Jstage = MidMap.get(countDel[i].Consumable_Product__c);
                        if (countDel[i].Box_Piece__c == '盒'){
                            Jstage.allnumber = Jstage.allnumber+1 ;
                        }
                        else{
                            Jstage.allnumber_piece = Jstage.allnumber_piece+1 ;
                        }
                        //Jstage.BoxPiece = CountDel[i].Box_Piece__c;
                        MidMap.put(countDel[i].Consumable_Product__c, Jstage);
                    }
                }
            }
            
        }

        //再把map里的值从新赋给ConsumableorderdetailsRecordsa0l0l0000000byXAAQ
        for(ConsumableorderdetailsInfo bss : MidMap.values()){

            if(selectedIdMap.containsKey(bss.Prod.id)){
                continue;
            }else{
                if(DealerProductMap.containsKey(bss.Prod.Id)){
                    bss.SpecialCampaignPrice  = DealerProductMap.get(bss.Prod.Id).Special_Campaign_Price__c;
                    bss.Campaign_EndDate = DealerProductMap.get(bss.Prod.Id).Campaign_EndDate__c;
                    bss.orderGoods_Limit = DealerProductMap.get(bss.Prod.Id).OrderGoods_Limit__c;
                }
                bss.sortBy = this.sortOrderAsc;
                bss.packing_list = 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;
                consumableorderdetailsRecords.add(bss);
            }
        }
        consumableorderdetailsRecords.sort();
        productLimtAndDate();
        getPageInfoForHos();

        this.sortKey = '1';
        this.preSortKey = '1';
        this.sortOrderAsc = false;
        this.sortOrder = new String[7];
        this.sortOrder = new String[]{'  ','  ','　', '','','','',''};
        cate1ForSort = category1;

        // 显示数据条数信息
        noOfRecords = consumableorderdetailsRecords.size();
        if (isfirst) {
            makeMessage();            
        }    
    }
    //用户切换医院时取消选中的产品
    private List<ConsumableorderdetailsInfo> getPageInfoForHos(){
        List<ConsumableorderdetailsInfo> reSet = new List<ConsumableorderdetailsInfo>();
        Map<String, String> selectedIdMap = new Map<String, String>();
        consumableorderdetailsRecordsview = new List<ConsumableorderdetailsInfo>();
        if (editAble){
            consumableorderdetailsRecordsview = reSet;
        }
        Integer pagestartNo = (con.getPageNumber() * size)-size;
        Integer pageendNo = (con.getPageNumber() * size)>noOfRecords? noOfRecords:(con.getPageNumber() * size-1);
        Integer addNo = 0;
        for(Integer i = pagestartNo; i < consumableorderdetailsRecords.size(); i++){
            
            Consumable_Orderdetails__c orderdetails1 = new Consumable_Orderdetails__c();
            if(selectedIdMap.containsKey(consumableorderdetailsRecords[i].Prod.Id)){
                addNo++;
                //continue;
            }else if(consumableorderdetailsRecordsview.size() >= pageLimit + size){
                break;
            }else{
                if(consumableorderdetailsRecords[i].check == false){
                    consumableorderdetailsRecords[i].esd = orderdetails1;
                }
                consumableorderdetailsRecordsview.add(consumableorderdetailsRecords[i]);
                addNo++;
            }
            if(addNo >= size)break;
        }
        return consumableorderdetailsRecordsview;
    }

    //add by rentx 2020-12-03 end =====================================================================================================================

    //特价
    public void OffersPrice(){
        edoffersPrice = true;
    }


    //得到促销产品Id
    private List<String> getDealerProductId(){
        List<String> ProductId = new List<String>();
        Map<String,String> DealerProductIdMap = new Map<String,String>();
        Date dateToday = Date.today();
        List<Dealer_Product__c> DealerProductList = [select Id, 
                                                            Name, 
                                                            Dealer_Product2__c,
                                                            Special_Campaign_Price__c,
                                                            Campaign_StartDate__c,
                                                            Campaign_EndDate__c,
                                                            Dealer_Contact__c,
                                                            OrderGoods_Limit__c
                                                    from Dealer_Product__c
                                                    where Dealer_Contact__c in :contactDealer
                                                    and Campaign_StartDate__c <= :dateToday
                                                    and Campaign_EndDate__c >= :dateToday
                                                    and Special_Campaign_Price__c != null
                                                    ];
        for(Dealer_Product__c dealerProduct : DealerProductList){
            if(DealerProductIdMap.containsKey(dealerProduct.Dealer_Product2__c)){
                continue;
            }else{
                ProductId.add(dealerProduct.Dealer_Product2__c);
                DealerProductIdMap.put(dealerProduct.Dealer_Product2__c, dealerProduct.Dealer_Product2__c);
            }
            
        }
        return ProductId;
    }

    private String makeSoql(String CateName,String CateCode,String Category3,String Category4,String Category5,Boolean specialCampaign,List<String> DealerProductId){
        String soql = 'SELECT Id, Name,Name__c,Intra_Trade_List_RMB__c,Asset_Model_No__c,SFDA_Status__c,Product2__r.SFDA_Approbation_No__c,Product2__r.SFDA_Expiration_Date__c,Product2__r.Packing_list_manual__c,Category3__c,Category4__c,Category5__c FROM Product2__c WHERE Estimation_Entry_Possibility__c = \'○\' ';
        // add begin ================================================================================================
        if(methodType != null && methodType.equals('hospitalorder')){
            //如果是医院特价 
            //1.判断 医院id是否有值 如果有值 则根据医院id去 医院特价表中获取产品id
            //医院id 有值
            if (hospitalId == null || hospitalId == '') {
                soql += ' and id = null ';
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '请选择医院'));
                
            }else{
                // DB202309406949 gzw start
                List<hospitalprice__c> hplist = [select id,product__c from hospitalprice__c where account__c = :accountid AND hospital__c = :hospitalId  and Product_Type_F__c = :agencyProType];
                // DB202309406949 gzw end
                if (hplist != null && hplist.size() > 0) {
                     hpids = new List<String>();
                    for (hospitalprice__c hc : hplist) {
                        hpids.add(hc.product__c);
                    }
                    if (hpids != null && hpids.size() > 0) {
                        soql += ' AND Id in : hpids ';
                    }
                }else{
                    //该医院下没有符合医院特价的产品
                    soql += ' AND Id = null ';
                    return soql;
                }
            }
              
        }
        //促销订货
        if(methodType != null && methodType.equals('promotionorder')){
            if (contractId == null || contractId == '') {
                soql += ' and id = null ';
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '请选择合同'));
            }else{
                //1.查询所有经销商产品
                List<Dealer_Product__c> dpclist =[select Id,Dealer_Product2__c from Dealer_Product__c
                                                        where Dealer_Contact__c = :contractId 
                                                        AND (Special_Discount__c <> null
                                                            or Special_Campaign_Price__c <> null)];

                if (dpclist != null && dpclist.size() > 0) {
                    hpids = new List<String>();
                    for (Dealer_Product__c hc : dpclist) {
                        hpids.add(hc.Dealer_Product2__c);
                    }
                    if (hpids != null && hpids.size() > 0) {
                        soql += ' AND Id in : hpids ';
                    }
                }else{
                    //该经销商下没有促销价格的产品
                    soql += ' AND Id = null ';
                    return soql;
                } 
            }                                          
        }
        //add end ===================================================================================================

        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(specialCampaign){
            // soql += ' AND Id in :DealerProductId';
        // }
        if(agencyProType == 'ET'){
            soql += ' AND Pro2_Dealer_Object__c = true';
        }
        if(agencyProType == 'ENG'){
            soql += ' AND Pro2_Dealer_ENG__c = true';
        }
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'agencyProType ' + agencyProType));
        soql += ' AND Intra_Trade_List_RMB__c > 0 ' ;
        System.debug('soql +++++++++++  ' + soql );
        return soql;
    }

    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]+'\')';
            }
        }
        String soql = 'SELECT Id, Name,Name__c,Intra_Trade_List_RMB__c,Asset_Model_No__c,SFDA_Status__c,Product2__r.SFDA_Approbation_No__c,Product2__r.SFDA_Expiration_Date__c,Product2__r.Packing_list_manual__c,Category3__c,Category4__c,Category5__c FROM Product2__c WHERE Estimation_Entry_Possibility__c = \'○\' ';
        if(orderzaikuId.size() > 0){
            soql += ' AND Id in' + sqlTail;
        }
        return soql;
    }

    // 编辑按钮
    public PageReference setEditAble(){
        statusEdit = 'Redirect';
        List<Consumable_order__c> oclist = [Select orderPattern__c from Consumable_order__c where id = :ESetid];
        // PageReference ref = new Pagereference('/apex/Consumable?ESetid='+ESetid+'&KeyWords='+statusEdit);
        PageReference ref = new Pagereference('/apex/Consumable?ESetid='+ESetid+'&KeyWords='+statusEdit+'&type='+oclist.get(0).orderPattern__c);
        ref.setRedirect(true);
        return ref;
    }

    // 再申请
    public PageReference backOrder(){
        statusEdit = 'Redirect';
        returnOrder = true;
        List<Consumable_order__c> oclist = [Select orderPattern__c from Consumable_order__c where id = :ESetid];
        PageReference ref = new Pagereference('/apex/Consumable?ESetid='+ESetid+'&KeyWords='+statusEdit+'&type='+oclist.get(0).orderPattern__c);
        // PageReference ref = new Pagereference('/apex/Consumable?ESetid='+ESetid+'&KeyWords='+statusEdit);
        ref.setRedirect(true);

        return ref;
    }


    public PageReference FilesUpload(){
        PageReference ref = new Pagereference('/p/attach/NoteAttach?pid='+ESetid+'&retURL=%2F' + '/Consumable?ESetid=' +ESetid);
        ref.setRedirect(true);
        return ref;
    }


    //删除按钮
    public PageReference DelConsumable(){
        Consumable_order__c cord = new Consumable_order__c(Id = ESetId);
        List<Consumable_Orderdetails__c> orderdetails1 = [SELECT Id from Consumable_Orderdetails__c
             WHERE Consumable_order__c = :EsetId];
        try {
            //主従ではない可能性があるので
            delete orderdetails1;
            delete cord;
            return returnOrderPage();
        } catch (Exception e) {
            ApexPages.addMessages(e);
            return null;
        }
    }


    // 返回订货页面
    public PageReference returnOrderPage(){
        PageReference ref = new Pagereference('/ConsumableOrderManage');
        ref.setRedirect(true);
        return ref;
    }
     // 提交按钮
    public PageReference Sorder() {
        Savepoint sp = Database.setSavepoint();
        Map<Id,String> prodMap = new Map<Id,String>();
        Consumable_order__c P = new Consumable_order__c();
        P = new Consumable_order__c(); 
        p.Id=ESetId;
        p.Order_date__c = Date.today();
        p.Order_status__c = '附件上传完成';
        for(Consumable_Orderdetails__c cod1 : [SELECT Consumable_product__r.Product2__c,
                                                      Consumable_product__r.Name__c
                                                FROM Consumable_Orderdetails__c
                                                WHERE Consumable_order__c = :ESetId]){
            prodMap.put(cod1.Consumable_product__r.Product2__c, cod1.Consumable_product__r.Name__c);
        }
        //String strRet = OpportunityWebService.checkProRegisterDecide(prodMap, accountid, '');
        //if(strRet != 'OK'){
        //    coc.addError(strRet);
        //    return null;
        //}
        // GZW 提交产品无效 出错误消息
        System.debug(prodMap);
        Map<String,String> chkMap = OpportunityWebService.MapCheckProRegisterDecide(prodMap, accountid, '');
        System.debug(chkMap);

        if(chkMap.size() > 0){
            if(chkMap.containsKey('agency')){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,  '第一经销商没有有效的医疗器械经营许可证。'));
            }
            for(String proId : prodMap.keySet()){
                if(chkMap.containsKey(proId)){
                    if(chkMap.get(proId) == '1'){
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,  '产品 ' + prodMap.get(proId) + ' 没有有效的注册证。'));
                    }else if(chkMap.get(proId) == '2'){
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,  '产品 ' + prodMap.get(proId) + ' 超过经销商经营范围。'));
                    }
                }
            }
            return null;
        }
        try{

            update p;

        }catch(Exception e){
            ApexPages.addmessages(e);
        }
        try {
            Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
            psr.setObjectId(ESetId);
            Approval.ProcessResult submitResult = Approval.process(psr);
            return  returnOrderPage(); 
        }
        catch (Exception e) {
            Database.rollback(sp);
            return  null; 
        }

    }

    // 打印订单
    public PageReference printConsumable(){
        //PrintConsumblePDF
        PageReference ref = new Pagereference('/PrintConsumblePDF?ESetid='+ESetid);
        return ref;
    }

    // 驳回订单copy
    public PageReference ordrCopy() {
        ESetId = '';
        return save();

    }

    /*
    // 保存按钮
    public PageReference save() {
        Map<String,Decimal> dealerPDiscountMap = new Map<String,Decimal>();
        List<Dealer_Product__c> DealerProductList = [select Id,
                                                            Name,
                                                            Dealer_Product2__c,
                                                            Special_Campaign_Price__c,
                                                            Campaign_StartDate__c,
                                                            Campaign_EndDate__c,
                                                            Dealer_Contact__c,
                                                            Special_Discount__c,
                                                            OrderGoods_Limit__c
                                                    from Dealer_Product__c
                                                    where Dealer_Contact__c in :contactDealer
                                                    AND Special_Discount__c <> null
                                                    ];
        for(Dealer_Product__c dealerProduct: DealerProductList){
            dealerPDiscountMap.put('' + dealerProduct.Dealer_Contact__c + dealerProduct.Dealer_Product2__c,dealerProduct.Special_Discount__c);

        }
        //经销商合同判断
        if(String.isEmpty(contractName)){
            coc.Order_effective_contact__c.addError('请选择合同');
            return null;
        }
        List<Account> contract = [select Id,Name,Contract_Department_Class__c,Contract_Quote_Decide_Flag__c 
                                    from account
                                    WHERE Name = :contractName
                                    AND Contract_Decide_Start_Date__c <= :Date.Today()
                                    AND Contract_Decide_End_Date__c >= :Date.Today()
                                    and Contact_Type__c like :agencyProType
                                    and Agent_Ref__c =:accountid];
        if(contract.size() <= 0){
            coc.Order_effective_contact__c.addError('不存在的合同，请重新确认。');
            return null;
        }else{
            //if(contract[0].Contract_Department_Class__c != 'ET'){
            //    coc.Order_effective_contact__c.addError('合同担当科室分类不是ET，请重新确认。');
            //    return null;
            //}
            if(String.isEmpty(contract[0].Contract_Quote_Decide_Flag__c)){
                coc.Order_effective_contact__c.addError('合同无效，请重新确认。');
                return null;
            }
        }
        //取经销商合同折扣
        List<Account> at = [SELECT id,Name,State_Master__c,State_Master__r.Name,Sales_Section__c,Dealer_discount__c 
                              FROM Account 
                              WHERE Name = :contractName 
                                and Contact_Type__c like :agencyProType
                                AND Contract_Decide_Start_Date__c <= :Date.Today()
                                AND Contract_Decide_End_Date__c >= :Date.Today()];
        if(at.size() > 0 && at[0].Dealer_discount__c != null){
            disCount = at[0].Dealer_discount__c;
        }else{
            disCount = 100;
        }
        Integer FLG = 0;
        Integer Count = 0;
        for(ConsumableorderdetailsInfo CheckCount : consumableorderdetailsRecordsview) {
            FLG = FLG + 1;
            if(CheckCount.check == false){
                Count = Count + 1;
            }
            if(CheckCount.check == true){
                if(CheckCount.esd.Consumable_Count__c == null||CheckCount.esd.Consumable_Count__c==0){
                    //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请输入订货数量'));
                    CheckCount.esd.Consumable_Count__c.addError('请输入采购数量');
                    return null;
                }
                //else if(CheckCount.esd.Dealer_Custom_Price__c == null){
                //    CheckCount.esd.Dealer_Custom_Price__c.addError('请确认产品定价');
                //    return null;
                //}
                if(CheckCount.orderGoods_Limit > 0 && math.mod(Integer.valueOf(CheckCount.esd.Consumable_Count__c),Integer.valueOf(CheckCount.orderGoods_Limit)) > 0){
                    CheckCount.esd.Consumable_Count__c.addError('请输入促销数量的倍数');
                    return null;
                }
            }
        }

        if(Count == FLG){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请选择所需消耗品')); 
            return null;
        }

        Consumable_order__c P = new Consumable_order__c(); 
        List<Consumable_Orderdetails__c> Ins = New List<Consumable_Orderdetails__c>();
        //新建订单时
        Savepoint sp = Database.setSavepoint();
        try{
            if(String.isBlank(ESetId)){
                Integer i = 1;
                
                Integer Roll = 0;
                
                p.Name = '*';
                p.Order_status__c = '草案中';
                p.Dealer_Info__c = accountid;
                p.Order_ProType__c = agencyProType;
                p.Offers_Price__c = coc.Offers_Price__c;
                p.Order_date__c = coc.Order_date__c;
                p.Order_effective_contact__c = contract[0].Id;
                p.Order_Reason__c = coc.Order_Reason__c;
                p.RecordTypeid = System.Label.RT_ConOrder_Order;
                //p.Order_reason_details__c = coc.Order_reason_details__c;
                p.Overrule_order__c = coc.Id;
                try{
                    insert p;
                } catch (Exception e) {
                    ApexPages.addMessages(e);
                }
                List<Consumable_order__c> Consumable_order = [SELECT Name FROM Consumable_order__c WHERE id =:p.id];
                //ESetId = p.id;
                for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecordsview)  {
                    Roll = Roll+1;

                    if(ass.check == true){
                        if(ass.esd.Consumable_Count__c == null||ass.esd.Consumable_Count__c==0){
                            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请输入订货数量'));
                            ass.esd.Consumable_Count__c.addError('请输入采购数量');

                            return null;
                        }
                        else{
                            if(Roll==(FLG-Count)){
                            }
                            Consumable_Orderdetails__c InsAfterDel = new Consumable_Orderdetails__c();
                            String str = string.valueOf(i);
                            if(str.length() == 1){
                            str = '0' + str;
                            }
                            InsAfterDel.Name = Consumable_order[0].Name + '-'+ str;
                            InsAfterDel.Consumable_Count__c = ass.esd.Consumable_Count__c;
                            InsAfterDel.Consumable_order__c = p.id;
                            InsAfterDel.Consumable_Product__c = ass.Prod.id;
                            InsAfterDel.Box_Piece__c = '盒';
                            //InsAfterDel.Sterilization_limit__c = Date.today();
                            if(DealerProductMap.containsKey(ass.Prod.Id)){
                                InsAfterDel.Intra_Trade_List_RMB__c  = DealerProductMap.get(ass.Prod.Id).Special_Campaign_Price__c;
                                InsAfterDel.Purchase_Unitprtprice_From__c = '促销';
                                InsAfterDel.Special_Campaign_Price__c  = DealerProductMap.get(ass.Prod.Id).Special_Campaign_Price__c;
                            }else if(dealerPDiscountMap.containsKey(''+ contract[0].Id + ass.Prod.Id)){
                                InsAfterDel.Intra_Trade_List_RMB__c =ass.Prod.Intra_Trade_List_RMB__c * dealerPDiscountMap.get(''+ contract[0].Id + ass.Prod.Id) / 100;
                            }else{
                                InsAfterDel.Intra_Trade_List_RMB__c =ass.Prod.Intra_Trade_List_RMB__c * disCount / 100;
                            }
                        
                            //InsAfterDel.Asset_Model_No__c = ass.Prod.Asset_Model_No__c;
                            //InsAfterDel.Sum_of_money__c = ass.esd.Consumable_Count__c * ass.esd.Dealer_Custom_Price__c;
                            InsAfterDel.RecordTypeId = System.Label.RT_ConOrderDetail1_Order;
                            //InsAfterDel.Consumable_principal__c = p.id;
                            //InsAfterDel.Dealer_Custom_Price__c = ass.esd.Dealer_Custom_Price__c;
                            i++;
                            Ins.add(InsAfterDel);
                        }
                    }
                }
                ESetId = p.id;
            }
            //修改之后 保存订单
            else if(!String.isBlank(ESetId)){
            }
            system.debug('Ins : ' + Ins);
            if(Ins.size()>0){
                insert Ins;
                return  UnabletoEdit();
            }
            else{
                List<Consumable_order__c> cocinfo = New List<Consumable_order__c>();
                cocinfo = [SELECT Id,Name,Order_status__c,Dealer_Info__c,
                                Deliver_date__c,Order_Reason__c,Offers_Price__c
                            FROM Consumable_order__c
                            WHERE Id =:ESetId];
                if (cocinfo.size()>0){
                    p = cocinfo[0];
                }
                p.Name = coc.Name;
                p.Dealer_Info__c = accountid;
                p.Order_ProType__c = agencyProType;
                p.Order_date__c = coc.Order_date__c;
                p.Order_effective_contact__c = contract[0].Id;
                p.Order_Reason__c = coc.Order_Reason__c;
                //p.Order_reason_details__c = coc.Order_reason_details__c;
                if(bargainPrice != null){
                    p.Offers_Price__c = bargainPrice;
                }
                update p;
                List<Consumable_order__c> Consumable_order = [SELECT Name FROM Consumable_order__c WHERE id =:p.id];
                List<Consumable_Orderdetails__c> qs = New List<Consumable_Orderdetails__c>();
                qs = [SELECT Id 
                        FROM Consumable_Orderdetails__c 
                        WHERE Consumable_order__c =:ESetId
                        AND Consumable_order__r.Dealer_Info__c = :accountid
                        ];
                if (qs.size()>0){
                    delete qs;
                }

                Integer i = 1;
                for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecordsview)  {
                    if(ass.check == true){
                        Consumable_Orderdetails__c InsAfterDel = new Consumable_Orderdetails__c();
                        if(ass.esd.Consumable_Count__c == null||ass.esd.Consumable_Count__c ==0){
                            ass.esd.Consumable_Count__c.addError('请输入采购数量');
                            return null;
                        }
                        //else if(ass.esd.Dealer_Custom_Price__c == null){
                          //  ass.esd.Dealer_Custom_Price__c.addError('请输入经销商定价');
                            //return null;
                        }
                        else{

                            String str = string.valueOf(i);
                            if(str.length() == 1){
                                str = '0' + str;
                            }
                            InsAfterDel.Name = Consumable_order[0].Name + '-'+ str;
                            InsAfterDel.Consumable_Count__c = ass.esd.Consumable_Count__c;
                            InsAfterDel.Consumable_order__c = ESetId;
                            InsAfterDel.Consumable_Product__c = ass.Prod.id;
                            InsAfterDel.Box_Piece__c = '盒';
                            //InsAfterDel.Sterilization_limit__c = Date.today();
                            if(DealerProductMap.containsKey(ass.Prod.Id)){
                                InsAfterDel.Intra_Trade_List_RMB__c  = DealerProductMap.get(ass.Prod.Id).Special_Campaign_Price__c;
                                InsAfterDel.Purchase_Unitprtprice_From__c = '促销';
                                InsAfterDel.Special_Campaign_Price__c  = DealerProductMap.get(ass.Prod.Id).Special_Campaign_Price__c;
                            }else if(dealerPDiscountMap.containsKey(''+ contract[0].Id + ass.Prod.Id)){
                                InsAfterDel.Intra_Trade_List_RMB__c =ass.Prod.Intra_Trade_List_RMB__c * dealerPDiscountMap.get(''+ contract[0].Id + ass.Prod.Id) / 100;
                            }else{
                                InsAfterDel.Intra_Trade_List_RMB__c =ass.Prod.Intra_Trade_List_RMB__c * disCount / 100;
                            }
                            //InsAfterDel.Intra_Trade_List_RMB__c =ass.Prod.Intra_Trade_List_RMB__c;
                            //InsAfterDel.Asset_Model_No__c = ass.Prod.Asset_Model_No__c;
                            //InsAfterDel.Sum_of_money__c = ass.esd.Consumable_Count__c * ass.esd.Dealer_Custom_Price__c;
                            //InsAfterDel.Dealer_Custom_Price__c = ass.esd.Dealer_Custom_Price__c;
                            InsAfterDel.RecordTypeId = System.Label.RT_ConOrderDetail1_Order;
                            //InsAfterDel.Consumable_principal__c = ESetId;
                            i++;

                            Ins.add(InsAfterDel);
                        }

                    }
                }
                if(Ins.size()>0){
                    insert Ins;
                }
            }
        }catch(Exception e){
            ApexPages.addMessages(e);
            Database.rollback(sp);
            return  null;
        }
        return UnabletoEdit();
    }
    */


    //保存按钮 byrentx start
    public PageReference save(){
        this.methodType =  ApexPages.currentPage().getParameters().get('type');
        //错误信息展示
        //经销商合同判断
        if(String.isEmpty(contractName)){
            coc.Order_effective_contact__c.addError('请选择合同');
            return null;
        }
        List<Account> contract = [select Id,Name,Contract_Department_Class__c,Contract_Quote_Decide_Flag__c 
                                    from account
                                    WHERE Name = :contractName
                                    AND Id =: contractId   //lt 20230517 安徽两票制 add
                                    AND Contract_Decide_Start_Date__c <= :Date.Today()
                                    AND Contract_Decide_End_Date__c >= :Date.Today()
                                    and Contact_Type__c like :agencyProType1  //lt 20230517 安徽两票制 add 1
                                    and Agent_Ref__c =:accountid
                                    and OSH_Dealer__c =: OSHFLG  //lt 20230517 安徽两票制 add
                                    ];

        if(contract.size() <= 0){
            coc.Order_effective_contact__c.addError('不存在的合同，请重新确认。');
            return null;
        }else{
            if(String.isEmpty(contract[0].Contract_Quote_Decide_Flag__c)){
                coc.Order_effective_contact__c.addError('合同无效，请重新确认。');
                return null;
            }
        }
        Integer FLG = 0;
        Integer Count = 0;
        //add by rentx 2020-11-25
        List<String> tpids = new List<String>();
        //add by rentx 2020-11-25

        for(ConsumableorderdetailsInfo CheckCount : consumableorderdetailsRecordsview) {
            FLG = FLG + 1;
            if(CheckCount.check == false){
                Count = Count + 1;
            }
            if(CheckCount.check == true){
                //add by rentx 2020-11-25
                tpids.add(CheckCount.Prod.Id);
                //add by rentx 2020-11-25

                if(CheckCount.esd.Consumable_Count__c == null||CheckCount.esd.Consumable_Count__c==0){
                    CheckCount.esd.Consumable_Count__c.addError('请输入采购数量');
                    return null;
                }
                if(CheckCount.orderGoods_Limit > 0 && math.mod(Integer.valueOf(CheckCount.esd.Consumable_Count__c),Integer.valueOf(CheckCount.orderGoods_Limit)) > 0){
                    CheckCount.esd.Consumable_Count__c.addError('请输入促销数量的倍数');
                    return null;
                }
            }
        }

        if(Count == FLG){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请选择所需消耗品')); 
            return null;
        }


        //=======================================医院特价,有金额的话取金额
        Map<String,Decimal> dealerHospitalmMap = new Map<String,Decimal>();
        // Map<String,Decimal> dealerHospitalpMap = new Map<String,Decimal>();
            List<hospitalprice__c> hplist = [select Id,hospital__c,mPrice__c,pPrice__c,product__c,account__c 
                                                from hospitalprice__c
                                                where product__c in :tpids and mPrice__c <> null 
                                                ];
        for(hospitalprice__c dealerProduct: hplist){
            if (dealerProduct.mPrice__c != null ) {
                dealerHospitalmMap.put('' + dealerProduct.account__c + dealerProduct.product__c,dealerProduct.mPrice__c); 
            }
            // if (dealerProduct.pPrice__c != null) {
            //     dealerHospitalpMap.put('' + dealerProduct.account__c + dealerProduct.product__c,dealerProduct.pPrice__c);  
            // }
        }

        //促销订货 根据经销商产品中的数据计算金额
        //=======================================产品特殊折扣
        Map<String,Decimal> dealerPDiscountMap = new Map<String,Decimal>();
        Map<String,Decimal> dealerMPDiscountMap = new Map<String,Decimal>();
        //1.获取有开始结束日的产品
        Date dateToday = Date.today();
        List<Dealer_Product__c> haveDateList = [select Id, 
                                                Name, 
                                                Dealer_Product2__c,
                                                Special_Campaign_Price__c,
                                                Campaign_StartDate__c,
                                                Campaign_EndDate__c,
                                                Dealer_Contact__c,
                                                OrderGoods_Limit__c,
                                                Special_Discount__c 
                                                from Dealer_Product__c
                                                where Dealer_Contact__c in :contactDealer
                                                and Campaign_StartDate__c <= :dateToday
                                                and Campaign_EndDate__c >= :dateToday
                                                AND (Special_Discount__c <> null
                                                    or Special_Campaign_Price__c <> null)
                                                        ];
        //2.获取没有开始结束日的产品
        List<Dealer_Product__c> DealerProductList = [select Id,
                                                            Name,
                                                            Dealer_Product2__c,
                                                            Special_Campaign_Price__c,
                                                            Campaign_StartDate__c,
                                                            Campaign_EndDate__c,
                                                            Dealer_Contact__c,
                                                            Special_Discount__c,
                                                            OrderGoods_Limit__c
                                                    from Dealer_Product__c
                                                    where Dealer_Contact__c in :contactDealer
                                                    AND (Special_Discount__c <> null
                                                        or Special_Campaign_Price__c <> null)
                                                    ];
        for(Dealer_Product__c dealerProduct: DealerProductList){
            //如果促销价格为null 则设置特殊折扣(百分比)到集合
            if (dealerProduct.Special_Campaign_Price__c == null) {
                dealerPDiscountMap.put('' + dealerProduct.Dealer_Contact__c + dealerProduct.Dealer_Product2__c,dealerProduct.Special_Discount__c);
            }else{
                dealerMPDiscountMap.put('' + dealerProduct.Dealer_Contact__c + dealerProduct.Dealer_Product2__c,dealerProduct.Special_Campaign_Price__c);
            }
        }
        //这样做是为了计算促销价格时 优先计算促销开始结束日不为空的产品 
        //如果该集合有值 则说明需要根据当前的金额或者折扣来计算
        if (haveDateList!= null && haveDateList.size() > 0) {
            for(Dealer_Product__c dealerProduct: haveDateList){
                if (dealerProduct.Special_Campaign_Price__c == null) {
                    dealerPDiscountMap.put('' + dealerProduct.Dealer_Contact__c + dealerProduct.Dealer_Product2__c,dealerProduct.Special_Discount__c);
                    dealerMPDiscountMap.remove('' + dealerProduct.Dealer_Contact__c + dealerProduct.Dealer_Product2__c);
                }else{
                    dealerMPDiscountMap.put('' + dealerProduct.Dealer_Contact__c + dealerProduct.Dealer_Product2__c,dealerProduct.Special_Campaign_Price__c);
                    dealerPDiscountMap.remove('' + dealerProduct.Dealer_Contact__c + dealerProduct.Dealer_Product2__c);
                }
            }
        }


        //=======================================经销商合同折扣
        List<Account> at = [SELECT id,Name,State_Master__c,State_Master__r.Name,Sales_Section__c,Dealer_discount__c 
                                  FROM Account 
                                  WHERE Name = :contractName 
                                    AND Id =: contractId   //lt 20230517 安徽两票制 add
                                    AND Contact_Type__c like :agencyProType1  //lt 20230517 安徽两票制 add  1
                                    AND Contract_Decide_Start_Date__c <= :Date.Today()
                                    AND Contract_Decide_End_Date__c >= :Date.Today()
                                    AND OSH_Dealer__c =: OSHFLG  //lt 20230517 安徽两票制 add
                                    ];
        System.debug('---lt123---at.size()：'+at.size());
        System.debug('---lt123---at[0].Dealer_discount__c：'+at[0].Dealer_discount__c);
        if(at.size() > 0 && at[0].Dealer_discount__c != null){
            disCount = at[0].Dealer_discount__c;
        }else{
            disCount = 100;
        }

        Consumable_order__c P = new Consumable_order__c(); 
        List<Consumable_Orderdetails__c> Ins = New List<Consumable_Orderdetails__c>();
        //新建订单时
        Savepoint sp = Database.setSavepoint();
        try{
            if(String.isBlank(ESetId)){
                Integer i = 1;        
                Integer Roll = 0;
                            
                p.Name = '*';
                p.Order_status__c = '草案中';
                p.Dealer_Info__c = accountid;
                p.Order_ProType__c = agencyProType;
                p.Offers_Price__c = coc.Offers_Price__c;
                p.Order_date__c = coc.Order_date__c;
                p.Order_effective_contact__c = contract[0].Id;
                p.Order_Reason__c = coc.Order_Reason__c;
                p.RecordTypeid = System.Label.RT_ConOrder_Order;
                p.Overrule_order__c = coc.Id;   
                if(String.isNotBlank(methodType)){ 
                    p.orderPattern__c = methodType;
                }
                
                insert p;

                List<Consumable_order__c> Consumable_order = [SELECT Name,orderPattern__c FROM Consumable_order__c WHERE id =:p.id];
                for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecordsview)  {
                    Roll = Roll+1;
                    if(ass.check == true){
                        if(ass.esd.Consumable_Count__c == null||ass.esd.Consumable_Count__c==0){
                            ass.esd.Consumable_Count__c.addError('请输入采购数量');
                            return null;
                        }
                        else{
                            Consumable_Orderdetails__c InsAfterDel = new Consumable_Orderdetails__c();
                            String str = string.valueOf(i);
                            if(str.length() == 1){
                            str = '0' + str;
                            }
                            InsAfterDel.Name = Consumable_order[0].Name + '-'+ str;
                            InsAfterDel.Consumable_Count__c = ass.esd.Consumable_Count__c;
                            InsAfterDel.Consumable_order__c = p.id;
                            InsAfterDel.Consumable_Product__c = ass.Prod.id;
                            InsAfterDel.Box_Piece__c = '盒';
                            //协议订货
                            if (methodType.equals('agreementorder')) {
                                Consumable_order[0].orderPattern__c  = 'agreementorder';

                                InsAfterDel.Intra_Trade_List_RMB__c =ass.Prod.Intra_Trade_List_RMB__c * disCount / 100;
                            //=====================================================================================update by rentx 2020-11-25
                            }else if (methodType.equals('promotionorder')) {

                                Consumable_order[0].orderPattern__c  = 'promotionorder';
                                //促销订货 
                                //如果促销价格不为null 则直接使用促销价格来计算金额
                                if (dealerMPDiscountMap.containsKey(''+ contract[0].Id + ass.Prod.Id)) {
                                    InsAfterDel.Intra_Trade_List_RMB__c =dealerMPDiscountMap.get(''+ contract[0].Id + ass.Prod.Id);
                                }else if ( dealerPDiscountMap.containsKey(''+ contract[0].Id + ass.Prod.Id)) {
                                    InsAfterDel.Intra_Trade_List_RMB__c =ass.Prod.Intra_Trade_List_RMB__c * dealerPDiscountMap.get(''+ contract[0].Id + ass.Prod.Id) / 100;
                                }
                                //=====================================================================================update by rentx 2020-11-25
                            }else if (methodType.equals('hospitalorder')) {
                                //医院特价
                                Consumable_order[0].Order_ForHospital__c = hospitalId;
                                Consumable_order[0].orderPattern__c  = 'hospitalorder';
                                if (dealerHospitalmMap.containsKey(accountid + ass.Prod.Id) && dealerHospitalmMap.get(accountid + ass.Prod.Id) != null) {
                                    //直接根据促销金额计算
                                    InsAfterDel.Intra_Trade_List_RMB__c = dealerHospitalmMap.get(''+ accountid + ass.Prod.Id);        
                                }
                            }
                            else if(DealerProductMap.containsKey(ass.Prod.Id)){
                                InsAfterDel.Intra_Trade_List_RMB__c  = DealerProductMap.get(ass.Prod.Id).Special_Campaign_Price__c;
                                InsAfterDel.Purchase_Unitprtprice_From__c = '促销';
                                InsAfterDel.Special_Campaign_Price__c  = DealerProductMap.get(ass.Prod.Id).Special_Campaign_Price__c;
                            }
                        InsAfterDel.RecordTypeId = System.Label.RT_ConOrderDetail1_Order;
                        i++;
                        Ins.add(InsAfterDel);
                        }
                    }
                }
                ESetId = p.id;
                if (Consumable_order.size() > 0) {
                    update Consumable_order;
                }   
            }
            //修改之后 保存订单
            if (Ins.size() > 0) {
                insert Ins;
            }else{
                //修改,获取消耗品订单
                List<Consumable_order__c> cocinfo = New List<Consumable_order__c>();
                cocinfo = [SELECT Id,Name,Order_status__c,Dealer_Info__c,
                                Deliver_date__c,Order_Reason__c,Offers_Price__c
                                FROM Consumable_order__c
                                WHERE Id =:ESetId];
                if (cocinfo.size()>0){
                    p = cocinfo[0];
                }
                p.Name = coc.Name;
                p.Dealer_Info__c = accountid;
                p.Order_ProType__c = agencyProType;
                p.Order_date__c = coc.Order_date__c;
                p.Order_effective_contact__c = contract[0].Id;
                p.Order_Reason__c = coc.Order_Reason__c;
                if(bargainPrice != null){
                    p.Offers_Price__c = bargainPrice;
                }
                update p;
                List<Consumable_order__c> Consumable_order = [SELECT Name,orderPattern__c FROM Consumable_order__c WHERE id =:p.id];
                List<Consumable_Orderdetails__c> qs = New List<Consumable_Orderdetails__c>();
                qs = [SELECT Id 
                        FROM Consumable_Orderdetails__c 
                        WHERE Consumable_order__c =:ESetId
                        AND Consumable_order__r.Dealer_Info__c = :accountid
                        ];
                if (qs.size()>0){
                    delete qs;
                }

                    Integer i = 1;
                for (ConsumableorderdetailsInfo ass : consumableorderdetailsRecordsview)  {
                    if(ass.check == true){
                        Consumable_Orderdetails__c InsAfterDel = new Consumable_Orderdetails__c();
                        if(ass.esd.Consumable_Count__c == null||ass.esd.Consumable_Count__c ==0){
                            ass.esd.Consumable_Count__c.addError('请输入采购数量');
                            return null;
                        }else{
                            String str = string.valueOf(i);
                            if(str.length() == 1){
                                str = '0' + str;
                            }
                            InsAfterDel.Name = Consumable_order[0].Name + '-'+ str;
                            InsAfterDel.Consumable_Count__c = ass.esd.Consumable_Count__c;
                            InsAfterDel.Consumable_order__c = ESetId;
                            InsAfterDel.Consumable_Product__c = ass.Prod.id;
                            InsAfterDel.Box_Piece__c = '盒';
                            //协议订货
                            if (methodType.equals('agreementorder')) {
                                Consumable_order[0].orderPattern__c  = 'agreementorder';
                                InsAfterDel.Intra_Trade_List_RMB__c =ass.Prod.Intra_Trade_List_RMB__c * disCount / 100;
                            }else if (methodType.equals('promotionorder')) {
                                Consumable_order[0].orderPattern__c  = 'promotionorder';
                                //促销订货 
                                if (dealerMPDiscountMap.containsKey(''+ contract[0].Id + ass.Prod.Id)) {
                                    InsAfterDel.Intra_Trade_List_RMB__c =dealerMPDiscountMap.get(''+ contract[0].Id + ass.Prod.Id);
                                }else if ( dealerPDiscountMap.containsKey(''+ contract[0].Id + ass.Prod.Id)) {
                                    InsAfterDel.Intra_Trade_List_RMB__c =ass.Prod.Intra_Trade_List_RMB__c * dealerPDiscountMap.get(''+ contract[0].Id + ass.Prod.Id) / 100;
                                }
                            }else if (methodType.equals('hospitalorder')) {
                                Consumable_order[0].orderPattern__c  = 'hospitalorder';
                                //医院特价
                                Consumable_order[0].Order_ForHospital__c = hospitalId;
                                if (dealerHospitalmMap.containsKey(accountid + ass.Prod.Id) && dealerHospitalmMap.get(accountid + ass.Prod.Id) != null) {
                                    //直接根据促销金额计算
                                    InsAfterDel.Intra_Trade_List_RMB__c = dealerHospitalmMap.get(''+ accountid + ass.Prod.Id);        
                                }
                            }
                            else if(DealerProductMap.containsKey(ass.Prod.Id)){
                                InsAfterDel.Intra_Trade_List_RMB__c  = DealerProductMap.get(ass.Prod.Id).Special_Campaign_Price__c;
                                InsAfterDel.Purchase_Unitprtprice_From__c = '促销';
                                InsAfterDel.Special_Campaign_Price__c  = DealerProductMap.get(ass.Prod.Id).Special_Campaign_Price__c;
                            }
                            // ==================================================之前的促销订货的逻辑
                            InsAfterDel.RecordTypeId = System.Label.RT_ConOrderDetail1_Order;
                            i++;
                            Ins.add(InsAfterDel);
                        }
                    }
                }
                if(Ins.size()>0){
                    insert Ins;
                }
            }
        }catch(Exception e){
            ApexPages.addMessages(e);
            Database.rollback(sp);
            return null;
        }
        // return null;
        return UnabletoEdit();

    }
    //保存按钮 byrentx end


    // 返回不可编辑状态
    public PageReference UnabletoEdit(){
        PageReference ref = new Pagereference('/Consumable?ESetid='+ESetId+'&type='+this.methodType);
        ref.setRedirect(true);
        return ref;
    }

    // 显示数据条数信息
    private void makeMessage() {
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '共有' + noOfRecords + '件产品'));
    }

    // Data Bean
    class ConsumableorderdetailsInfo implements Comparable {
        public Boolean check { get; set; }
        public Boolean oldCheck { get; set; }
        public Consumable_Orderdetails__c esd { get; set; }
        public Product2__c Prod { get; set; }
        public Integer packing_list { get; set; }
        public Date expiration_Date { get; set; }
        public String approbation_No { get; set; }
        public Decimal allnumber { get; set; }
        public Decimal allnumber_piece { get; set; }
        public Decimal oldConsumableCount { get; set; }
        public Boolean canSelect { get; set; }
        public Attachment Concc { get; set; }
        public Boolean sortBy { get; set; }
        public Decimal upperlimit { get; set; }
        public Decimal lowerlimit { get; set; }
        public Decimal SpecialCampaignPrice { get; set; }
        public Decimal orderGoods_Limit { get; set; }
        public Date Campaign_EndDate { get; set; }

        // 已存产品明细
        public ConsumableorderdetailsInfo(Consumable_Orderdetails__c e) {
            check = true;
            oldCheck = true;
            esd = e;
            Prod = e.Consumable_Product__r;
            oldConsumableCount = e.Consumable_Count__c;
            canSelect = true;
            allnumber = 0;
            allnumber_piece = 0;
        }

        public ConsumableorderdetailsInfo(Product2__c e) {
            check = false;
            oldCheck = false;
            esd = new Consumable_Orderdetails__c();
            Prod = e;
            oldConsumableCount = null;
            canSelect = true;
            allnumber = 0;
            allnumber_piece = 0;
        }
        //附件
        public ConsumableorderdetailsInfo(Attachment e) {
            Concc = e;
        }
        // 排序Consumable_order__c
        public Integer compareTo(Object compareTo) {
            ConsumableorderdetailsInfo compareToesd =(ConsumableorderdetailsInfo)compareTo;
            Integer returnValue = 0;
            if(check == true){
                if(sortBy == false){
                    if (allnumber > compareToesd.allnumber) {
                        returnValue = -1;
                    } else if (allnumber < compareToesd.allnumber) {
                        returnValue = 1;
                    }
                    return returnValue;
                }else{
                    if (allnumber > compareToesd.allnumber) {
                        returnValue = 1;
                    } else if (allnumber < compareToesd.allnumber) {
                        returnValue = -1;
                    }
                    return returnValue;
                }
                //returnValue = -1;
                //return returnValue;
            }else{
                if(sortBy == false){
                    if (allnumber > compareToesd.allnumber) {
                        returnValue = -1;
                    } else if (allnumber < compareToesd.allnumber) {
                        returnValue = 1;
                    }
                    return returnValue;
                }else{
                    if (allnumber > compareToesd.allnumber) {
                        returnValue = 1;
                    } else if (allnumber < compareToesd.allnumber) {
                        returnValue = -1;
                    }
                    return returnValue;
                }
            }
            
        }
    }

    
}