/**
 * 2024-1-9 create sx
 * 邮件通用类
 * */
public with sharing class SendEmailUtil {
    public SendEmailUtil() {
        
    }

    //贸易合规二期邮件模版
    /**
     * status 警示/黑名单,冻结
     * toEmailList to邮箱地址
     * ccEmailList cc邮箱地址
     * rentalId 备品借出申请单Id
     * stepName 操作步骤
     * assetList 保有设备list
     * raesdList 备品明细
     * */
    @AuraEnabled
    public static void tradeTempleSend(String rentalId, String stepName, List<String> assetList, List<String> raesdList){

        //判断是否是测试环境
        Boolean isSandboxBoolean = isSandbox();
        /** 查询申请单相关邮箱 
         *  备品中心邮件地址
         *  医院名,医院贸易合规状态,操作者邮箱
         * */
        List<Rental_Apply__c> currentRentalList = [Select Id, Name, RA_Status__c, Loaner_centre_mail_address__c, Hospital__r.Name, Hospital__r.TradeComplianceStatus__c,
                                        applyUser__r.Email
                                        FROM Rental_Apply__c WHERE Id = :rentalId];

        Rental_Apply__c currentRental = new Rental_Apply__c();

        if(currentRentalList.size()>0){
            currentRental = currentRentalList[0];
        }

        //获取精琢邮箱
        String jzEmail = System.Label.JZ_VALIDAE_EMAIL;
        List<String> jzEmailList = new List<String>();
        if(jzEmail != null || jzEmail != ''){
            jzEmailList = jzEmail.split(';');
        }

        //违规的明细一览
        List<Rental_Apply_Equipment_Set_Detail__c> engleRentalDetailList = new List<Rental_Apply_Equipment_Set_Detail__c>();

        if(raesdList != null && raesdList.size() > 0){
            engleRentalDetailList = [SELECT Id, Name, Asset__r.Name, Asset__r.SerialNumber, Asset__r.Product2.ProTradeComplianceStatus__c, Rental_Apply__c, Rental_Apply__r.Name FROM Rental_Apply_Equipment_Set_Detail__c WHERE Id IN : raesdList];
        }

        //分配时候只涉及产品的显示
        List<Asset> engleAsset = new List<Asset>();
        if(assetList!= null && assetList.size()>0){
            engleAsset = [SELECT Id, Product_Name__c, SerialNumber From Asset WHERE Id IN : assetList];
        }

        //申请人, 审批人
        Set<String> submitPesronSet = new Set<String>();
        Set<String> approvalPersonSet = new Set<String>();

        // 法务邮箱
        String lawPerson = System.Label.LegalDepartmentEmail;
        try{
            //审批流
            List<ProcessInstanceStep> steps =  [SELECT Id, StepStatus, ProcessInstance.TargetObjectId, ProcessInstance.SubmittedBy.Email, Actor.Email,CreatedDate
                                                FROM ProcessInstanceStep
                                                WHERE ProcessInstance.TargetObjectId = :rentalId
                                                ORDER BY CreatedDate ASC];
            if(steps.size() > 0){
                for(ProcessInstanceStep instans :steps){
                    submitPesronSet.add(instans.ProcessInstance.SubmittedBy.Email);
                    approvalPersonSet.add(instans.Actor.Email);
                }
            }

            //发送邮件
            List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            //发件人,当前操作人
            List<User> currUser = [SELECT Id, Name, Email, Default_Referable_Apply_Equipment_Center__c
                                    FROM User
                                    WHERE Id = :UserInfo.getUserId()];
            //不同的操作Cc/To的人不一样
            List<String> toAddresses = new List<String>();
            List<String> ccAddresses = new List<String>();
            String subjectString = '';
            String emailBody = '';
            System.debug('currentRental===' + currentRental == null);
            System.debug('stepName===' + stepName);
            //备品申请单 邮件模板

            if(currentRental.Hospital__r.TradeComplianceStatus__c != null && currentRental.Hospital__r.TradeComplianceStatus__c != ''){
                if(currentRental.Hospital__r.TradeComplianceStatus__c == '冻结,人工审批中' || currentRental.Hospital__r.TradeComplianceStatus__c == '黑名单'){
                    //邮件模板
                    subjectString = '【贸易合规】--' + currentRental.Hospital__r.Name + '涉及' + currentRental.Hospital__r.TradeComplianceStatus__c;
                    emailBody += '您好：<br/>';
                    emailBody += currentRental.Hospital__r.Name + '的贸易合规状态为' + currentRental.Hospital__r.TradeComplianceStatus__c + '<br/>';
                    emailBody += '其申请单号：' + currentRental.Name + '的备品借出状态为：' + currentRental.RA_Status__c + '，请确认。<br/>'; 
                    emailBody += '<a href="' + System.Label.Environment_Url + rentalId + '">申请单号链接</a>';

                    /**
                     * 提交待审批 TO申请人、操作者/CC相应北上广的备品中心,法务的人
                     * */
                    if(stepName == '提交待审批'){
                        if(submitPesronSet.size() > 0){
                            for(String submit : submitPesronSet){
                                toAddresses.add(submit);
                            }
                        }
                        if(currentRental.applyUser__r.Email != null && currentRental.applyUser__r.Email != ''){
                            toAddresses.add(currentRental.applyUser__r.Email);
                        }
                        if(currentRental.Loaner_centre_mail_address__c != null && currentRental.Loaner_centre_mail_address__c != ''){
                            //上正式要修改代码，TODO=====
                            System.debug('isSandboxBoolean===' + isSandboxBoolean);
                            if(isSandboxBoolean){
                                ccAddresses.add(currentRental.Loaner_centre_mail_address__c + '.invalid');
                            }else{
                                ccAddresses.add(currentRental.Loaner_centre_mail_address__c);
                            }   
                        }
                        ccAddresses.add(lawPerson);
                        //测试用 start
                        if(System.Label.ComplianceEmailSwitch == 'true'){
                            if(jzEmailList.size()>0){
                                ccAddresses.addAll(jzEmailList);
                            }
                        }
                        //测试用 end
                    }
                    /**
                     * 分配画面  TO相应北上广的备品中心/CC申请人、操作者,法务的人
                     * 出库指示  TO相应北上广的备品中心/CC申请人、操作者,法务的人
                     * 下架      *****
                     * */
                    if(stepName == '分配画面' || stepName == '出库指示' || stepName == '下架' || stepName == '出库前检测' || stepName == '出库' || stepName == '办事处分配' 
                        || stepName == '办事处分配画面' || stepName == '自动分配页面'){
                        if(currentRental.Loaner_centre_mail_address__c != null && currentRental.Loaner_centre_mail_address__c != ''){
                            //上正式要修改代码，TODO=====
                            System.debug('isSandboxBoolean===' + isSandboxBoolean);
                            if(isSandboxBoolean){
                                toAddresses.add(currentRental.Loaner_centre_mail_address__c + '.invalid');
                            }else{
                                toAddresses.add(currentRental.Loaner_centre_mail_address__c);
                            }
                        }
                        //测试用 start
                        if(System.Label.ComplianceEmailSwitch == 'true'){
                            if(jzEmailList.size()>0){
                                ccAddresses.addAll(jzEmailList);
                            }
                        }
                        //测试用 end
                        if(currentRental.applyUser__r.Email != null && currentRental.applyUser__r.Email != ''){
                            ccAddresses.add(currentRental.applyUser__r.Email);
                        }
                        if(submitPesronSet.size() > 0){
                            for(String submit : submitPesronSet){
                                ccAddresses.add(submit);
                            }
                        }
                        if(approvalPersonSet.size() > 0){
                            for(String approval : approvalPersonSet){
                                ccAddresses.add(approval);
                            }
                        }
                        ccAddresses.add(lawPerson);
                    }
                    
                    

                }else if(currentRental.Hospital__r.TradeComplianceStatus__c == '警示名单'){
                    //邮件模板
                    subjectString = '【贸易合规】--' + stepName + '涉及警示产品' ;
                    emailBody += '您好：<br/>';
                    emailBody += currentRental.Hospital__r.Name + '的贸易合规状态为' + currentRental.Hospital__r.TradeComplianceStatus__c + '<br/>';
                    emailBody += '其申请单号：' + currentRental.Name + '的备品借出状态为：' + currentRental.RA_Status__c + '，请确认。<br/>'; 
                    emailBody += '<a href="' + System.Label.Environment_Url + rentalId + '">申请单号链接</a><br/>';
                    System.debug('engleRentalDetailList===' + engleRentalDetailList.size());
                    //备品明细
                    if(engleRentalDetailList.size()>0){ 
                        emailBody += '其申请单号:' + currentRental.Name + '的明细No.为:<br/>';
                        for(Integer i = 0 ; i < engleRentalDetailList.size(); i++){
                            emailBody += i+ 1 + '.' + engleRentalDetailList[i].Name + ' ;保有设备:' + engleRentalDetailList[i].Asset__r.Name + ' ;其机身编码:' + engleRentalDetailList[i].Asset__r.SerialNumber + '<br/>';
                        }
                    }

                    if(engleAsset.size() > 0){
                        emailBody += '涉及到警示产品的保有设备明细为:<br/>';
                        for(Integer i = 0 ; i < engleAsset.size(); i++){
                            emailBody += i+1 + '. 保有设备:' + engleAsset[i].Product_Name__c + ';其机身编码:' + engleAsset[i].SerialNumber + '<br/>';
                        }
                    }

                    /**
                     * 出库指示  TO相应北上广的备品中心 CC抄送申请人、审批人、操作者,法务的人
                     * */
                    if(stepName == '主体分配' || stepName == '附属品选择' || stepName == '附属品追加' || stepName == '出库指示' 
                            || stepName == '下架' || stepName == '出库前检测' || stepName == '出库' || stepName == '发货' || stepName == '办事处分配画面发货' || stepName == '办事处分配画面分配' || stepName == '自动分配页面'){
                        if(currentRental.Loaner_centre_mail_address__c != null && currentRental.Loaner_centre_mail_address__c != ''){
                            //上正式要修改代码，TODO=====
                            if(isSandboxBoolean){
                                toAddresses.add(currentRental.Loaner_centre_mail_address__c + '.invalid');
                            }else{
                                toAddresses.add(currentRental.Loaner_centre_mail_address__c);
                            }
                        }
                        if(currentRental.applyUser__r.Email != null && currentRental.applyUser__r.Email != ''){
                            ccAddresses.add(currentRental.applyUser__r.Email);
                        }
                        if(submitPesronSet.size() > 0){
                            for(String submit : submitPesronSet){
                                ccAddresses.add(submit);
                            }
                        }
                        if(approvalPersonSet.size() > 0){
                            for(String approval : approvalPersonSet){
                                ccAddresses.add(approval);
                            }
                        }
                        ccAddresses.add(lawPerson);
                        //测试用 start
                        if(System.Label.ComplianceEmailSwitch == 'true'){
                            if(jzEmailList.size()>0){
                                ccAddresses.addAll(jzEmailList);
                            }
                        }
                        //测试用 end
                    }
                    
                }
                System.debug('toAddresses==='+ toAddresses);
                System.debug('ccAddresses==='+ ccAddresses);
                mail.setSaveAsActivity(false);
                mail.setToAddresses(toAddresses);
                mail.setCcAddresses(ccAddresses);
                mail.setSubject(subjectString);
                mail.setCharset('UTF-8');
                mail.setHtmlBody(emailBody);
                emails.add(mail);
                Messaging.sendEmail(emails);
            }
            
        }catch(Exception e){
            System.debug('sendTemperatureEmail====' + e.getMessage());
        }

    }

    @AuraEnabled
    public static void tradeConsumTempleSend(String consumlId, String stepName, List<String> assetList, List<String> consumList){
        //判断是否是测试环境
        Boolean isSandboxBoolean = isSandbox();
        //耗材申请单
        List<Consum_Apply__c> currentConsumList = [Select Id, Name, RA_Status__c, Loaner_centre_mail_address__c, Hospital__r.Name, Hospital__r.TradeComplianceStatus__c,
                                        applyUser__r.Email
                                        FROM Consum_Apply__c WHERE Id = :consumlId];
        Consum_Apply__c cunrentConsum = new Consum_Apply__c();
        if(currentConsumList.size() >0){
            cunrentConsum = currentConsumList[0];
        }
        System.debug('cunrentConsum===' + cunrentConsum);
        //获取精琢邮箱
        String jzEmail = System.Label.JZ_VALIDAE_EMAIL;
        List<String> jzEmailList = new List<String>();
        if(jzEmail != null || jzEmail != ''){
            jzEmailList = jzEmail.split(';');
        }
        
        //违规明细
        List<Consum_Apply_Equipment_Set_Detail__c> engleConsumDetailList = new List<Consum_Apply_Equipment_Set_Detail__c>();
        if(consumList != null && consumList.size()>0){
            engleConsumDetailList = [SELECT Id, Name, Asset__r.Name, Asset__r.SerialNumber, Asset__r.Product2.ProTradeComplianceStatus__c, Consum_Apply__c, Consum_Apply__r.Name FROM Consum_Apply_Equipment_Set_Detail__c WHERE Id IN : consumList];
        }

        //分配时候只涉及产品的显示
        List<Asset> engleAsset = new List<Asset>();
        if(assetList!= null && assetList.size()>0){
            engleAsset = [SELECT Id, Product_Name__c, SerialNumber From Asset WHERE Id IN : assetList];
        }

        //申请人, 审批人
        Set<String> submitPesronSet = new Set<String>();
        Set<String> approvalPersonSet = new Set<String>();

        // 法务邮箱
        String lawPerson = System.Label.LegalDepartmentEmail;

        try {
            //审批流
            List<ProcessInstanceStep> steps =  [SELECT Id, StepStatus, ProcessInstance.TargetObjectId, ProcessInstance.SubmittedBy.Email, Actor.Email,CreatedDate
                                                FROM ProcessInstanceStep
                                                WHERE ProcessInstance.TargetObjectId = :consumlId
                                                ORDER BY CreatedDate ASC];
            if(steps.size() > 0){
                for(ProcessInstanceStep instans :steps){
                    submitPesronSet.add(instans.ProcessInstance.SubmittedBy.Email);
                    approvalPersonSet.add(instans.Actor.Email);
                }
            }

            //发送邮件
            List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

            //不同的操作Cc/To的人不一样
            List<String> toAddresses = new List<String>();
            List<String> ccAddresses = new List<String>();
            String subjectString = '';
            String emailBody = '';
            if(cunrentConsum.Hospital__r.TradeComplianceStatus__c != null && cunrentConsum.Hospital__r.TradeComplianceStatus__c != ''){
                if(cunrentConsum.Hospital__r.TradeComplianceStatus__c == '冻结,人工审批中' || cunrentConsum.Hospital__r.TradeComplianceStatus__c == '黑名单'){
                    //邮件模板
                    subjectString = '【贸易合规】--' + cunrentConsum.Hospital__r.Name + '涉及' + cunrentConsum.Hospital__r.TradeComplianceStatus__c;
                    emailBody += '您好：<br/>';
                    emailBody += cunrentConsum.Hospital__r.Name + '的贸易合规状态为' + cunrentConsum.Hospital__r.TradeComplianceStatus__c + '<br/>';
                    emailBody += '其申请单号：' + cunrentConsum.Name + '的备品借出状态为：' + cunrentConsum.RA_Status__c + '，请确认。<br/>'; 
                    emailBody += '<a href="' + System.Label.Environment_Url + consumlId + '">申请单号链接</a>';

                    /**
                     * 提交待审批 TO申请人、操作者/CC相应北上广的备品中心,法务的人
                     * */
                    if(stepName == '提交待审批' ){
                        if(submitPesronSet.size() > 0){
                            for(String submit : submitPesronSet){
                                toAddresses.add(submit);
                            }
                        }
                        if(cunrentConsum.applyUser__r.Email != null && cunrentConsum.applyUser__r.Email != ''){
                            toAddresses.add(cunrentConsum.applyUser__r.Email);
                        }
                        if(cunrentConsum.Loaner_centre_mail_address__c != null && cunrentConsum.Loaner_centre_mail_address__c != ''){
                            //上正式要修改代码，TODO=====
                            if(isSandboxBoolean){
                                ccAddresses.add(cunrentConsum.Loaner_centre_mail_address__c + '.invalid');
                            }else{
                                ccAddresses.add(cunrentConsum.Loaner_centre_mail_address__c);
                            }
                        }
                        ccAddresses.add(lawPerson);
                        //测试用 start
                        if(System.Label.ComplianceEmailSwitch == 'true'){
                            if(jzEmailList.size()>0){
                                ccAddresses.addAll(jzEmailList);
                            }
                        }
                        //测试用 end
                    }else if(stepName == '查看默认分配' || stepName == '分配' || stepName == '出库指示' || stepName == '耗材备品申请单发货'){
                        System.debug('stepName===' + stepName);
                        if(cunrentConsum.Loaner_centre_mail_address__c != null && cunrentConsum.Loaner_centre_mail_address__c != ''){
                            //上正式要修改代码，TODO=====
                            if(isSandboxBoolean){
                                toAddresses.add(cunrentConsum.Loaner_centre_mail_address__c + '.invalid');
                            }else{
                                toAddresses.add(cunrentConsum.Loaner_centre_mail_address__c);
                            }
                        }
                        if(cunrentConsum.applyUser__r.Email != null && cunrentConsum.applyUser__r.Email != ''){
                            ccAddresses.add(cunrentConsum.applyUser__r.Email);
                        }
                        if(submitPesronSet.size() > 0){
                            for(String submit : submitPesronSet){
                                ccAddresses.add(submit);
                            }
                        }
                        if(approvalPersonSet.size() > 0){
                            for(String approval : approvalPersonSet){
                                ccAddresses.add(approval);
                            }
                        }
                        ccAddresses.add(lawPerson);
                        //测试用 start
                        if(System.Label.ComplianceEmailSwitch == 'true'){
                            if(jzEmailList.size()>0){
                                ccAddresses.addAll(jzEmailList);
                            }
                        }
                        //测试用 end
                    }
                }else if(cunrentConsum.Hospital__r.TradeComplianceStatus__c == '警示名单'){
                    //邮件模板
                    subjectString = '【贸易合规】--' + stepName + '涉及警示产品' ;
                    emailBody += '您好：<br/>';
                    emailBody += cunrentConsum.Hospital__r.Name + '的贸易合规状态为' + cunrentConsum.Hospital__r.TradeComplianceStatus__c + '<br/>';
                    emailBody += '其申请单号：' + cunrentConsum.Name + '的备品借出状态为：' + cunrentConsum.RA_Status__c + '，请确认。<br/>'; 
                    emailBody += '<a href="' + System.Label.Environment_Url + consumlId + '">申请单号链接</a><br/>';

                    //备品明细
                    if(engleConsumDetailList.size()>0){ 
                        emailBody += '其申请单号:' + cunrentConsum.Name + '的明细No.为:<br/>';
                        for(Integer i = 0 ; i < engleConsumDetailList.size(); i++){
                            emailBody += i+ 1 + '.' + engleConsumDetailList[i].Name + ' ;保有设备:' + engleConsumDetailList[i].Asset__r.Name + ' ;其机身编码:' + engleConsumDetailList[i].Asset__r.SerialNumber + '<br/>';
                        }
                    }

                    if(engleAsset.size() > 0){
                        emailBody += '涉及到警示产品的保有设备明细为:<br/>';
                        for(Integer i = 0 ; i < engleAsset.size(); i++){
                            emailBody += i+1 + '. 保有设备:' + engleAsset[i].Product_Name__c + ';其机身编码:' + engleAsset[i].SerialNumber + '<br/>';
                        }
                    }

                    /**
                     * 出库指示  TO相应北上广的备品中心 CC抄送申请人、审批人、操作者,法务的人
                     * */
                    if(stepName == '提交待审批' || stepName == '选择明细'){
                        if(submitPesronSet.size() > 0){
                            for(String submit : submitPesronSet){
                                toAddresses.add(submit);
                            }
                        }
                        if(cunrentConsum.applyUser__r.Email != null && cunrentConsum.applyUser__r.Email != ''){
                            toAddresses.add(cunrentConsum.applyUser__r.Email);
                        }
                        if(cunrentConsum.Loaner_centre_mail_address__c != null && cunrentConsum.Loaner_centre_mail_address__c != ''){
                            //上正式要修改代码，TODO=====
                            if(isSandboxBoolean){
                                ccAddresses.add(cunrentConsum.Loaner_centre_mail_address__c + '.invalid');
                            }else{
                                ccAddresses.add(cunrentConsum.Loaner_centre_mail_address__c);
                            }
                        }
                        ccAddresses.add(lawPerson);
                        //测试用 start
                        if(System.Label.ComplianceEmailSwitch == 'true'){
                            if(jzEmailList.size()>0){
                                ccAddresses.addAll(jzEmailList);
                            }
                        }
                        //测试用 end
                    }else if(stepName == '默认分配画面' || stepName == '耗材分配画面' || stepName == '出库指示' || stepName == '耗材备品申请单发货' ){
                        System.debug('默认分配===警示名单');
                        if(cunrentConsum.Loaner_centre_mail_address__c != null && cunrentConsum.Loaner_centre_mail_address__c != ''){
                            //上正式要修改代码，TODO=====
                            if(isSandboxBoolean){
                                toAddresses.add(cunrentConsum.Loaner_centre_mail_address__c + '.invalid');
                            }else{
                                toAddresses.add(cunrentConsum.Loaner_centre_mail_address__c);
                            }
                        }
                        if(cunrentConsum.applyUser__r.Email != null && cunrentConsum.applyUser__r.Email != ''){
                            ccAddresses.add(cunrentConsum.applyUser__r.Email);
                        }
                        if(submitPesronSet.size() > 0){
                            for(String submit : submitPesronSet){
                                ccAddresses.add(submit);
                            }
                        }
                        if(approvalPersonSet.size() > 0){
                            for(String approval : approvalPersonSet){
                                ccAddresses.add(approval);
                            }
                        }
                        ccAddresses.add(lawPerson);
                        //测试用 start
                        if(System.Label.ComplianceEmailSwitch == 'true'){
                            if(jzEmailList.size()>0){
                                ccAddresses.addAll(jzEmailList);
                            }
                        }
                        //测试用 end
                    }
                }
            }
            System.debug('toAddresses=='+toAddresses);
            System.debug('ccAddresses=='+ccAddresses);
            mail.setSaveAsActivity(false);
            mail.setToAddresses(toAddresses);
            mail.setCcAddresses(ccAddresses);
            mail.setSubject(subjectString);
            mail.setCharset('UTF-8');
            mail.setHtmlBody(emailBody);
            emails.add(mail);
            Messaging.sendEmail(emails);
        }
        catch (Exception e) {
            System.debug('tradeConsumTempleSend====' + e.getMessage());
        }
        
        //耗材明细 start
        // if(engleConsumDetailList.size()>0){
        //     emailBody += '其申请单号:' + currentRental.Name + '的明细No.为:<br/>';
        //     for(Integer i = 0 ; i < engleRentalDetailList.size(); i++){
        //         emailBody += i+ 1 + '.' + engleRentalDetailList[i].Name + ' ;保有设备:' + engleRentalDetailList[i].Asset__r.Name + ' ;其机身编码:' + engleRentalDetailList[i].Asset__r.SerialNumber + '<br/>';
        //     }
        // }
    }


    // 判断是否是测试环境
    public static Boolean isSandbox() {
        return [SELECT IsSandbox FROM Organization LIMIT 1].IsSandbox;
    }
}