public without sharing class lexToMcpApprovalController {
     // 服务合同打包-跳转到提交待审批
    @AuraEnabled
    public static List<InitData> init(String recordId ,String mcpeId){
        List<InitData> initDataList  = new List<InitData>();
        String exitId = '';
        InitData initData = new InitData();
        List<Maintenance_Contract_Estimate__c> optionList = new List<Maintenance_Contract_Estimate__c>();
        List<Maintenance_Contract_Estimate__c> mceLists = [Select Id,Name,Maintenance_Price__c,Estimate_Asset_Cnt__c,CreatedDate,
                    Request_quotation_Amount__c,
                    Monthly_Repair_Cost_SUM__c,
                    Maintenance_Contract__r.Name,
                    Maintenance_Contract__r.Id 
                    from Maintenance_Contract_Estimate__c 
                    where Maintenance_Contract__c in (Select Id from Maintenance_Contract__c  where MaintanceContractPack__c = :recordId) order by Maintenance_Contract__r.Id];

         //编辑页面初始化
        List<MaintanceContractPackEstimate__c> mcpeList = [Select Id,Name,McpeReson__c,Consumption_Rate_Solution__c,Maintenance_Contract_Estimate__c,Decide__c,Process_Status__c from MaintanceContractPackEstimate__c where Id =:mcpeId];
        MaintanceContractPackEstimate__c mcpe = new MaintanceContractPackEstimate__c();
        if(mcpeList.size()>0) {
            mcpe = mcpeList[0];
        }
        for(Maintenance_Contract_Estimate__c mce : mceLists) {
            // Maintenance_Contract_Estimate__c mceObj = new Maintenance_Contract_Estimate__c();
            // mceObj.Id = mce.Id;
            // mceObj.Name = mce.Name;
            // mceObj.Maintenance_Price__c = mce.Maintenance_Price__c;
            // mceObj.Estimate_Asset_Cnt__c = mce.Estimate_Asset_Cnt__c;
            if(!exitId.equals(mce.Maintenance_Contract__r.Id) && exitId !='' ){
                initData.mceList = optionList;
                initDataList.add(initData);
                initData = new InitData();
                optionList = new List<Maintenance_Contract_Estimate__c>();
                exitId = mce.Maintenance_Contract__r.Id;
                initData.mcId = mce.Maintenance_Contract__r.Id;
                initData.mcName = mce.Maintenance_Contract__r.Name;
                if(String.isNotBlank(mcpe.Id)) {
                     initData.mcpeId = mcpe.Id;
                     initData.mcpeReson = mcpe.McpeReson__c;
                     initData.consumptionRateSolution = mcpe.Consumption_Rate_Solution__c;
                     initData.isMcpeDecide = mcpe.Decide__c;
                     initData.processStatus = mcpe.Process_Status__c;
                     initData.mceIds = mcpe.Maintenance_Contract_Estimate__c;
                }
                
                System.debug('---initData' +initData);
            } else if(exitId ==''){
                exitId = mce.Maintenance_Contract__r.Id;
                initData.mcId = mce.Maintenance_Contract__r.Id;
                initData.mcName = mce.Maintenance_Contract__r.Name;
                if(String.isNotBlank(mcpe.Id)) {
                    initData.mcpeId = mcpe.Id;
                    initData.mcpeReson = mcpe.McpeReson__c;
                    initData.consumptionRateSolution = mcpe.Consumption_Rate_Solution__c;

                    initData.isMcpeDecide = mcpe.Decide__c;
                    initData.processStatus = mcpe.Process_Status__c;
                    initData.mceIds = mcpe.Maintenance_Contract_Estimate__c;
                }
            } 
            optionList.add(mce);
        }
       
        initData.mceList = optionList;
        initDataList.add(initData);  
      
        System.debug('---initDataList' +initDataList); 
        return initDataList;
    }


    @AuraEnabled
    public static SaveReturnData save(String recordId, List<String> mceIds,String mcpeReson,String mcpeId,Boolean isDecide,String consumptionRateSolution) {
        Decimal contractAmount = 0;
        SaveReturnData returnData = new SaveReturnData();
        Savepoint sp = Database.setSavepoint();
        String contractType = '其它合同';
        Boolean isNewContractType = true;
        Decimal consumptionRateForecast;
        Decimal GuidePrice_DownF = 0;
        Decimal GuidePrice_UpF = 0;
        Decimal Request_quotation_Amount = 0;
        Decimal Limit_Price_Amount = 0;
        Decimal Asset_Repair_Sum_PriceF = 0;
        Decimal Contract_Amount = 0;
        Decimal Service_discount_Rate;

        Decimal totalPriceNumerator = 0;
        Decimal totalPriceDenominator = 0;
        Decimal monthlyRepairCostSUM = 0;
        Decimal contractRange = 0;
        Decimal costrateForecast = 0; 
        Decimal Total_Contract_Price = 0; 
        String estimatePriceRange;
        String contractPriceType; 
        Decimal Estimate_Asset_Cnt = 0; 
        Decimal Sum_repair_price = 0; 
        Decimal Repair_Cost_Sum = 0;  //    维修成本总金额
        Decimal Usage_ratio_New = 0;  //    合同消费率
        Decimal Contract_Consumption_rate = 0;  //    消费率（每月实时）
        String Dealer; //经销商名--取任意一条小合同的经销商名即可
        Boolean old_Is_RecognitionModel = false;
        //小合同有decide的情况下，报价组合不能进行取消decide操作
        List<Maintenance_Contract_Estimate__c> mceDecideLists = [Select Id,Name,Maintenance_Price__c,Estimate_Asset_Cnt__c,CreatedDate,
                    Request_quotation_Amount__c,
                    Monthly_Repair_Cost_SUM__c,
                    Maintenance_Contract__r.Name,
                    Maintenance_Contract__r.Id 
                    from Maintenance_Contract_Estimate__c 
                    where Estimation_Decision__c=true and Process_Status__c='批准' and Maintenance_Contract__c in (Select Id from Maintenance_Contract__c  where MaintanceContractPack__c = :recordId) order by Maintenance_Contract__r.Id];

        String errorMsg = '';
        System.debug('mceDecideLists.size:' + mceDecideLists.size());
        System.debug('isDecide:' + isDecide);
        System.debug('mcpeId:' + mcpeId);
        // if(!isDecide && String.isNotBlank(mcpeId) && mceDecideLists.size()>0 ) {
        if( String.isNotBlank(mcpeId) && mceDecideLists.size()>0 ) {
            List<MaintanceContractPackEstimate__c> mcpeDecide = [Select Id from MaintanceContractPackEstimate__c where Id = :mcpeId and Decide__c=true];
            System.debug('mcpeDecide.size:' + mcpeDecide.size());

            // if(mcpeDecide.size()>0) {
                for(Maintenance_Contract_Estimate__c mce:mceDecideLists) {
                    errorMsg += mce.Name;
                    errorMsg += ':小合同报价已经decide,请先对小合同报价取消decide后再操作 \n';
                }
                System.debug('errorMsg:' + errorMsg);
                returnData.result = errorMsg;
                return returnData;
            // }
        }
        try {
            String mceIdsString = String.join(mceIds, ',');
            MaintanceContractPack__c mcp = new MaintanceContractPack__c();
            //zzm 20240116  DB202401357055 打包报价15个合同超限问题 start
            
            // List<MaintanceContractPackEstimate__c> mcpeExists = [Select Id from MaintanceContractPackEstimate__c where Maintenance_Contract_Estimate__c = :mceIdsString];
            // if(mcpeExists.size()>0 && String.isBlank(mcpeId)) {
            //     returnData.result = '报价组合已存在';

            //     return returnData;
            // }
            List<MaintanceContractPackEstimate__c> mcpeExists = [Select Id ,Maintenance_Contract_Estimate__c from MaintanceContractPackEstimate__c where MaintanceContractPack__c = :recordId];
            for(MaintanceContractPackEstimate__c mcpeTemp:mcpeExists) {
                if(mcpeTemp.Maintenance_Contract_Estimate__c ==mceIdsString  && String.isBlank(mcpeId)) {
                    returnData.result = '报价组合已存在';
                    return returnData;
                }
            }
            //zzm 20240116  DB202401357055 打包报价15个合同超限问题 end
            List<Maintenance_Contract_Estimate__c> mceOther = new List<Maintenance_Contract_Estimate__c>();
            MaintanceContractPackEstimate__c mcpe = new MaintanceContractPackEstimate__c();
            mcpe.MaintanceContractPack__c = recordId;
            mcpe.McpeReson__c = mcpeReson;
            mcpe.Consumption_Rate_Solution__c = consumptionRateSolution;
            List<MaintanceContractPack__c> mcps = [Select Id ,Management_Code__c From MaintanceContractPack__c Where Id = :recordId ];
            Integer mcpeCode = [Select Count() from MaintanceContractPackEstimate__c Where MaintanceContractPack__c = :recordId];
            mcpeCode = mcpeCode +1;
            if(mcps.size()>0 ) {
                mcp.Id = mcps[0].Id;
            }
            if(String.isBlank(mcpeId)) {
                mcpe.Name = mcps[0].Management_Code__c+'-0' + mcpeCode.format();
            }
                
            
            mcpe.Maintenance_Contract_Estimate__c = String.join(mceIds, ',');
            mcpe.Maintenance_Contract_Estimate_TextArea__c = String.join(mceIds, '\n');


            List<Maintenance_Contract_Estimate__c> mceSelectList = [Select Id,Name
                ,SalesDepartment__c
                ,Asset_Repair_Sum_Price__c
                ,Limit_Price_Amount__c
                ,Maintenance_Contract__r.GuidePrice_UpF__c
                ,GuidePrice_Down__c
                ,GuidePrice_Up__c
                ,Maintenance_Contract__r.GuidePrice_DownF__c
                ,Contract_Range__c
                ,Request_quotation_Amount__c
                ,Monthly_Repair_Cost_SUM__c
                ,New_Contract_Type_TxT__c 
                ,Maintenance_Price__c
                ,Total_Contract_Price__c
                ,Maintenance_Contract__r.Contract_Amount__c 
                ,Maintenance_Contract__r.Estimate_Asset_Cnt__c  //报价资产件数
                ,Maintenance_Contract__r.Sum_repair_price_new__c  //合同期间修理金额
                ,Maintenance_Contract__r.Repair_Cost_Sum__c  // 维修成本总金额
                ,Maintenance_Contract__r.Dealer__c  // 经销商名
                ,Maintenance_Contract__r.old_Is_RecognitionModel__c  // 经销商名
                From Maintenance_Contract_Estimate__c Where Name in :mceIds];
            List<String> New_Contract_Type_TextAreas = new List<String>();
            for(Maintenance_Contract_Estimate__c mce : mceSelectList){
                New_Contract_Type_TextAreas.add(mce.New_Contract_Type_TxT__c);
                contractAmount += mce.Maintenance_Price__c;
                if(mce.New_Contract_Type_TxT__c == '首签合同') {
                    contractType = '首签合同';
                    isNewContractType = false;
                } else if(mce.New_Contract_Type_TxT__c != '新品合同') {
                    isNewContractType = false;
                }
                if (mce.Monthly_Repair_Cost_SUM__c !=null) {
                    monthlyRepairCostSUM = mce.Monthly_Repair_Cost_SUM__c;
                }
                if (mce.Contract_Range__c !=null) {
                    contractRange = mce.Contract_Range__c;
                }
                if (mce.Request_quotation_Amount__c !=null && mce.Request_quotation_Amount__c!=0) {
                   // 计算分子
                    totalPriceNumerator += (monthlyRepairCostSUM*contractRange*30);
                   // 计算分母
                    totalPriceDenominator += mce.Request_quotation_Amount__c;
                }
                if (mce.Limit_Price_Amount__c !=null) {
                    Limit_Price_Amount += mce.Limit_Price_Amount__c;
                }
                if (mce.Asset_Repair_Sum_Price__c !=null) {
                    Asset_Repair_Sum_PriceF += mce.Asset_Repair_Sum_Price__c;
                }
                // if (mce.Limit_Price_Amount__c !=null) {
                //     Contract_Amount += mce.Maintenance_Contract__r.Contract_Amount__c;
                // }
                // if (mce.Maintenance_Contract__r.GuidePrice_DownF__c !=null) {
                //     GuidePrice_DownF += mce.Maintenance_Contract__r.GuidePrice_DownF__c;
                // }
                // if (mce.Maintenance_Contract__r.GuidePrice_UpF__c !=null) {
                //     GuidePrice_UpF += mce.Maintenance_Contract__r.GuidePrice_UpF__c;
                // } 
                if (mce.Maintenance_Contract__r.Contract_Amount__c !=null) {
                    Contract_Amount += mce.Maintenance_Contract__r.Contract_Amount__c;
                }
                if (mce.GuidePrice_Down__c !=null) {
                    GuidePrice_DownF += mce.GuidePrice_Down__c;
                }
                if (mce.GuidePrice_Up__c !=null) {
                    GuidePrice_UpF += mce.GuidePrice_Up__c;
                } 
                //申请报价金额
                if (mce.Request_quotation_Amount__c!=null) {
                    Request_quotation_Amount += mce.Request_quotation_Amount__c; 
                }
                if (mce.Total_Contract_Price__c!=null) {
                    Total_Contract_Price += mce.Total_Contract_Price__c; 
                }
                //报价资产件数
                if (mce.Maintenance_Contract__r.Estimate_Asset_Cnt__c !=null) {
                    Estimate_Asset_Cnt += mce.Maintenance_Contract__r.Estimate_Asset_Cnt__c;
                }
                // 合同期间修理金额（大）
                // if (mce.Maintenance_Contract__r.Sum_repair_price_new__c !=null) {
                //     Sum_repair_price += mce.Maintenance_Contract__r.Sum_repair_price_new__c;
                // }
                //维修成本总金额
                if (mce.Maintenance_Contract__r.Repair_Cost_Sum__c !=null) {
                    Repair_Cost_Sum += mce.Maintenance_Contract__r.Repair_Cost_Sum__c;
                }
                //经销商名
                if (mce.Maintenance_Contract__r.Dealer__c !=null) {
                    Dealer = mce.Maintenance_Contract__r.Dealer__c;
                }
                 //先款经销商
                if (mce.Maintenance_Contract__r.old_Is_RecognitionModel__c !=null) {
                    old_Is_RecognitionModel = mce.Maintenance_Contract__r.old_Is_RecognitionModel__c;
                }
            }

            mcpe.New_Contract_Type_TextArea__c = String.join(New_Contract_Type_TextAreas, '\n');
            mcpe.Limit_Price_Amount__c = Limit_Price_Amount;
            mcpe.Asset_Repair_Sum_Price__c = Asset_Repair_Sum_PriceF;
            // mcpe.Contract_Amount__c = Contract_Amount;
            mcpe.GuidePrice_DownF__c = GuidePrice_DownF; 
            mcpe.GuidePrice_UpF__c = GuidePrice_UpF; 
            mcpe.Request_quotation_Amount__c = Request_quotation_Amount;
            mcpe.Maintenance_Price__c = contractAmount;
            mcpe.Total_Contract_Price__c = Total_Contract_Price;
                
            if(isNewContractType) {
                contractType = '新品合同';
            }
            if (totalPriceDenominator != 0) {
                // 预测消费率
                consumptionRateForecast = ((totalPriceNumerator/totalPriceDenominator)*100);
                mcpe.Consumption_rate_Forecast__c = consumptionRateForecast;
               
                // 预测成本率
                costrateForecast = (totalPriceNumerator/totalPriceDenominator)*0.75*100;
                mcpe.Cost_rate_Forecast__c = costrateForecast;
                
            }
            if(Request_quotation_Amount < GuidePrice_DownF){
                if(contractType == '新品合同') {
                    estimatePriceRange = '低于最低价格';
                } else if(contractType == '首签合同') {
                    if( consumptionRateForecast > 100) { //zzm 20240118 价格范围bug
                        estimatePriceRange = '低于最低价格,预测消费率在100%以上';
                    } else {
                        estimatePriceRange = '低于最低价格,预测消费率在100%以内';     
                    }
                } else {
                    if(costrateForecast>100) { //zzm 20240118 价格范围bug
                        estimatePriceRange = '低于最低价格,预测成本率在100%以上';
                    } else {
                        estimatePriceRange = '低于最低价格,预测成本率在100%以内';
                    }
                }
                
            } else {
                if( Request_quotation_Amount >= GuidePrice_DownF && Request_quotation_Amount <= GuidePrice_UpF){
                    estimatePriceRange = '标准价格的范围内';
                } else {
                    if(Request_quotation_Amount <= GuidePrice_UpF * 2){
                        estimatePriceRange = '最高价格的200%以内';
                    } else{
                        estimatePriceRange = '最高价格的200%以上';
                    }

                }
            } 

            if(estimatePriceRange == '标准价格的范围内') {
                contractPriceType = '标准价格范围内-终批人营业经理';
            } else {
                if(estimatePriceRange.contains('以内')) {
                    contractPriceType = '特价范围-终批人服务总监';
                } else {
                     contractPriceType = '特价范围-终批人总经理';
                }
            }

            //更新打包合同的cl3 4 5 6 
            User loginUser = [SELECT Id, Name, JingliApprovalManager__c, BuchangApprovalManager__c, ZongjianApprovalManager__c, TongkuoZongjian__c FROM User WHERE Id = :UserInfo.getUserId()];
            mcpe.JingliApprovalManager__c = loginUser.JingliApprovalManager__c == null ? loginUser.Id : loginUser.JingliApprovalManager__c;
            mcpe.BuchangApprovalManager__c = loginUser.BuchangApprovalManager__c == null ? loginUser.Id : loginUser.BuchangApprovalManager__c;
            mcpe.ZongjianApprovalManager__c = loginUser.ZongjianApprovalManager__c == null ? loginUser.Id : loginUser.ZongjianApprovalManager__c;
             if(mceSelectList.size()>0) {
                mcpe.SalesDepartment__c = mceSelectList[0].SalesDepartment__c;
            }

            mcpe.TKZongjianApprovalManager__c = loginUser.TongkuoZongjian__c == null ? loginUser.Id : loginUser.TongkuoZongjian__c;
            
            mcpe.Estimate_Price_range__c = estimatePriceRange;
            
            mcpe.ContractPriceType__c = contractPriceType;
            


            //用的报价上的合同总金额字段进行计算
            // mcpe.Contract_Amount__c = contractAmount;
            
            mcpe.New_Contract_Type_TxT__c = contractType;
            

            List<MaintanceContractPackEstimate__c> mcpeUpdateList = [Select Id,Decide__c,Maintenance_Contract_Estimate__c from MaintanceContractPackEstimate__c where MaintanceContractPack__c =:recordId];             
            List<MaintanceContractPackEstimate__c> IsSyncingList = [Select Id,Decide__c,Maintenance_Contract_Estimate__c from MaintanceContractPackEstimate__c where MaintanceContractPack__c =:recordId and Decide__c=true];             

            List<Maintenance_Contract_Estimate__c> mceAllLists = [Select Id
                    from Maintenance_Contract_Estimate__c 
                    where Maintenance_Contract__c in (Select Id from Maintenance_Contract__c  where MaintanceContractPack__c = :recordId) order by Maintenance_Contract__r.Id];
            
            if(isDecide) {
                //报价decide时，更新经销商
                mcp.old_Is_RecognitionModel__c = old_Is_RecognitionModel;
                mcp.Dealer__c = Dealer;
                //当前报价decide改为true,把其它组合的decide状态改为false;
                //只要有decide的组合，其它的报价组合同期都为false
                for(MaintanceContractPackEstimate__c mcpeOther : mcpeUpdateList) {
                    mcpeOther.Decide__c = false;
                    mcpeOther.IsSyncing__c = false;
                }
                mcpe.Decide__c =true;
                mcpe.IsSyncing__c =true;

                //当前报价组合选中的小合同报价decide状态改为true,其它合同报价状态的改为false
                for(Maintenance_Contract_Estimate__c mce : mceAllLists) {
                    mce.McpDecide__c = false;
                }
                //选中的报价组合里的报价为true;
                for(Maintenance_Contract_Estimate__c mce : mceSelectList){
                    mce.McpDecide__c =true;
                }
                //decide时，同步更新大合同相关的字段
                mcp.Limit_Price_Amount__c = Limit_Price_Amount;
                // mcp.Contract_Amount__c = Contract_Amount;
                mcp.GuidePrice_DownF__c = GuidePrice_DownF;
                mcp.GuidePrice_UpF__c = GuidePrice_UpF;  
                mcp.FieldRequest_quotation_Amount__c = Request_quotation_Amount;
                mcp.Consumption_rate_Forecast__c = consumptionRateForecast;
                mcp.Cost_rate_Forecast__c = costrateForecast;
                mcp.Estimate_Price_range__c = estimatePriceRange;
                mcp.ContractPriceType__c = contractPriceType;
                mcp.Contract_Amount__c = contractAmount;
                mcp.New_Contract_Type_TxT__c = contractType;
                mcp.Total_Contract_Price__c = Total_Contract_Price;
                //最新确认的报价组合
                mcp.Estimation_Id__c = mcpeId;
                mcp.Estimate_Asset_Cnt__c = Estimate_Asset_Cnt;
                mcp.Asset_Repair_Sum_PriceF__c = Asset_Repair_Sum_PriceF;
                // mcp.Sum_repair_price__C = Sum_repair_price; //Sum_repair_price__c合同期间修理金额--数据来源接口？
                mcp.Repair_Cost_Sum__c = Repair_Cost_Sum;
                //合同消费率的计算公式IF(Contract_Amount__c=0,0,Sum_repair_price_new__c / Contract_Amount__c)
                if(contractAmount==0) {
                    Usage_ratio_New = 0;
                } else {
                    Usage_ratio_New = (Sum_repair_price/contractAmount) * 100;
                }
                // mcp.Usage_ratio_New__c = Usage_ratio_New;
                //消费率(每月实时) 计算公式
                //IF(Management_Code__c = 'SH-RS-FJ0054009', 0.3535, 
                    //if(contractAmountForRate__c=0,0,
                        //if(RecordType.DeveloperName = 'VM_Contract',
                        //((currentTotalRepairAmount__c + previousTotalRepairAmount__c )/(GuaranteePrice_Amount__c*1.13)),
                        //(currentTotalRepairAmount__c + previousTotalRepairAmount__c )/contractAmountForRate__c)))


            } else {
                mcpe.Decide__c = false;
                //编辑decide状态为false时，需要把decide为true相关的合同报价状态改为true
                if(String.isNotBlank(mcpeId)) {
                    for(Maintenance_Contract_Estimate__c mce : mceAllLists) {
                        mce.McpDecide__c = false;
                    }
                    List<MaintanceContractPackEstimate__c> mcpeSelect = [Select Maintenance_Contract_Estimate__c from MaintanceContractPackEstimate__c where MaintanceContractPack__c = :recordId and id != :mcpeId and Decide__c=true limit 1];
                    if(mcpeSelect.size()>0) {
                        List<String> mceOtherIds = mcpeSelect[0].Maintenance_Contract_Estimate__c.split(',');
                        mceOther = [Select Id,name from Maintenance_Contract_Estimate__c where Name in :mceOtherIds];
                        for(Maintenance_Contract_Estimate__c mce : mceOther) {
                            mce.McpDecide__c = true;
                        }
                    }else {
                        mcp.Estimation_Id__c = null;
                    }

                }

                //如果没有decide的报价组合，当前编辑或新建的报价组合就为同期
                
                if(IsSyncingList.size()== 0) {
                    for(MaintanceContractPackEstimate__c mcpeOther : mcpeUpdateList) {
                        mcpeOther.IsSyncing__c = false;
                    }
                    mcpe.IsSyncing__c =true;
                }
            }

           
            //计算【相对标准价格范围的折扣率-Service_discount_Rate__c】
            // 1) 标准价格范围内时，结果为0;
            // 2) 比标准价格低时，结果是1-希望价格/标准价的最低价格
            // 3) 比标准价格高时，结果是1-希望价格/标准价的最高价格
            if(Request_quotation_Amount<GuidePrice_DownF) {
                Service_discount_Rate = (1-Request_quotation_Amount/GuidePrice_DownF)*100;

            }else if( Request_quotation_Amount >= GuidePrice_DownF && Request_quotation_Amount <= GuidePrice_UpF){
                Service_discount_Rate = 0;
            } else {
                Service_discount_Rate = (1-Request_quotation_Amount/GuidePrice_UpF)*100;
            }
            mcpe.Service_discount_Rate__c = Service_discount_Rate;

            if(mcpeUpdateList.size()>0) {
                update mcpeUpdateList;
            }
            if(mceAllLists.size()>0){
                update mceAllLists;
            }
            if(mceSelectList.size()>0) {
                update mceSelectList;
            }
            if(mceOther.size()>0) {
                update mceOther;
            }
            
            update mcp;
            System.debug(mcpeId);
            if(String.isNotBlank(mcpeId) && mcpeId!=null) {
                mcpe.Id = mcpeId;
                update mcpe;
            } else {
                INSERT mcpe;
            }
            returnData.mcpeId = mcpe.Id;
            returnData.result = '1';

            return returnData;
        }catch(Exception e){
            system.debug('Exception from update mcp:'+e.getMessage());
            returnData.result = e.getMessage();
            Database.rollback(sp);
            return returnData;
        }  
    }
    //服务合同打包-提交待审批
    @AuraEnabled
    public static String mcpAprroval(String recordId, List<String> mceIds,String mcpeReson,String mcpeId,Boolean isDecide,String consumptionRateSolution){
        SaveReturnData saveResult = save(recordId,mceIds,mcpeReson,mcpeId,isDecide,consumptionRateSolution);

        if(String.isBlank(mcpeId)) {
            if(saveResult.result == '1') {
                mcpeId = saveResult.mcpeId;
            } else {
                return saveResult.result;
            }
        }

        //当前服务合同(是否存在报价decide的情况)
        List<Maintenance_Contract__c> mcList = [Select Id,Name,Decided_Estimation__c from Maintenance_Contract__c 
                                                    where MaintanceContractPack__c = :recordId];
        for(Maintenance_Contract__c mc :mcList) {
            if(mc.Decided_Estimation__c !=null) {
                return mc.Name+':报价已经decide，请先取消decide,再提交审批！ \n';
            }
        } 
        //提交审批时，提交时，更新 是否使用上一期维修合同首次报价日
        Date mon1stDate = Date.newInstance(Date.today().year(), Date.today().month(), 1);
        Map<id, Maintenance_Contract__c> mcUpdateList = new Map<id, Maintenance_Contract__c>();
        List<Maintenance_Contract_Asset_Estimate__c> mcaeList = [Select Id,
        Asset__r.Id,
        Asset__r.CurrentContract_F__r.Id,
        Asset__r.CurrentContract_F__r.Contract_End_Date__c,
        Asset__r.CurrentContract_F__r.First_Estimate_Date__c,
        Asset__r.CurrentContract_F__r.Contract_Consumption_rate__c,
        ifHaveleftInPrevious__c 
        from Maintenance_Contract_Asset_Estimate__c 
        where Maintenance_Contract_Estimate__r.Name in :mceIds and  Asset__r.CurrentContract_F__c !=null];
        for(Maintenance_Contract_Asset_Estimate__c mcae:mcaeList) {
            Maintenance_Contract__c mctemp = new Maintenance_Contract__c();
            if (mcae.Asset__r.CurrentContract_F__r.Contract_End_Date__c >= mon1stDate) {
                if (mcae.Asset__r.CurrentContract_F__r.First_Estimate_Date__c == null) {
                    mctemp.Id = mcae.Asset__r.CurrentContract_F__c;
                    mctemp.First_contract_usage_Rate__c = mcae.Asset__r.CurrentContract_F__r.Contract_Consumption_rate__c;
                    mctemp.First_Estimate_Date__c = Date.today();
                    mcUpdateList.put(mctemp.Id, mctemp);
                    mcae.ifHaveleftInPrevious__c = true;
                }
            }
        }
        if(mcaeList.size()>0) {
            update mcaeList;
        }
        if(mcUpdateList.size()>0) {
            update  mcUpdateList.values();
        }
        
        //小合同报价的原有逻辑
        // if (isApproval) {
        //                 Maintenance_Contract__c mctemp = new Maintenance_Contract__c();
        //                 //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , '+++++ ' + ass.rec.CurrentContract_F__r.Contract_End_Date__c + '   ' + mon1stDate));
        //                 // 因为月初计算消费率，所以结束日在上月或以前，可以取到完整消费率，否则保存首次报价日
        //                 if (input.rec.CurrentContract_F__r.Contract_End_Date__c >= mon1stDate) {
        //                     if (input.rec.CurrentContract_F__r.First_Estimate_Date__c == null) {
        //                         mctemp.Id = input.rec.CurrentContract_F__c;
        //                         mctemp.First_contract_usage_Rate__c = input.rec.CurrentContract_F__r.Contract_Consumption_rate__c;
        //                         mctemp.First_Estimate_Date__c = Date.today();
        //                         mcList.put(mctemp.Id, mctemp);
        //                         input.mcae.ifHaveleftInPrevious__c = true;
        //                     }
        //                 }
        //             }   

        try{
            Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
            psr.setObjectId(mcpeId);
            Approval.ProcessResult submitResult = Approval.process(psr);
            return '1';
           
        }catch(exception e){
            return e.getMessage();
        } 

    }
    public class InitData {
        @AuraEnabled
        public String mcId ;
        @AuraEnabled
        public String mcName ;
        @AuraEnabled
        public String mcpeId ;
         @AuraEnabled
        public String mceIds ;
        @AuraEnabled
        public String mcpeReson ;
        @AuraEnabled
        public Boolean isMcpeDecide ;
        @AuraEnabled
        public String processStatus ;
         @AuraEnabled
        public String consumptionRateSolution ;
        @AuraEnabled
        public List<Maintenance_Contract_Estimate__c> mceList;
    }
    public class SaveReturnData {
        @AuraEnabled
        public String mcpeId ;
        @AuraEnabled
        public String result ;
    }

   
}