public with sharing class LexQuoteEntryDecidebottonController {
     //fy DB202312538864 2024.02.19 start
     public static List<PreProduct_Storage_List__c> PreProductStorageList = new List<PreProduct_Storage_List__c>();
     public static List<PreProduct_Storage__c> UpdatePreProductStorageList =  new List<PreProduct_Storage__c>();
     //fy DB202312538864 2024.02.19 end
    @AuraEnabled
    public static String updateOpportunity(String recordId){
        //fy DB202312538864 2024.02.19 start
        Savepoint sp = Database.setSavepoint();
        //fy DB202312538864 2024.02.19 end
        try {
            //fy DB202312538864 2024.02.19 start
            checkLastbuydecide(recordId);
            //fy DB202312538864 2024.02.19 end
            Opportunity opp = new Opportunity();
            opp.Id = recordId;
            opp.Estimation_Decision__c = false;
            opp.Stock_Confrim_Date__c = null;
            update opp;
            //fy DB202312538864 2024.02.19 start
            if(PreProductStorageList.size()>0){
                insert PreProductStorageList;
            }
            // if(UpdatePreProductStorageList.size()>0){
            //     update UpdatePreProductStorageList;
            // }
            System.debug('PreProductStorageListf56522!!!'+PreProductStorageList);
            System.debug('UpdatePreProductStorageListdf22565!!!'+UpdatePreProductStorageList);
            //fy DB202312538864 2024.02.19 end
            return 'success';
        } catch (Exception e) {
            //fy DB202312538864 2024.02.19 start
            Database.rollback(sp);
            //fy DB202312538864 2024.02.19 end
            return '取消Decide失败:'+e.getLineNumber()+':'+e.getMessage();
        }
    }
    @AuraEnabled
    public static Opportunity selectOpportunityById(String recordId){
        Opportunity opp = [select id,Estimation_Decision__c from Opportunity where Id = :recordId];
        return opp;
    }
    @AuraEnabled
    public static User selectUser(){
        User us = new User();
        String userid = UserInfo.getUserId();
        if (userid != null) {
            us = [Select Id,Quote_Correct__c From User Where Id = :userid];
        }
        return us;
    }
    //fy DB202312538864 2024.02.19 start
    //产品预留check
    // public static Boolean checkLastbuy2(String recordId){
    //     Boolean lastcheck = false;
    //     Map<string,OpportunityLineItem> quotlinitMap = new Map<string,OpportunityLineItem>();
    //     List<Id> lastProductFLGListId = new List<Id>();
    //     List<OpportunityLineItem> lastProductFLGList = new List<OpportunityLineItem>();
    //     List<OpportunityLineItem> act = new List<OpportunityLineItem>();
    //     List<OpportunityLineItem> act2 = new List<OpportunityLineItem>();
    //     // for(QELine aaa :activities){
    //     //   if(aaa.pageObject.PricebookEntry.Product2Id!=null){
    //     //     act.add(aaa.pageObject);
    //     //   }
    //     // }
    //     Opportunity opp = new Opportunity();
    //     List<Opportunity> oppList = [select Id,Salesdepartment_SAP__c,OCM_man_province_cus__c from Opportunity where Id =:recordId];
    //     if(oppList.size()>0){
    //         opp = oppList[0];
    //     }
    //     act =  [select Id,Quantity,PricebookEntry.Product2Id,PricebookEntry.Product2.LastbuyProductFLG__c from OpportunityLineItem where OpportunityId =:recordId];
    //     act2=act.deepClone();
    //     Map<String,OpportunityLineItem> map1 = new Map<String,OpportunityLineItem>();
    //     System.debug('activitiesss!!!'+act);
    //     //*****合并产品重复的报价行项目****
    //     for(OpportunityLineItem pspsc :act2){
    //       if(pspsc.PricebookEntry.Product2Id!=null){
    //         if(map1.containsKey(pspsc.PricebookEntry.Product2Id)){
    //             OpportunityLineItem quoteLine = map1.get(pspsc.PricebookEntry.Product2Id);
    //           quoteLine.Quantity =quoteLine.Quantity+pspsc.Quantity;
    //           map1.put(pspsc.PricebookEntry.Product2Id,quoteLine);
    //         }else{
    //           map1.put(pspsc.PricebookEntry.Product2Id,pspsc);
    //         }
    //         System.debug('3449987sdf9!!!'+act);
    //       }
    //     }
    //     System.debug('3434sdf343!!!'+act);
    //     System.debug('5656sdf565!!!'+map1);
    //     for (OpportunityLineItem value : map1.values()) {
    //       if(value.PricebookEntry.Product2.LastbuyProductFLG__c){
    //         lastProductFLGListId.add(value.PricebookEntry.Product2Id);
    //         quotlinitMap.put(value.PricebookEntry.Product2Id,value);
    //         lastProductFLGList.add(value);
    //       }
    //     }
    //     System.debug('opp5656sdf565!!!'+opp);
    //     //*****合并产品重复的报价****
    //     if(lastProductFLGListId!=null&&lastProductFLGListId.size()!=0){
    //       // 锁定行前查询数据
    //       List<PreProduct_Storage__c> lockedPreProductStorage = [SELECT Id,Name,Storage_Number__c,Used_Number__c,Department__c,Province__c,Product_Type__c,Field1__c FROM PreProduct_Storage__c WHERE ifValid__c = true and Field1__c in:lastProductFLGListId FOR UPDATE];
    //       // 执行需要锁定行的其他操作
    //       if(lockedPreProductStorage!=null&&lockedPreProductStorage.size()!=0){
            
    //         for (PreProduct_Storage__c preProductStorage : lockedPreProductStorage) {
    //           Decimal pronumber = map1.get(preProductStorage.Field1__c).Quantity;
    //           if((preProductStorage.Product_Type__c == '整机'
    //             && opp.Salesdepartment_SAP__c == preProductStorage.Department__c )
    //             || (preProductStorage.Product_Type__c == '耗品'
    //             && opp.OCM_man_province_cus__c == preProductStorage.Province__c)){
    //               // preProductStorage.LeftNumber__c += pronumber;
    //               // preProductStorage.Used_Number__c -= pronumber;
    //               PreProduct_Storage_List__c PreProductStorageObj = new PreProduct_Storage_List__c();
    //               PreProductStorageObj.PreProduct_Storage__c = preProductStorage.Id;
    //               PreProductStorageObj.Modify_Number__c = pronumber;
    //               PreProductStorageObj.AddReduceNumber__c = pronumber;
    //               PreProductStorageObj.Modified_Time__c = Datetime.now();
    //               PreProductStorageObj.Change_Type__c = '退回';
    //               PreProductStorageObj.Opportunity__c = recordId;
    //               UpdatePreProductStorageList.add(preProductStorage);
    //               PreProductStorageList.add(PreProductStorageObj);
    //           }
    //         }
    //       }
    //     }
    //     System.debug('PreProductStorageListf565!!!'+PreProductStorageList);
    //     System.debug('UpdatePreProductStorageListdf565!!!'+UpdatePreProductStorageList);
    //     return lastcheck;
      
    // }
      //产品预留check
    public static Boolean checkLastbuydecide(String recordId){
      Boolean lastcheck = false;
      Map<string,OpportunityLineItem> quotlinitMap = new Map<string,OpportunityLineItem>();
      List<Id> lastProductFLGListId = new List<Id>();
      List<Id> NewcodeListId = new List<Id>();
      // List<Id> lastNewcodeListId = new List<Id>();
      List<OpportunityLineItem> lastProductFLGList = new List<OpportunityLineItem>();
      List<OpportunityLineItem> act = new List<OpportunityLineItem>();
      List<OpportunityLineItem> act2 = new List<OpportunityLineItem>();
      Opportunity opp = new Opportunity();
      List<Opportunity> oppList = [select Id,Salesdepartment_SAP__c,OCM_man_province_cus__c from Opportunity where Id =:recordId];
      if(oppList.size()>0){
          opp = oppList[0];
      }
      act =  [select Id,Quantity,PricebookEntry.Product2Id,PricebookEntry.Product2.LastbuyProductFLG__c,PricebookEntry.Product2.whetherOldCode_PrePro__c from OpportunityLineItem where OpportunityId =:recordId];
      
      act2=act.deepClone();
      Map<String,OpportunityLineItem> map1 = new Map<String,OpportunityLineItem>();
      System.debug('activitiessws!!!'+act);
      //*****合并产品重复的报价行项目****
      for(OpportunityLineItem pspsc :act2){
        if(pspsc.PricebookEntry.Product2Id!=null){
          if(map1.containsKey(pspsc.PricebookEntry.Product2Id)){
            OpportunityLineItem quoteLine = map1.get(pspsc.PricebookEntry.Product2Id);
            quoteLine.Quantity =quoteLine.Quantity + pspsc.Quantity;
            map1.put(pspsc.PricebookEntry.Product2Id,quoteLine);
          }else{
            map1.put(pspsc.PricebookEntry.Product2Id,pspsc);
          }
          System.debug('3449987wsdf9!!!'+act);
        }
      }
      System.debug('3434sdf3w43!!!'+act);
      System.debug('5656sdf5w65!!!'+map1);
      for (OpportunityLineItem value : map1.values()) {
        //检索是否有旧code的产品id
        if(value.PricebookEntry.Product2.whetherOldCode_PrePro__c){
          NewcodeListId.add(value.PricebookEntry.Product2Id);
        }
        if(value.PricebookEntry.Product2.LastbuyProductFLG__c){
          lastProductFLGListId.add(value.PricebookEntry.Product2Id);
          quotlinitMap.put(value.PricebookEntry.Product2Id,value);
          lastProductFLGList.add(value);
        }
      }
      System.debug('5656sdfaa5w65!!!'+NewcodeListId);
      List<Product2> prd2List = new List<Product2>();
      Map<String,String> prd2Map = new Map<String,String>();
      Map<String,PreProduct_Storage__c> prd2ppsMap = new Map<String,PreProduct_Storage__c>();
      // List<PreProduct_Storage__c> ProductStorageList = new List<PreProduct_Storage__c>();
      if(NewcodeListId.size() > 0){
        prd2List = [Select Id,Correspond_Code__c From Product2 Where Correspond_Code__c In:NewcodeListId];
        for(Product2 prd2 : prd2List){
          lastProductFLGListId.add(prd2.Id);
          prd2Map.put(prd2.Correspond_Code__c, prd2.Id);
        }
      }
      System.debug('opp5656sdf565!!!'+opp);
      //*****合并产品重复的报价****
      if(lastProductFLGListId!=null&&lastProductFLGListId.size()!=0){
        // 锁定行前查询数据
        List<PreProduct_Storage__c> lockedPreProductStorage = [SELECT Id,Name,Storage_Number__c,LeftNumber__c,Used_Number__c,Department__c,Province__c,RecordType.Name,Field1__c 
        FROM PreProduct_Storage__c WHERE ifValid__c = true and Field1__c in:lastProductFLGListId 
        and ((RecordType.Name = '整机' and Department__c =:opp.Salesdepartment_SAP__c) 
          or (RecordType.Name = '耗材' and Province__c =:opp.OCM_man_province_cus__c) ) FOR UPDATE];
        // 执行需要锁定行的其他操作
        System.debug('opp5656sdf56aa5!!!>>'+lockedPreProductStorage);
        if(lockedPreProductStorage!=null&&lockedPreProductStorage.size()!=0){
          List<Id> preProductStorageIdList = new List<Id>();
          for (PreProduct_Storage__c preProductStorage : lockedPreProductStorage) {
              prd2ppsMap.put(preProductStorage.Field1__c,preProductStorage);
              preProductStorageIdList.add(preProductStorage.Id);
          }
          List<PreProduct_Storage_List__c> pslList = [select Id,PreProduct_Storage__c,AddReduceNumber__c,Opportunity__c 
                                                      from PreProduct_Storage_List__c 
                                                      where Opportunity__c =:opp.Id 
                                                      and PreProduct_Storage__c in:preProductStorageIdList];
          Map<String,Decimal> fallbackQuantityMap = new Map<String,Decimal>();
          for(PreProduct_Storage_List__c psl :pslList){
            if(fallbackQuantityMap.containsKey(psl.PreProduct_Storage__c)){
              Decimal lastsumnum = fallbackQuantityMap.get(psl.PreProduct_Storage__c);
              Decimal newsumnum = psl.AddReduceNumber__c+lastsumnum;
              fallbackQuantityMap.put(psl.PreProduct_Storage__c,newsumnum);
            }else{
              fallbackQuantityMap.put(psl.PreProduct_Storage__c,psl.AddReduceNumber__c);
            }
          }
          for (OpportunityLineItem value2 : map1.values()) {
            if(prd2ppsMap.containsKey(value2.PricebookEntry.Product2Id) || value2.PricebookEntry.Product2.whetherOldCode_PrePro__c){
              //有预留的产品
              PreProduct_Storage__c preProductStorage2 = prd2ppsMap.get(value2.PricebookEntry.Product2Id);
              //有旧code的产品
              PreProduct_Storage__c oldcodeps = prd2ppsMap.get(prd2Map.get(value2.PricebookEntry.Product2Id));
              if(oldcodeps != null){
                Decimal oldcodenum = fallbackQuantityMap.get(oldcodeps.Id);
                if(oldcodenum<0){
                  oldcodenum = -oldcodenum;
                  PreProduct_Storage_List__c PreProductStorageObj = new PreProduct_Storage_List__c();
                  PreProductStorageObj.PreProduct_Storage__c = oldcodeps.Id;
                  PreProductStorageObj.Modify_Number__c = oldcodenum;
                  PreProductStorageObj.AddReduceNumber__c = oldcodenum;
                  PreProductStorageObj.Modified_Time__c = Datetime.now();
                  PreProductStorageObj.Change_Type__c = '退回';
                  PreProductStorageObj.Opportunity__c = opp.Id;
                  PreProductStorageList.add(PreProductStorageObj);
                }
              }
              if(preProductStorage2 != null){
                Decimal newnum = fallbackQuantityMap.get(preProductStorage2.Id);
                if(newnum<0){
                  newnum = -newnum;
                  PreProduct_Storage_List__c PreProductStorageObj = new PreProduct_Storage_List__c();
                  PreProductStorageObj.PreProduct_Storage__c = preProductStorage2.Id;
                  PreProductStorageObj.Modify_Number__c = newnum;
                  PreProductStorageObj.AddReduceNumber__c = newnum;
                  PreProductStorageObj.Modified_Time__c = Datetime.now();
                  PreProductStorageObj.Change_Type__c = '退回';
                  PreProductStorageObj.Opportunity__c = opp.Id;
                  PreProductStorageList.add(PreProductStorageObj);
                }
              }
            }
          }
        }
      }
      System.debug('PreProductStorageListf565!!!'+PreProductStorageList);
      System.debug('UpdatePreProductStorageListdf565!!!'+UpdatePreProductStorageList);
      return lastcheck;
    
    }
      //fy DB202312538864 2024.02.19 end
}