public with sharing class lexToAddMaintenanceContractController {
    @AuraEnabled
    public static String canAddMc(String recordId) {
        List<MaintanceContractPackEstimate__c> mcpeList = [Select Id  from MaintanceContractPackEstimate__c Where MaintanceContractPack__c = :recordId and Decide__c =true limit 1];
        if(mcpeList.size()>0) {
            return '2'; //有decide的报价组合之后，不能添加小合同
        } else {
            List<MaintanceContractPackEstimate__c> mcpeStatusList = 
            [Select Id  from MaintanceContractPackEstimate__c Where MaintanceContractPack__c = :recordId and ( Process_Status__c='申请中' OR  Process_Status__c='批准' )  limit 1];
            if(mcpeStatusList.size()>0) { //有不是草案中的报价组合，提示重新做报价
                return '3';
            }
            
        }
        return '1';
    }
    //zzm 20231026 start
    @AuraEnabled
    public static String getContractType(String recordId) {
        List<MaintanceContractPack__c> mcpList = [Select Id,Contract_Type__c From MaintanceContractPack__c Where Id = :recordId];
        if(mcpList.size()>0) {
            return mcpList[0].Contract_Type__c;
        } else {
            return '1';
        }
    }
    //zzm 20231026 end

    @AuraEnabled
    public static McInfoList init(String recordId,String contractType) {
        McInfoList mcInfoList = new McInfoList();
        if(String.isNotBlank(contractType)) {
            contractType = EncodingUtil.urlDecode(contractType,'UTF-8');
        }
        String status = '引合中';
        mcInfoList.selectedMcLists = [SELECT Id,Management_Code__c, Name, Hospital__c,Hospital__r.Name,Service_Contract_Staff__c,Service_Contract_Staff__r.Name FROM Maintenance_Contract__c Where MaintanceContractPack__c = :recordId ];
        mcInfoList.allMcLists = [SELECT Id,Management_Code__c, Name, Hospital__c,Hospital__r.Name,Service_Contract_Staff__c ,Service_Contract_Staff__r.Name FROM Maintenance_Contract__c Where MaintanceContractPack__c =null And Status__c = :status And Contract_Type__c = :contractType Limit 50];
        return mcInfoList;
    }

    //搜索
    @AuraEnabled
    public static List<Maintenance_Contract__c> searchMc(String txt, String con, String val, String contractType,String searchHospital) {
        if(String.isNotBlank(contractType)) {
            contractType = EncodingUtil.urlDecode(contractType,'UTF-8');
        }
        return getMaintenanceContract(txt,con,val,contractType,searchHospital);
    }

    //检索验证
    private static List<Maintenance_Contract__c> getMaintenanceContract(String txt, String con, String val, String contractType,String searchHospital) {
        String soql = 'SELECT Id,Management_Code__c, Name, Hospital__c,Hospital__r.Name,Service_Contract_Staff__c,Service_Contract_Staff__r.Name FROM Maintenance_Contract__c where MaintanceContractPack__c =null And Status__c =\'' +'引合中' + '\'';
        if(String.isNotBlank(contractType)) {
            soql += ' and Contract_Type__c= \'' +contractType +'\'';
        }
        if(String.isNotBlank(val)){
            soql += ' and ' ;
            soql += makeTextSql(txt, con, val);
        }
        if(String.isNotBlank(searchHospital)){
            
            soql += ' and Hospital__c= :searchHospital' ;
        }
        soql += ' limit 50';
        // if(String.isBlank(val)) {
            // soql += ' Contract_Type__c= \''+contractType + '\'  limit 50';
        // } else {
        //     soql += makeTextSql(txt, con, val);
        //     soql += ' and Contract_Type__c= \''+contractType + '\' limit 50';
        // }

        // if(String.isBlank(val)) {
        //     soql += ' Contract_Type__c= '+contractType +  ' limit 50';
        // } else {
        //     soql += makeTextSql(txt, con, val);
        //     soql += ' and Contract_Type__c= '+contractType +  ' limit 50';
        //     // soql += ' and Contract_Type__c= \''+contractType + '\' limit 50';
        // }

        // system.debug('=======search soql:' +makeTextSql(txt, con, val));
        
        system.debug('====getAssetconfim:' + soql);
        return Database.query(soql);
    }
    // 拼接检索条件sql文
    private static String makeTextSql(String txt1, String con, String val) {
        String soql = '';
        if (String.isBlank(con)) {
            con = 'equals';
        }
        if (!String.isBlank(txt1)) {
            if ((con == 'contains' || con == 'notcontains') && val.contains(' ')) {
                String[] vals = val.split(' ');
    
                String cSql = '';
                if (vals.size() > 0) {
                    String txt = txt1.substring(2);
                    soql += '  ( ';
                    for (String v : vals) {
                        if (String.isNotBlank(v)) {
                            if (con == 'contains') {
                                soql += txt + ' like \'%' + v + '%\' or ';
                            } else {
                                soql += txt + ' not like \'%' + v + '%\' and ';
                            }
                        }
    
    
                    }
                    soql = soql.substring(0, soql.length() - 4);
                    soql += ')';
                }
                system.debug('containssoql:     ' + soql);
            } else if ((con == 'equals' || con == 'notequals') && val.contains(',')) {
                String[] vals = val.split(',');
                if (vals.size() > 0) {
                    String txt = txt1.substring(2);           
                    soql += '  ( ';
                    for (String v : vals) {
                        if (con == 'equals') {
                            soql += txt + ' = \'' + v + '\' or ';
                        } else {
                            // notequals
                            soql += txt + ' <> \'' + v + '\' and ';
                        }
                    }
                    soql = soql.substring(0, soql.length() - 4);
                    soql += ')';
                }
            } else {
                String cSql = makeTextSqlStr(txt1, con, val);
                if (con != 'notcontains') {
                    soql += makeTextSqlStr(txt1, con, val);
                } else {
                    // notcontains
                    if (!String.isBlank(cSql)) {
                        cSql = cSql.substring(5);               
                        soql += '  (NOT ' + cSql + ') ';
                    }
                }
            }
        }
        return soql;
    }
    private static String makeTextSqlStr(String txt1, String con, String val) {
        String soql = '';
        if (!String.isBlank(txt1)) {
            String txt = txt1.substring(2);
            String colType = txt1.substring(0, 2);
            String tmpVal = val.trim();
            // 空白の場合''にする
            if (String.isBlank(tmpVal)) {
                if (con == 'equals') {
                    //soql += ' and ' + txt + ' = ' + tmpVal;
                    soql += '  ' + txt + ' = null';
                } else if (con == 'notequals') {
                    soql += '  ' + txt + ' <> null';
                } else {
                    // 空白の場合、contains, notcontains と starts withは無視
                }
            } else {
                soql += '  ' + txt;
                if (con == 'equals') {
                    if (colType == 'S:') {
                        soql += ' = \'' + tmpVal + '\'';
                    } else {
                        soql += ' = ' + tmpVal + ' ';
                    }
                } else if (con == 'notequals') {
                    if (colType == 'S:') {
                        soql += ' <> \'' + tmpVal + '\'';
                    } else {
                        soql += ' <> ' + tmpVal + ' ';
                    }
                } else if (con == 'contains' || con == 'notcontains') {
                    soql += ' like \'%' + String.escapeSingleQuotes(tmpVal.replaceAll('%', '\\%')) + '%\'';
                } else if (con == 'starts with') {
                    soql += ' like \'' + String.escapeSingleQuotes(tmpVal.replaceAll('%', '\\%')) + '%\'';
                } else {
                    if (colType == 'S:') {
                        soql += ' ' + con + '\'' + tmpVal + '\'';
                    } else {
                        soql += ' ' + con + ' ' + tmpVal + ' ';
                    }
                }
            }
        }
        return soql;
    }
    //添加进打包合同
    @AuraEnabled
    public static String exchangeMc(List<String> selectedMcs,String recordId) {
        List<Maintenance_Contract__c> oldMcs = [SELECT Id,Management_Code__c, Name FROM Maintenance_Contract__c Where MaintanceContractPack__c = :recordId ];
        
        List<Maintenance_Contract__c> upMcList = new List<Maintenance_Contract__c>();
        if(selectedMcs !=null && selectedMcs.size()>0) {
            for(Maintenance_Contract__c mc:oldMcs) {
                if(!selectedMcs.contains(mc.Id)){
                    mc.MaintanceContractPack__c = null;
                    upMcList.add(mc);
                } 
            }
            for(String mcId : selectedMcs) {
                Maintenance_Contract__c mcObj = new Maintenance_Contract__c();
                mcObj.Id = mcId;
                mcObj.MaintanceContractPack__c = recordId;
                upMcList.add(mcObj);                
            }             
        } else {
            for(Maintenance_Contract__c mc:oldMcs) {
                mc.MaintanceContractPack__c = null;
                upMcList.add(mc);
            }
        }
        try{ 
            //加先款经销商名
            String SalesOfficeCode_selection = null;
            MaintanceContractPack__c mcp = new MaintanceContractPack__c();  
            mcp.Id = recordId;
            List<MaintanceContractPack__c> mcpList = [Select Id from MaintanceContractPack__c where ID= :recordId]; 
            if (upMcList.size()>0) {
                List<Maintenance_Contract__c> selectedMcsInfo = [Select Id ,SalesOfficeCode_selection__c from Maintenance_Contract__c Where id in :selectedMcs limit 1];
                if(selectedMcsInfo.size()>0 && mcpList.size()>0) {
                    SalesOfficeCode_selection = selectedMcsInfo[0].SalesOfficeCode_selection__c;
                }
               
                // mcp.SalesOfficeCode_selection__c = SalesOfficeCode_selection;

                update upMcList;
                update mcp;
                // String updateColunmRes = updateColunm(recordId);
                // system.debug('大合同金额更新结果：'+updateColunmRes);
               
            } 
            return '1';
            // else {
            //     return '请选择维修合同！';
            // }
        }catch(exception e){
            return e.getMessage();
            // return e.getDmlMessage(0);
        }
    }
    //zzm 20231026 start
    //更新报价的上期合同信息
    @AuraEnabled
    public static String updateLastMc(String recordId) {
        String lastMcStr = '999'; //zzm 20231121 上期合同信息bug修复
        try{
            String reportId = '';
            List<Report> reportList = [select Id from Report where  DeveloperName ='Repair_Contract_Repair_Fault' limit 1];
            if(reportList.size()>0) {
                reportId = reportList[0].Id;
            }
            List<String> mcLastIds = new List<String>();
            // MaintanceContractPack__c mcp = [select id,name from MaintanceContractPack__c where Estimation_Id__r.id =:recordId];
            MaintanceContractPackEstimate__c mcpe = [select id,name,MaintanceContractPack__c from MaintanceContractPackEstimate__c where Id =:recordId];
            List<Maintenance_Contract__c> mcList = [select id,Name,LastMContract1_NO__c,LastMContract2_NO__c,LastMContract3_NO__c,LastMContract4_NO__c,LastMContract5_NO__c from Maintenance_Contract__c where MaintanceContractPack__c=:mcpe.MaintanceContractPack__c];
            for(Maintenance_Contract__c mc:mcList) {
                if(String.isNotBlank(mc.LastMContract1_NO__c)) {
                    mcLastIds.add(mc.LastMContract1_NO__c);
                }
                if(String.isNotBlank(mc.LastMContract2_NO__c)) {
                    mcLastIds.add(mc.LastMContract2_NO__c);
                }
                if(String.isNotBlank(mc.LastMContract3_NO__c)) {
                    mcLastIds.add(mc.LastMContract3_NO__c);
                }
                if(String.isNotBlank(mc.LastMContract4_NO__c)) {
                    mcLastIds.add(mc.LastMContract4_NO__c);
                }
                if(String.isNotBlank(mc.LastMContract5_NO__c)) {
                    mcLastIds.add(mc.LastMContract5_NO__c);
                }
            }
            if(mcLastIds.size()>0) {
                lastMcStr = String.join(mcLastIds, ',');
            }
            String url = '/lightning/r/Report/' + reportId+'/view?fv0='+lastMcStr;
            System.debug('url:'+url);
            return url;
        } catch (exception e){
            return '2';
        }        
    }
    //打包报价 -过去三年修理实绩 
    @AuraEnabled
    public static String initDBPast2YearsRepairPriceRep(String recordId){
        try {
            String reportId = '';
            List<Report> reportList = [select Id from Report where DeveloperName ='Last2YearsRepairPrice3' limit 1];
            if(reportList.size()>0) {
                reportId = reportList[0].Id;
            }
           
            String mCEName = [select Maintenance_Contract_Estimate__c from MaintanceContractPackEstimate__c where Id = :recordId].Maintenance_Contract_Estimate__c;
            String url = '/lightning/r/Report/' + reportId+'/view?fv0='+mCEName;

            return url;
        }
        catch (exception e) {
            return '2';
        }    
        
    }
    //打包报价 -编辑按钮覆盖
    @AuraEnabled
    public static String initToAmpApprovalEdit(String recordId){
        try {
            MaintanceContractPackEstimate__c mcpe = [select Id,MaintanceContractPack__c from MaintanceContractPackEstimate__c where Id = :recordId];
            String url = '/apex/toMcpApproval?id='+mcpe.MaintanceContractPack__c+'&mcpeId=' +mcpe.Id;
            return url;
        }
        catch (exception e) {
            return '2';
        }    
        
    }
    //zzm 20231026 end
    // private static String updateColunm(String recordId){
    //     //当前维修合同
    //    List<Maintenance_Contract__c> mcList = [Select Id,Submit_contract_to_Financial_dept__c,HP_Dealer_print__c,Contract_print_completed__c,OCM_Print_request__c,GuidePrice_DownF__c,GuidePrice_UpF__c,Request_quotation_AmountF__c,
    //                                             Contract_Start_Date__c,
    //                                             Contract_End_Date__c,
    //                                             Limit_Price_Amount__c,
    //                                             Total_Contract_Price__c,
    //                                             Contract_Amount__c from Maintenance_Contract__c 
    //                                                 where MaintanceContractPack__c = :recordId];
    //      MaintanceContractPack__c mcp = new MaintanceContractPack__c();
    //      mcp.id = recordId;
    //      Decimal GuidePrice_DownF = 0;
    //      Decimal GuidePrice_UpF = 0;
    //      Decimal FieldRequest_quotation_Amount = 0;
    //      Decimal Limit_Price_Amount = 0;
    //      Decimal Contract_Amount = 0;
    //      Decimal Total_Contract_Price = 0;
      
    //      for ( Maintenance_Contract__c mc :mcList) {
    //         //增加上限金额汇总
    //         if (mc.Limit_Price_Amount__c !=null) {
    //             Limit_Price_Amount += mc.Limit_Price_Amount__c;
    //         }
    //         if (mc.GuidePrice_DownF__c !=null) {
    //             GuidePrice_DownF += mc.GuidePrice_DownF__c;
    //         }
    //         if (mc.GuidePrice_UpF__c !=null) {
    //             GuidePrice_UpF += mc.GuidePrice_UpF__c;
    //         }    
    //         if (mc.Request_quotation_AmountF__c!=null) {
    //             FieldRequest_quotation_Amount += mc.Request_quotation_AmountF__c; 
    //         }
    //         if (mc.Contract_Amount__c!=null) {
    //             Contract_Amount += mc.Contract_Amount__c; 
    //         }
    //         //合同定价总额
    //         if (mc.Total_Contract_Price__c!=null) {
    //             Total_Contract_Price += mc.Total_Contract_Price__c; 
    //         }
         
    //     }
    //     mcp.Limit_Price_Amount__c = Limit_Price_Amount; 
    //     mcp.GuidePrice_DownF__c = GuidePrice_DownF; 
    //     mcp.GuidePrice_UpF__c = GuidePrice_UpF; 
    //     mcp.FieldRequest_quotation_Amount__c = FieldRequest_quotation_Amount;
    //     mcp.Contract_Amount__c = Contract_Amount;
    //     mcp.Total_Contract_Price__c = Total_Contract_Price;
    //     update mcp;
    //     try{
    //        update mcp;
    //        return '1';
    //     }catch(exception e){
    //         return e.getMessage();
    //     }
       
    // }
    //zzm 20231026 start
    //合同复核初始化
    @AuraEnabled
    public static McpPreInfo initMcpPreSubmit(String recordId) {
        McpPreInfo mcpPre = new McpPreInfo();
        try {
            MaintanceContractPack__c mcp =[ SElECT 
                Id,
                Name,
                Estimation_Id__c,
                OCM_Print_request__c,
                HP_Dealer_print__c,
                Contract_print_completed__c,
                Submit_contract_to_Financial_dept__c,
                Contract_Conclusion_Date__c from MaintanceContractPack__c Where Id =:recordId
            ];
            mcpPre.mcp = mcp;
            // mcpPre.decideEstimationId = mcp.Estimation_Id__c;
            List<MaintanceContractPackEstimate__c> mcpeList = [select Id,Decide__c from MaintanceContractPackEstimate__c where Id=:mcp.Estimation_Id__c and Decide__c=true];
            mcpPre.mcpeList = mcpeList;
            List<Maintenance_Contract__c> mcList = [select Id,Name,Decided_Estimation__c,Status__c,MC_approval_status__c,Is_Recognition_Model_True__c,Contract_print_completed__c,Contract_quotation_or_not__c,Maintenance_Contract_No__c,upload_to_sap_time__c,upload_to_RM_time__c,old_Is_RecognitionModel__c,Payment_Plan_Sum_First__c from Maintenance_Contract__c where MaintanceContractPack__c=:recordId]; 
            mcpPre.mcList = mcList;
        }
        catch (Exception e) {
            System.debug(e.getMessage());
        }
        return mcpPre;
       
    }
    //更新大合同日期到小合同
    @AuraEnabled
    public static String updateMcDate(String recordId) {
        try {
            
            MaintanceContractPack__c mcp =[ SElECT 
                    Id,
                    Name,
                    Estimation_Id__c,
                    OCM_Print_request__c,
                    HP_Dealer_print__c,
                    Contract_print_completed__c,
                    Submit_contract_to_Financial_dept__c,
                    Contract_Conclusion_Date__c from MaintanceContractPack__c Where Id =:recordId
            ];
            List<Maintenance_Contract__c> mcList = [select Id,Name,Decided_Estimation__c,Status__c,MC_approval_status__c,Is_Recognition_Model_True__c,Contract_print_completed__c,Contract_quotation_or_not__c,Maintenance_Contract_No__c,upload_to_sap_time__c,upload_to_RM_time__c,old_Is_RecognitionModel__c,Payment_Plan_Sum_First__c from Maintenance_Contract__c where MaintanceContractPack__c=:recordId]; 
            for(Maintenance_Contract__c mc:mcList) {
                mc.OCM_Print_request__c = mcp.OCM_Print_request__c;
                mc.HP_Dealer_print__c = mcp.HP_Dealer_print__c;
                mc.Contract_print_completed__c = mcp.Contract_print_completed__c;
                mc.Submit_contract_to_Financial_dept__c = mcp.Submit_contract_to_Financial_dept__c;
                mc.Contract_Conclusion_Date__c = mcp.Contract_Conclusion_Date__c;
            }
            if(mcList.size()>0){
                update mcList;
            } 
            return '1';
        }
        catch (Exception e) {
            return '2';
        }
       
    }
    // //打包合同合同复核审批流
    // @AuraEnabled
    // public static String preSubmitMcp(String recordId) {
    //     try{
    //         Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
    //         psr.setObjectId(recordId);
    //         Approval.ProcessResult submitResult = Approval.process(psr);
    //         return '1';
           
    //     }catch(exception e){
    //         return e.getMessage();
    //     } 
    // }
    //初始化上传认款合同
    @AuraEnabled
    public static List<Maintenance_Contract__c> initUploadToRecognition(String recordId) {
        List<Maintenance_Contract__c> mcList = [select Id,Name,Decided_Estimation__c,Contract_quotation_or_not__c,Maintenance_Contract_No__c,upload_to_sap_time__c,upload_to_RM_time__c,old_Is_RecognitionModel__c,Payment_Plan_Sum_First__c from Maintenance_Contract__c where MaintanceContractPack__c=:recordId];
        return mcList;
    }
    //zzm 20231026 end


    public class McInfoList {
        @AuraEnabled
        public List<Maintenance_Contract__c> allMcLists;
        @AuraEnabled
        public List<Maintenance_Contract__c> selectedMcLists;
    }
    
    //zzm 20231026 start
    public class McpPreInfo{
        @AuraEnabled
        public MaintanceContractPack__c mcp;
        // @AuraEnabled
        // public String decideEstimationId;
        @AuraEnabled
        public List<MaintanceContractPackEstimate__c> mcpeList;
        @AuraEnabled
        public Boolean decideEstimationFlag;
        @AuraEnabled
        public List<Maintenance_Contract__c> mcList;
    }
    //zzm 20231026 end

    
}