/**
 * 调用地址：
 * ContactTriggerHandler.sendToComPlat 直接调用 接口
 */
public without sharing class NFM606Controller {

    public static String logstr;
    public static String status;  
    //add aws respnse sushanhu 20220228 start
    public static String responseBody;  
    //add aws respnse sushanhu 20220228 end
    private static final String LOG_TYPE = 'NFM606';
    private static final String API = '/admin/api/user/save';
    public class NFM606 {
        public GeDatas GeDatas;
    }
    public Class GeDatas {
        public NFMUtil.MonitoringToComPlat Monitoring;
        public GeData[] GeData;

    }
    public Class GeData {
        public String ContactId; //智慧医疗ID
        public String ServiceUserId; //服务平台用户ID
        public String Mobile; //手机号码
        public String PersonManagementCode; //人员管理编码
        public Boolean AgentFlag; //经销商标识 True：是经销商；False：是医院
        public String State; //省
        public String City; //市
        public String SalesBusinessDivision; //销售本部
        public Boolean Status; //状态
        public String Hospital; //医院编码
        public String Department; //科室编码
        public String Name; //姓名
        public String Account; //经销商名称
        public String AgentCode; //经销商编码
        public String AgentUserType; //人员类型
        public String Email; //电子邮件
        //add aws pi start sushanhu 20220228
        public String DataId;//aws 存储凭据
        //add aws pi end sushanhu 20220228

    }

    @future(callout = true)
    public static void callout(String iflog_Id, List < String > conIdList) {
        executeNotFuture(iflog_Id, conIdList);
    }
    public static void executeNotFuture(String iflog_Id, List < String > conIdList) {
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmmss');
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        if (string.isNotBlank(iflog_Id)) {
            iflog = [Select Id, Name, Log__c, ErrorLog__c,MessageGroupNumber__c from BatchIF_Log__c where Id =: iflog_Id];
        } 
        
        iflog.MessageGroupNumber__c = String.isBlank(iflog.Id)?nowStr:iflog.MessageGroupNumber__c;
        iflog.Log__c = 'callout start\n';
        iflog.Type__c = LOG_TYPE;
        iflog.ErrorLog__c = '';

        NFMUtil.MonitoringToComPlat me = new NFMUtil.MonitoringToComPlat();
        me.Tag                  = 'MSGH';
        me.Sender               = 'SFDC';
        me.Receiver             = '智慧医疗/服务新系统';
        me.MessageType          = LOG_TYPE;
        me.MessageGroupNumber   = nowStr;
        if (String.isNotBlank(iflog.Name)) {
            me.MessageGroupNumber = iflog.Name;
        }
        me.TransmissionDateTime = nowStr;
        me.Text = '';
        String randomstr = NFMUtil.randomUUID(16);
        Long timestamp = DateTime.now().getTime();
        String timestampStr = String.valueOf(timestamp);
        String getToken = NFMUtil.getToken(randomstr, timestamp);
        me.API_RANDOM_STR = randomstr;
        me.API_TIME = timestampStr;
        me.API_TOKEN = getToken;


        
        GeDatas gds = new GeDatas();
        gds.GeData = new List < GeData > ();
        BatchIF_Log__c rowData = null;

        // 排除 记录类型为 社内员工的联系人
        List < Contact > conList = [select id, UnifiedI_Contact_ID__c, MobilePhone, 
            Salesdepartment_Text__c,
            Account.Management_Code__c,
            Account.Hospital__r.State_Master__r.Name,
            Account.Hospital__r.City_Master__r.Name,
            Account.Hospital__r.State_Master__r.Level1_Code__c,
            Account.Hospital__r.City_Master__r.Level2_Code__c,
            Isactive__c,
            ContactType__c,
            Account.Name,
            CManageCode__c,
            Account.Salesdepartment_Dept__c,
            Account.Hospital__r.Salesdepartment_Dept__c,
            Account.Hospital_Department_Class__r.Salesdepartment_Dept__c,
            Agency_User__c,
            RecordTypeId,
            ServicePlatformCode__c,
            Account.Parent_Management_Code__c,
            Account.State_Master__r.Level1_Code__c,
            Account.City_Master__r.Level2_Code__c,
            Account.Hospital_Department_Class__r.State_Master__r.Level1_Code__c,
            Account.Hospital_Department_Class__r.City_Master__r.Level2_Code__c,
            Account.ParentId,
            Account.Parent.ParentId,
            UniqueNumber__c,
            AWS_Data_Id__c,
            ChargeState__c, // 20220829 ljh LLIU-CHR8FF  add
            Account.RecordTypeId,// 20220829 ljh LLIU-CHR8FF  add
            ChargeState__r.Level1_Code__c,// 20220829 ljh LLIU-CHR8FF  add
            Name, Email from Contact where id in: conIdList AND RecordTypeId != '01210000000QtkyAAC'
        ];
        String logstr = iflog.Log__c + ' ' + 'NumberOfRecord=' + conList.size() + '\n';
        try {
            for (Contact con: conList) {
                String flag = '';
                GeData ged = new GeData();
                ged.ContactId = String.isBlank(con.UnifiedI_Contact_ID__c) ? '':con.UnifiedI_Contact_ID__c; //智慧医疗ID
                //update to AWS_UnifiedI_Contact_ID__c sushanhu 20220228 start
                //ged.ContactId = String.isBlank(con.) ? '':con.AWS_UnifiedI_Contact_ID__c; //AWS 智慧医疗ID
                ////update to AWS_UnifiedI_Contact_ID__c sushanhu 20220228 end
                ged.ServiceUserId = String.isBlank(con.ServicePlatformCode__c) ? '':con.ServicePlatformCode__c; //服务平台用户ID???
                ged.Mobile = String.isNotBlank(con.UniqueNumber__c) ? con.UniqueNumber__c:con.MobilePhone;//手机
                ged.PersonManagementCode = con.CManageCode__c; //人员管理编码
                ged.Status = '有效'.equals(con.Isactive__c) ? true:false ;//状态
                ged.Name = con.Name;//姓名
                ged.Email = '';
                ged.Hospital =''; //医院编码
                ged.Department = ''; //科室编码
                ged.Account = '';//经销商名
                ged.AgentCode = '';//经销商编码
                ged.AgentUserType =''; //人员类型
                ged.AgentFlag = false;//经销商标识
                if (!ged.Status) {
                    ged.Mobile = con.MobilePhone;
                }
                // 医师
                if ('01210000000QfWdAAK'.equals(con.RecordTypeId)) {
                    ged.Hospital = con.Account.Parent_Management_Code__c;//医院编码
                    ged.Department = con.Account.Management_Code__c; //科室编码
                    ged.AgentFlag = false;//医院

                }
                // 经销商
                if ('01210000000QfWiAAK'.equals(con.RecordTypeId)) {
                    //ged.Name = con.Name;//姓名
                    ged.Account = con.Account.Name;//经销商名
                    ged.AgentCode = con.Account.Management_Code__c;//经销商编码
                    ged.AgentUserType = String.isBlank(con.ContactType__c) ? '': con.ContactType__c.replaceAll(';',',');//人员类型
                    ged.AgentFlag = true;//经销商
                    ged.Email = con.Email;
                }
                ged.DataId =con.AWS_Data_Id__c;//add aws 存储凭据
                ged = getStateAndCity(ged,con);
                gds.GeData.add(ged);

            }
            logstr += '\nend';
            if (gds.GeData.size() > 0) {
                me.NumberOfRecord       = '' + gds.GeData.size();
                gds.Monitoring = me;


                logstr = iflog.Log__c + '\nNumberOfRecord=' + gds.GeData.size() + ' ';
                NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
                Monitoring.Tag                  = gds.Monitoring.Tag;
                Monitoring.Sender               = gds.Monitoring.Sender;
                Monitoring.Receiver             = gds.Monitoring.Receiver;
                Monitoring.MessageType          = gds.Monitoring.MessageType;
                Monitoring.MessageGroupNumber   = gds.Monitoring.MessageGroupNumber;
                Monitoring.NumberOfRecord       = gds.Monitoring.NumberOfRecord;
                Monitoring.TransmissionDateTime = gds.Monitoring.TransmissionDateTime;
                Monitoring.Text = '';


                NFM606 nfm606 = new NFM606();
                nfm606.GeDatas = new GeDatas();
                nfm606.GeDatas = gds;

                rowData = NFMUtil.makeRowData(Monitoring, LOG_TYPE, nfm606);
                execute(rowData, iflog);

            }
        } catch (Exception e) {
            //发生错误时
            System.debug(Logginglevel.ERROR, LOG_TYPE + iflog.Name + ':' + e.getMessage());
            System.debug(Logginglevel.ERROR, LOG_TYPE + iflog.Name + ':' + e.getStackTraceString());
            logstr += e.getMessage();
            iflog.ErrorLog__c += e.getMessage() + '\n';
            iflog.ErrorLog__c += e.getStackTraceString() + '\n';
            iflog.Log__c = iflog.Log__c + logstr;
        }
        if (rowData != null) {
            upsert rowData;
        }
        iflog.Log__c = iflog.Log__c + logstr;
        upsert iflog;

    }

    private static GeData getStateAndCity(GeData ged,Contact con){
        String state = '';
        String city = '';
        String salesdepartment_Dept = '';
        if (String.isBlank(con.Account.ParentId)) {//医院/经销商下的联系人，获取医院/经销商的省和市的编码;销售本部
            // 20220829 ljh LLIU-CHR8FF update start
            // state =  con.Account.State_Master__r.Level1_Code__c;
            Id AgencyId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Agency').getRecordTypeId();
            // System.debug('aaa000zheli'+con.ChargeState__c+'~'+AgencyId+'~'+con.Account.RecordTypeId+'~'+con.Account.State_Master__c);
            if(String.isNotBlank(con.ChargeState__c) && con.Account.RecordTypeId == AgencyId &&String.valueOf(con.ChargeState__c).substring(0,15) != String.valueOf(con.Account.State_Master__c).substring(0,15)){
                state =  con.ChargeState__r.Level1_Code__c;
            }else{
                state =  con.Account.State_Master__r.Level1_Code__c;
            }
            // 20220829 ljh LLIU-CHR8FF update end
            city =  con.Account.City_Master__r.Level2_Code__c;
            salesdepartment_Dept =  con.Account.Salesdepartment_Dept__c; //销售本部             
        } else if(String.isNotBlank(con.Account.Parent.ParentId)){//科室下的联系人， 获取医院的省和市的编码;销售本部
            state = con.Account.Hospital__r.State_Master__r.Level1_Code__c;//省
            city = con.Account.Hospital__r.City_Master__r.Level2_Code__c;//市
            salesdepartment_Dept = con.Account.Hospital__r.Salesdepartment_Dept__c;//销售本部
        } else {//战略科室下的联系人，获取医院的省和市的编码;销售本部
            state = con.Account.Hospital_Department_Class__r.State_Master__r.Level1_Code__c;//省
            city = con.Account.Hospital_Department_Class__r.City_Master__r.Level2_Code__c;//市
            salesdepartment_Dept = con.Account.Hospital_Department_Class__r.Salesdepartment_Dept__c;//销售本部
        }
        //LLIU-CKQ5FS 【委托】SFDC上“复旦大学附属中山医院厦门医院”省市问题 LY 20221101 end
        system.debug('1111111111111111111111111111');
        if (con.Account.Parent_Management_Code__c =='8045004') {
            state = 'CN-19';
            city = 'CN-1917';
        }
        //LLIU-CKQ5FS 【委托】SFDC上“复旦大学附属中山医院厦门医院”省市问题 LY 20221101 end
        ged.State = state;
        ged.City = city;
        ged.SalesBusinessDivision = salesdepartment_Dept;

        return ged;
    }


    /**
     * 接口发送失败 根据BatchLogId进行手动发送
     * @Author   XHL
     * @DateTime 2021-07-22
     * @param    rowDataId  [BatchLogId]
     */
    public static void ManualExecute(String rowDataId) {
        List < BatchIF_Log__c > row = [select id, name, MessageGroupNumber__c, retry_cnt__c,
            RowDataFlg__c, ErrorLog__c, Type__c,
            Log__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c,
            Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c
            from BatchIF_Log__c
            where id =: rowDataId
        ];
        if (row.size() > 0) execute(row[0], null);
    }

    /**
     * 逻辑正常执行发送
     * @Author   XHL
     * @DateTime 2021-07-22
     * @param    rowDataSFDC [BatchLogId]
     * @param    iflog       [执行情况记录]
     */
    public static void execute(BatchIF_Log__c rowDataSFDC, BatchIF_Log__c iflog) {
        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        String rowDataStr = NFMUtil.getRowDataStr(rowDataSFDC);
        String logstr = rowDataSFDC.MessageGroupNumber__c + ' start\n';
        if (iflog == null) {
            iflog = new BatchIF_Log__c();
            iflog.Type__c = LOG_TYPE;
            iflog.MessageGroupNumber__c = rowDataSFDC.MessageGroupNumber__c;
            iflog.Log__c = logstr;
            iflog.ErrorLog__c = '';

        } else {
            iflog.Type__c = LOG_TYPE;
            iflog.MessageGroupNumber__c = rowDataSFDC.MessageGroupNumber__c;
            logstr = iflog.Log__c;
        }

        try {
            
            
            // // 发往PO 
            // status = NFMUtil.sendToSapRet(rowDataStr, NFMUtil.NFM606_ENDPOINT);
            // System.debug('NFM606Log--status->'+ status);
            // // status = ''
            // if ('Accepted'.equals(status)) {
            //     logstr += status+'\n';
            //     rowDataSFDC.retry_cnt__c = 0;
            // } 
            // else {
            //     rowDataSFDC = NFMUtil.LogAutoSend(rowDataSFDC, null, status);
            // }
            //update to aws 20220228 sushanhu satrt 
            PIHelper.PIIntegration pi =PIHelper.getPIIntegrationInfo('NFM606');
            NFMUtil.response result =NFMUtil.sendToPiAWS(rowDataStr,pi.newUrl,pi.token);
            system.debug('aws result---'+result);
            responseBody=result.responseBody;
            //Map<String, Object> res = (Map<String, Object>)JSON.deserializeUntyped(responseBody);
            //status=(String)res.get(status);
            status =result.status;
            system.debug('stadtucode--'+result.status);
            if ('202'.equals(status)) {
                logstr += status+'\n';
                     rowDataSFDC.retry_cnt__c = 0;
            }
            else {
                logstr+=responseBody+'\n';
                rowDataSFDC = NFMUtil.LogAutoSend(rowDataSFDC, null, status);
            }
            //update to aws 20220228 sushanhu end
        } catch (Exception ex) {
            // TODO IOException
             // 异常重发
            // Callout from triggers are currently not supported.
            if (!String.valueOf(ex.getMessage()).contains('Callout from triggers')) {
                logstr += ex.getMessage();
                iflog.ErrorLog__c += ex.getMessage() + '\n';
                iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
            }
            rowDataSFDC = NFMUtil.LogAutoSend(rowDataSFDC, null, status);
        }
        iflog.Log__c = iflog.Log__c + logstr;
        upsert iflog;
        upsert rowDataSFDC;
    }
}