/**********************************************************************
 * 
 *
 * @url: /services/apexrest/NFM209/execute
 * 
 * 
*************************************************************************/
@RestResource(urlMapping='/NFM209/*')
global with sharing class NFM209Rest {
    //新增NFM209Rest 合规状态  you start
  
    global class GeDatas {
        public NFMUtil.Monitoring Monitoring;
        public  GeData[] GeData;
    }

    global class GeData {
        public String custCode;                    // 客户管理编码
        public String complStatus;                 // 零合规状态
        public String orgSysId;                    // 发起系统
        public String glbBusiNo;                   // 报文流水号
        public String custTp;                      // 对象类型
        public String entityTp;                    // 实体类型
        public String custName;                    // 客户名称
       
    }

    @HttpPost
    global static void execute() {

        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        GeDatas ges = (GeDatas) JSON.deserializeStrict(strData, GeDatas.class);
        system.debug('rquest----'+strData);
        if (ges == null ) {
            return;
        }

        NFMUtil.Monitoring Monitoring = ges.Monitoring;
        if (Monitoring == null) {
            return;
        }

        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'NFM209', ges.GeData);
        if (String.isBlank(rowData.Log__c) == false) {
            executefuture(rowData.Id);
        }

        // JSONを戻す
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        String jsonResponse = '{"Result": {"Result": "00", "Message":""}}';
        res.responseBody = blob.valueOf(jsonResponse);
        return;
    }

    @future
    global static void executefuture(String rowData_Id) {
        main(rowData_Id);
    }

    global static void main (String rowData_Id) {
        Map<String, String> transferMap = new Map<String, String>();
        List<BatchIF_Transfer__c> transferList = [select Table__c,
                                  Column__c,
                                  External_value__c,
                                  Internal_value__c
                                  from BatchIF_Transfer__c
                                  where Dropped_Flag__c = false
                                          and (Table__c = 'Account')
                                          ];
        for (BatchIF_Transfer__c t : transferList) {
            transferMap.put(t.Column__c + t.External_value__c, t.Internal_value__c);
        }


        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        BatchIF_Log__c rowData = [Select Id, Name, retry_cnt__c, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
        String logstr = rowData.MessageGroupNumber__c + ' start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = 'NFM209';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;

        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        List<GeData> geDataList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);

        if (geDataList == null || geDataList.size() == 0) {
            return;
        }

        Savepoint sp = Database.setSavepoint();

        try {
            List<Account> accInsList = new List<Account>();

            //将客户管理编码、合规状态存入List
            List<String> custCodeList = new List<String>();
            List<String> complStatusList = new List<String>();
            
            for (GeData geData : geDataList) {
                if (String.isBlank(geData.custCode)) {
                    iflog.ErrorLog__c += '管理编码不能为空。\n';
                    continue;
                } else {
                    custCodeList.add(geData.custCode);
                }

                if (String.isBlank(geData.complStatus)) {
                    iflog.ErrorLog__c += geData.custCode+':合规状态为空。\n';
                    continue;
                } 
                
            }
            
            //客户管理编码和合规状态日期存入Map
            Map<String, Account> accInfoMap = new Map<String, Account>();
            if (custCodeList.size() > 0) {
                List<Account> accList = [select ID,Parent_Management_CodeClean__c,TradeComplianceStatus__c  from Account where Parent_Management_CodeClean__c in :custCodeList and (RecordType.DeveloperName = 'HP' or RecordType.DeveloperName = 'Agency')];
                if (accList.size() > 0) {
                    for (Account accInfo : accList) {
                        accInfoMap.put(accInfo.Parent_Management_CodeClean__c, accInfo);
                    }
                }
            }
            
            
            //kk  20231221  贸易合规2  start
            // 涉及更新的listId
            List<String> updateAccountIDList = new List<String>();
            //kk  20231221  贸易合规2  end

            // 将XML的合规状态存入客户对象中
            for (GeData geData : geDataList) {
                    
                Account acc = new Account();
                if (!accInfoMap.containsKey(geData.custCode)){
                    iflog.ErrorLog__c += '客户管理编码:' +geData.custCode +'：未找到。\n';
                    continue;
                }
                acc.Id = (accInfoMap.get(geData.custCode)).ID;      
                //kk  20231221  贸易合规2  start
                updateAccountIDList.add(acc.Id);
                //kk  20231221  贸易合规2  end      
                acc.TradeComplianceStatus__c = NFMUtil.getMapValue(transferMap, 'TradeComplianceStatus__c', string.valueof(geData.complStatus), iflog);             //合规状态
                
                accInsList.add(acc);
                logstr += '客户管理编码:' +geData.custCode +'：获取成功。\n';

            }
            //kk  20231221  贸易合规2  start
            // 存放更新前数据的map
            Map<String,String> oldStatus = new Map<String,String>();
            List<Account> oldAccount = [SELECT Id,TradeComplianceStatus__c 
                                            FROM Account 
                                                WHERE Id IN :updateAccountIDList];
            for(Account ac : oldAccount){
                oldStatus.put(ac.Id,ac.TradeComplianceStatus__c);
            }
            System.debug('==oldAccount=='+oldStatus);
            //kk  20231221  贸易合规2  end

            if (accInsList.size() > 0) {
                upsert accInsList;
                logstr += '更新成功。\n';
            }

            logstr += '\nend';
            rowData.retry_cnt__c = 0;

            //kk  20231130  贸易合规2  start
            secondCompliance(accInfoMap,transferMap,geDataList,iflog,oldStatus);
            //kk  20231130  贸易合规2  end

        } catch (Exception ex) {
            // エラーが発生した場合
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'NFM209_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM209_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
            logstr += '\n' + ex.getMessage();
            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
            if (rowData.retry_cnt__c < batch_retry_max_cnt) {
                rowData.retry_cnt__c++;
                LogAutoSendSchedule.assignOneMinute();
            }
            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '错误次数已经超过自动收信设定的最大次数，请手动收信';
            }
        }

        update rowData;
        iflog.Log__c = logstr;
        if (iflog.Log__c.length() > 131072) {
            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
        }
        if (iflog.ErrorLog__c.length() > 32768) {
            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
        }
        update iflog;
    }
    //新增NFM209Rest 合规状态 you end

    //kk 20231129  合规2期  start
    public static void secondCompliance(Map<String, Account> accInfoMap,Map<String, String> transferMap,List<GeData> geDataList, BatchIF_Log__c iflog,Map<String,String> oldStatus){
        //<客户ids,客户名>
        Map<String,String> data4 = new Map<String,String>();
        //<客户ids,客户合规状态>
        Map<String,String> data1 = new Map<String,String>();
        //<备品申请单id,审批对象>
        //Map<String,ProcessInstanceStep> data2 = new Map<String,ProcessInstanceStep>();
        //<备品申请单明细Id,备品明细对象>
        List<Rental_Apply_Equipment_Set_Detail__c> data3 = new List<Rental_Apply_Equipment_Set_Detail__c>();
         //客户ids
        List<String> accountIdList = new List<String>();
        //用客户id查出所有rentalList
        List<Rental_Apply__c> rentalList = new List<Rental_Apply__c>();
        //用客户id查出所有ProcessInstanceStep
        List<ProcessInstanceStep> steps = new List<ProcessInstanceStep>();
        //
        List<Rental_Apply_Equipment_Set_Detail__c> rentalEqList = new List<Rental_Apply_Equipment_Set_Detail__c>();
        // 发送邮件内容
        List<Messaging.SingleEmailMessage> sendMails = new List<Messaging.SingleEmailMessage>();
        for(GeData geData : geDataList){
            String accountId = (accInfoMap.get(geData.custCode)).ID;
            System.debug('accountId'+accountId);
            String complianceStatus = NFMUtil.getMapValue(transferMap, 'TradeComplianceStatus__c', string.valueof(geData.complStatus), iflog);
            if(oldStatus.get(accountId) == complianceStatus){
                return;
            }
            String aName = geData.custName;
            data1.put(accountId, complianceStatus);
            data4.put(accountId,aName);
            accountIdList.add(accountId);
        }
        System.debug('accountIdList'+accountIdList);
        rentalList = [SELECT RA_Status__c, Id,Name,applyUser__r.Email,Loaner_centre_mail_address__c,Hospital__c,Tracking_Delivery_Number__c,Asset_return_Status__c
            FROM Rental_Apply__c
            WHERE Hospital__c IN :accountIdList  And (RA_Status__c!='取消' And RA_Status__c!='完了')];

        system.debug('=====rentalList====='+ rentalList);
        List<String> rentalIdList = new List<String>();
        for(Rental_Apply__c rental : rentalList){
            rentalIdList.add(rental.Id);    
        }
        //没有备品申请单直接返回
        if(rentalIdList.size() == 0){
            return;
        }
        system.debug('=====rentalIdList====='+ rentalIdList);
        steps = [
            SELECT Id, StepStatus, ProcessInstance.TargetObjectId, ProcessInstance.SubmittedBy.Email, Actor.Email,CreatedDate
            FROM ProcessInstanceStep
            WHERE ProcessInstance.TargetObjectId IN :rentalIdList
            ORDER BY CreatedDate ASC];
        system.debug('=====steps====='+ steps);
        rentalEqList = [SELECT Asset__r.Product2.CountryOfOrigin__c,Asset__r.Product2.USRatio_US_OUT10__c,Rental_Apply__c,Name,Asset__r.Name,Asset__r.Product2.USRatio_US__c,Asset__r.SerialNumber
                        FROM Rental_Apply_Equipment_Set_Detail__c
                            WHERE Rental_Apply__r.Hospital__c in :accountIdList];
        system.debug('=====rentalEqList====='+ rentalEqList);
        system.debug('=====rentalEqList[0]====='+ rentalEqList[0].Asset__r.Product2.CountryOfOrigin__c);
        
        //if(steps.size()>0){
        //    system.debug('=====steps.size====='+ steps.size());
        //    for( ProcessInstanceStep instans : steps ){
        //        data2.put(instans.ProcessInstance.TargetObjectId, instans);    
        //    }     
        //}
        system.debug('=====111111=====');
        for( Rental_Apply_Equipment_Set_Detail__c esd : rentalEqList){
            data3.add(esd);
        }
        system.debug('=====2222====='+ rentalList);
        //便利备品申请单
        //判断是否发邮件
        String  juageFlag;
        for(Rental_Apply__c rental : rentalList){
            if(data1.containsKey(rental.Hospital__c)){
                system.debug('=====333====='+ data1);
                String rentalTrackingDeliveryNumber = rental.Tracking_Delivery_Number__c;
                String assetReturnStatus = rental.Asset_return_Status__c;
                String tradeComplianceStatus = data1.get(rental.Hospital__c); 
                String accountName = data4.get(rental.Hospital__c);
                system.debug('=====4444====='+ data4.get(rental.Hospital__c));
                String rentalNo = rental.Name;
                String rentalId = rental.Id;
                //String submitPesron;
                //String approvalPerson;
                //去重
                Set<String> submitPesronSet = new Set<String>();
                Set<String> approvalPersonSet = new Set<String>();
                system.debug('=====rental====='+ rental.Asset_return_Status__c);
                if(steps.size() > 0){
                    for(ProcessInstanceStep   instans :steps){
                        if( rental.Id == instans.ProcessInstance.TargetObjectId){
                            submitPesronSet.add(instans.ProcessInstance.SubmittedBy.Email);
                            approvalPersonSet.add(instans.Actor.Email);
                        }
                    }
                }
                //if(data2.size()>0){
                //    if(data2.containskey(rental.Id)){
                //        //当前备品申请单的申请人 的邮件
                //        submitPesron = data2.get(rental.Id).ProcessInstance.SubmittedBy.Email;
                //        //当前备品申请单的批准人 的邮件
                //        approvalPerson = data2.get(rental.Id).Actor.Email;     
                //        system.debug('=====sqr====='+ submitPesron);
                //        system.debug('=====pzr====='+ approvalPerson);
                //    }
                //    else{
                //        submitPesron='';
                //        approvalPerson='';     
                //    }
                //}
                //else{
                //    submitPesron='';
                //    approvalPerson='';    
                //}
                
                //当前备品申请单的操作者(创建人)
                String operatorPerson = rental.applyUser__r.Email;
                system.debug('=====operatorPerson====='+ rental.applyUser__r.Email);
                //备品中心邮箱地址
                String rentalCentetEmailAdress = rental.Loaner_centre_mail_address__c;
                //法务人员 

                String raStatus = rental.RA_Status__c;
                system.debug('=====raStatus====='+ rental.RA_Status__c);
                // //冻结、黑名单
                if((tradeComplianceStatus == '冻结,人工审批中'  ||  tradeComplianceStatus == '黑名单') 
                    && (raStatus == '草案中' || raStatus == '申请中' || raStatus == '申请中（OPD未通过）')){      //20231224 sx add  备品智能化添加状态申请中（OPD未通过） 优化
                    //邮件
                    juageFlag = secondSendEmail( tradeComplianceStatus , accountName, rentalId, rentalNo, raStatus, submitPesronSet, approvalPersonSet,
                         operatorPerson ,  rentalCentetEmailAdress , '1', data3,sendMails);
                }
                if((tradeComplianceStatus == '冻结,人工审批中'  ||  tradeComplianceStatus == '黑名单') 
                        &&(raStatus == '已批准' ||  raStatus == '已分配' || raStatus == '已出库指示' || raStatus == '已下架' || raStatus == '出库前已检测')){
                    //邮件
                    juageFlag = secondSendEmail( tradeComplianceStatus , accountName, rentalId, rentalNo, raStatus, submitPesronSet, approvalPersonSet,
                         operatorPerson ,  rentalCentetEmailAdress , '2', data3,sendMails);
                }
                if((tradeComplianceStatus == '冻结,人工审批中' || tradeComplianceStatus == '黑名单') 
                        && (raStatus == '已出库' || raStatus == '申请者已收货' ||  raStatus == '医院已装机确认' ||  raStatus == '已回寄' ||  raStatus == '欠品中')){
                    //!String.isBlank(rentalTrackingDeliveryNumber) && assetReturnStatus != '全部归还'
                    //邮件
                    juageFlag = secondSendEmail( tradeComplianceStatus , accountName, rentalId, rentalNo, raStatus, submitPesronSet, approvalPersonSet,
                         operatorPerson ,  rentalCentetEmailAdress , '3', data3,sendMails);
                }

                //警示名单
                if((tradeComplianceStatus == '警示名单') 
                        &&(raStatus == '已批准' || raStatus == '已出库指示' || raStatus == '已分配' || raStatus == '已下架' || raStatus == '出库前已检测')){
                    //判断产品信息是否合规
                    //不合规发邮件  
                    juageFlag = secondSendEmail( tradeComplianceStatus , accountName, rentalId, rentalNo, raStatus, submitPesronSet, approvalPersonSet,
                         operatorPerson ,  rentalCentetEmailAdress , '2', data3,sendMails);

                }
                if((tradeComplianceStatus == '警示名单') 
                        && (raStatus == '已出库' || raStatus == '申请者已收货' ||  raStatus == '医院已装机确认' ||  raStatus == '已回寄' ||  raStatus == '欠品中')){
                    //判断产品信息是否合规
                    //不合规发邮件
                    juageFlag = secondSendEmail( tradeComplianceStatus , accountName, rentalId, rentalNo, raStatus, submitPesronSet, approvalPersonSet,
                         operatorPerson ,  rentalCentetEmailAdress , '3', data3,sendMails);
                }
            }
        }
        system.debug('===sendMails==='+sendMails);
        if (sendMails.size() > 0) {
            //Messaging.sendEmail(allMails);
            Messaging.SendEmailResult[] results = Messaging.sendEmail(sendMails);
            for (Integer i = 0; i < results.size(); i++) {
                if (results[i].success == false) {
                    system.debug('=====send mail error:' + results[i].errors[0].message);
                }
            }
        }     

    }


    public static String secondSendEmail(String tradeComplianceStatus ,String accountName,String rentalId,String rentalNo,String raStatus,Set<String> submitPesronSet,Set<String> approvalPersonSet
        ,String operatorPerson , String rentalCentetEmailAdress , String  flag,List<Rental_Apply_Equipment_Set_Detail__c> data3,List<Messaging.SingleEmailMessage> sendMails){
        system.debug('=====进入邮件发送=====');
        system.debug('=====申请人====='+submitPesronSet);
        system.debug('=====审批人====='+approvalPersonSet);
        
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();  
        //提醒 
        List<String> toMailsList = new List<String>();
        //抄送
        List<String> ccEmailSet = new List<String>();
        //单独抄送法务
        List<String> ccEmailSet1 = new List<String>();
        //法务cc
        // String ccLawPerson = 'Lina_Yun@olympus.com.cn';
        // 测试用 代表法务
        String ccLawPerson = System.Label.LegalDepartmentEmail;
        //代表 备品中心等
        String  testJzMail  = 'olympus@prec-tech.com' ;
        //不合规的借出备品配套一览明细List
        List<Rental_Apply_Equipment_Set_Detail__c> noRuleRentalEqList = new List<Rental_Apply_Equipment_Set_Detail__c>();
        //不合规的邮件
        if(tradeComplianceStatus =='警示名单'){
            try {
                for(Integer i = 0;i<data3.size();i++){
                system.debug('=====不合规的邮件====='+ data3[i].Rental_Apply__c+'===='+rentalId);
                if(data3[i].Asset__c != null){
                    if(data3[i].Rental_Apply__c == rentalId && (data3[i].Asset__r.Product2.CountryOfOrigin__c == 'US' || data3[i].Asset__r.Product2.USRatio_US_OUT10__c =='1')){
                        noRuleRentalEqList.add(data3[i]);
                    }    
                }
                
            }     
             }
             catch (Exception e) {
                 system.debug('=====Exception====='+ e);
             }
            
        }


        system.debug('=====noRuleRentalEqList====='+ noRuleRentalEqList+'size'+noRuleRentalEqList.size());
  
        //申请人、审批人、操作者
        if (operatorPerson != null && operatorPerson != '') {
            toMailsList.add(operatorPerson);
            system.debug('=====operatorPerson====='+ operatorPerson);
         }
        if (approvalPersonSet.size() > 0) {
            for(String approvalPerson :approvalPersonSet){
                toMailsList.add(approvalPerson);    
            }
            system.debug('=====approvalPersonSet====='+ approvalPersonSet);
        }
        if (submitPesronSet.size() > 0) {
            for(String submitPesron : submitPesronSet){
                toMailsList.add(submitPesron);    
            }
            system.debug('=====submitPesronSet====='+ submitPesronSet);
        }
        //备品中心 
        system.debug('=====rentalCentetEmailAdress====='+ rentalCentetEmailAdress);
        if (rentalCentetEmailAdress != null && rentalCentetEmailAdress != '') {
             ccEmailSet.add(rentalCentetEmailAdress);
        }
        //两种相反的情况
        if(flag == '1'){
            message.setToAddresses(toMailsList); 
            //法务人永远是cc
            ccEmailSet.add(ccLawPerson);
            //精琢抄送
            ccEmailSet.add(testJzMail);
            message.setCcAddresses(ccEmailSet);
            system.debug('=====法务人永远是cc====='+ ccEmailSet);
        }
        else if(flag == '2'){
            message.setToAddresses(ccEmailSet); 
            //法务人永远是cc
            toMailsList.add(ccLawPerson);
            //精琢抄送
            toMailsList.add(testJzMail);
            message.setCcAddresses(toMailsList);    
        }
        else{
            toMailsList.add(rentalCentetEmailAdress);
            toMailsList.add(testJzMail); 
            ccEmailSet1.add(ccLawPerson);
            message.setToAddresses(toMailsList); 
            message.setCcAddresses(ccEmailSet1);   
        }
        system.debug('=====toMailsList====='+ ccEmailSet);
        system.debug('=====toMailsList====='+ toMailsList);
        String subject = '【贸易合规】合规状态变更提醒--' + accountName;
        String htmlStr = '您好：  ' + '<BR>' +'<BR>';
        htmlStr+= accountName + '的贸易合规状态已变更为' + tradeComplianceStatus +'<BR>';
        htmlStr+= '其申请单号：'+rentalNo + '的备品借出状态为：'+raStatus + '，请确认。     <BR>';
        htmlStr+= '<a href="' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + rentalId + '">申请单号链接</a>';
        

        //不合规的备品明细记录在邮件内
        if(tradeComplianceStatus =='警示名单' && noRuleRentalEqList.size() > 0){
            //编辑警示邮件
            htmlStr+= '<BR>'+'其申请单号：'+rentalNo + '的明细No.为：';
            for(Integer i = 0; i<noRuleRentalEqList.size() ;i++){
                htmlStr+= '<BR>' +(i+1)+'.' +noRuleRentalEqList[i].Name +' ;保有设备：' +  noRuleRentalEqList[i].Asset__r.Name + ' ;其机身编码：' + noRuleRentalEqList[i].Asset__r.SerialNumber;
                
            }
        }

        message.setSubject(subject);
        message.setHtmlBody(htmlStr);
        message.setCharset('UTF-8');
        system.debug('=====message====='+ message);
        if(tradeComplianceStatus =='警示名单' && noRuleRentalEqList.size() <= 0){
            system.debug('=====不发邮件====='+ noRuleRentalEqList.size());
            return 'NoMail';
        }
        sendMails.add(message);
        return '1';
        //合规直接不发邮件
        

               
    }
    //kk 20231129  合规2期  end



}