/**********************************************************************
 *
 *
 * @url: /services/apexrest/NFM620Rest
 * @data:
 *  {

    }
*************************************************************************/
@RestResource(urlMapping = '/NFM620/*')
global with sharing class NFM620Rest {
    //新增NFM620Rest 商品询问单接收数据接口 精琢技术 start
    /*迁移ali sushanhu 20231018
   //add to AWS 回复 start sushanhu 20220225 
   static Boolean SFStatus=true;
   static String SFMessage='';
  //add to AWS 回复 end sushanhu 20220225 
  */
    global class GeDatas {
        public NFMUtil.Monitoring Monitoring;
        public  GeData[] GeData;
    }

    global class GeData {
        public String Name;                      // 询问单名称
        public String InquiryNo;                 // 询问单编码
        public String ContactId;                 // 统一用户ID
        public String ContactWay;                // 联系方式
        public String Campaign;                  // 主要学会(市场活动编码)
        public String Product;                   // 产品信息
        public String Request;                   // 委托事项
        public String RequestDetail;             // 委托事项详细
        public String ApproverID;                // 审核人员员工编码
        //public String ContactWayEncrypted;         //联系方式密文 for pi      //zhj新方案改造 2022-12-07 
        //public String DataId;                      //AWS 加密凭据 //  迁移ali sushanhu 20231018
        //public Integer ContactType;                 //联系方式 1为邮箱 2为电话 迁移ali sushanhu 20231018
    }

    @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, 'NFM620', 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 = '{"status": "Success", "Message":""}';
        res.responseBody = blob.valueOf(jsonResponse);
        /* 迁移ali sushanhu 20231018
        //updata response toAWS 20220225 sushanhu start
        NFMUtil.NFMResponse result = NFMUtil.getNFMResponse();
        result.SFStatus=SFStatus;
        result.SFMessage=SFMessage;
        String jsonResponse =JSON.serialize(result);
        system.debug('result---'+jsonResponse);
        res.responseBody = blob.valueOf(jsonResponse);
        //updata response toAWS 20220225 sushanhu end
        */
        return;
    }

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

    global static void main (String rowData_Id) {

        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 = 'NFM620';
        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;
        }

        // BatchIF転送表 から、コード変換のMapを作成
        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 = 'Inquiry_form__c'];
        for (BatchIF_Transfer__c t : transferList) {
            transferMap.put(t.Column__c + t.External_value__c, t.Internal_value__c);
        }

        Savepoint sp = Database.setSavepoint();

        try {
            List<Inquiry_form__c> inqInsList = new List<Inquiry_form__c>();

            //将统一用户ID、市场活动编码、咨询单编码存入List
            List<String> inquiryNoList = new List<String>();
            List<String> conIDList = new List<String>();
            List<String> camNoList = new List<String>();
            List<String> approverIDList = new List<String>();
            List<GeData> geDataListNew = new List<GeData>();
            for (GeData geData : geDataList) {
                if (String.isBlank(geData.InquiryNo)) {
                    // 必須項目がない場合、処理と飛ばす
                    iflog.ErrorLog__c += '咨询单编码不能为空。\n';
                    continue;
                } else {
                    inquiryNoList.add(geData.InquiryNo);
                }

                if (String.isBlank(geData.ContactId)) {
                    // 必須項目がない場合、処理と飛ばす
                    iflog.ErrorLog__c += '统一用户ID不能为空。\n';
                    continue;
                } else {
                    conIDList.add(geData.ContactId);
                }
                if (String.isNotBlank(geData.ApproverID)) {
                    approverIDList.add(geData.ApproverID);
                }
                if (String.isNotBlank(geData.Campaign)) {
                    camNoList.add(geData.Campaign);
                }
                
                geDataListNew.add(geData);
            }
            //使用统一用户ID获取科室、战略科室分类、用户姓名并存入Map
            Map<String, Contact> conInfoMap = new Map<String, Contact>();
            if (conIDList.size() > 0) {
                List<Contact> conList = [select UnifiedI_Contact_ID__c, Account.Id,
                                         Strategic_dept_Class__c, Strategic_dept_Class__r.OwnerId, Id
                                         from Contact where UnifiedI_Contact_ID__c in: conIDList];
                if (conList.size() > 0) {
                    //科室、战略科室分类、用户姓名获取成功
                    for (Contact conInfo : conList) {
                        conInfoMap.put(conInfo.UnifiedI_Contact_ID__c, conInfo);
                    }
                }

            }
            //使用市场活动编码获取市场活动ID存入Map
            Map<String, String> camInfoMap = new Map<String, String>();
            if (camNoList.size() > 0) {
                List<Campaign> campList = [select Num__c, Id from Campaign where Num__c in :camNoList];
                if (campList.size() > 0) {
                    //市场活动ID获取成功
                    for (Campaign camInfo : campList) {
                        camInfoMap.put(camInfo.Num__c, camInfo.Id);
                    }
                }
            }

            //询问单编码已经存在的时候连同ID一起存入Map
            Map<String, String> inqInfoMap = new Map<String, String>();
            if (inquiryNoList.size() > 0) {
                List<Inquiry_form__c> inquiryList = [select Inquiry_No__c, Id from Inquiry_form__c where Inquiry_No__c in :inquiryNoList];
                if (inquiryList.size() > 0) {
                    for (Inquiry_form__c inqInfo : inquiryList) {
                        inqInfoMap.put(inqInfo.Inquiry_No__c, inqInfo.Id);
                    }
                }
            }
            //使用审核人员员工编码查询用户ID
            Map<string,String> ownerMap = new Map<string,String>();
            if(approverIDList.size()>0){
                List<User> ownerList = [select Id,Employee_No__c from User where Employee_No__c  IN:approverIDList];
                if (ownerList.size()>0){
                    for(User temp : ownerList){
                        ownerMap.put(temp.Employee_No__c,temp.Id);
                    }
                }
            }
            // 将XML各数据项更新到商品询问单对象中
            for (GeData geData : geDataListNew) {
                    
                Inquiry_form__c inquiry = new Inquiry_form__c();

                inquiry.ComPlat_Name__c = geData.Name;                                       //询问单名称
                inquiry.Inquiry_No__c = geData.InquiryNo;                         //询问单编码
                // inquiry.Opportunity_Division__c = '询价';                         //意向区分
                inquiry.Status__c = '01.未跟进';                                     //询问单状态
                inquiry.Request_Detail__c = geData.RequestDetail;                 //委托事项详细
                inquiry.Product1__c = geData.Product;                             //产品信息
                inquiry.ContactId__c = geData.ContactId;                          //统一用户ID
                if (String.isNotBlank(ownerMap.get(geData.ApproverID))){
                    inquiry.OwnerId = ownerMap.get(geData.ApproverID);            //所有人
                }          
                //inquiry.AWS_Data_Id__c =geData.DataId;                              //AWS加密凭据 add 200220214 /* 迁移ali sushanhu 20231018
                

                //委托事项取值后拆分
                List<String> requestList = geData.Request.split(';');
                String request1 = '';
                for (String req11 : requestList) {
                    request1 += NFMUtil.getMapValue(transferMap, 'Request1__c', req11, iflog) + ';';
                }                                   
                inquiry.Request1__c = request1.substring(0, request1.length() - 1);  //委托事项
                
                //使用统一用户ID获取科室、战略科室、客户姓名
                if (conInfoMap.containsKey(geData.ContactId)) {
                    Contact contact = conInfoMap.get(geData.ContactId);
                    inquiry.Hospital_Name__c = contact.Account.Id;                    //科室名    
                    // inquiry.Department_Class__c = contact.Strategic_dept_Class__c;    //战略科室分类
                    inquiry.Contact_Name__c = contact.Id;                             //客户姓名
                    // inquiry.OwnerId = contact.Strategic_dept_Class__r.OwnerId;        //所有人
                } 
                //使用市场活动编码获取市场活动ID
                if (String.isNotBlank(geData.Campaign)) {
                    if (String.isNotBlank(camInfoMap.get(geData.Campaign))) {
                        inquiry.Campaign__c = camInfoMap.get(geData.Campaign); //主要学会
                        inquiry.LeadSource__c = '学会会议';                    //询问单来源
                    } else {
                        iflog.ErrorLog__c += geData.InquiryNo + '：市场活动编码不存在。\n';
                        continue;                              
                    }
                } else {
                    inquiry.LeadSource__c = '智慧医疗';                 //询问单来源
                }
                logstr += '咨询单来源:' + inquiry.LeadSource__c + '\n';                               
                //联系方式的值是否包含@来判断是邮箱还是电话
                //if (geData.ContactType==1) { //迁移ali 20231214 tiger
                if (geData.ContactWay.contains('@')) {    
                    inquiry.Phone__c = '';                            //电话
                    //inquiry.Phone_Encrypted__c='';                     //电话密文 add 20220214        //zhj新方案改造 2022-12-07 
                    inquiry.Email__c = geData.ContactWay;             //邮箱
                    //inquiry.Email_Encrypted__c =geData.ContactWayEncrypted; //邮箱密文 add 20220214   //zhj新方案改造 2022-12-07 

                } else {
                    inquiry.Phone__c = geData.ContactWay;
                    inquiry.Email__c = '';
                    //inquiry.Email_Encrypted__c = ''; //邮箱密文 add 20220214                          //zhj新方案改造 2022-12-07 
                    //inquiry.Phone_Encrypted__c=geData.ContactWayEncrypted;    //电话密文 add 20220214 //zhj新方案改造 2022-12-07 
                }

                if (String.isNotBlank(inqInfoMap.get(geData.InquiryNo))) {
                    //询问单编码存在,获取询问单的ID
                    inquiry.Id = inqInfoMap.get(geData.InquiryNo);
                }

                inqInsList.add(inquiry);
                //logstr += geData.InquiryNo +'：获取成功。\n';

            }

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

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

        } catch (Exception ex) {
            // エラーが発生した場合
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'NFM620_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM620_' + 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;
    }
    //新增NMF620接口 精琢技术 end
}