/**
 * PIとの通信時、使う共通機能
 * 日付変換、メール送信なの
 */
global class NFMUtil {

    public static Integer MaxLogColumnLength = 131072;
    public static String DummyAssetProfix = '不可用：';
    public static String Authorization = 'Basic T0NNX1NGX1VTRVI6b2Ntc2ZkYzg0MDI=';
    public static String CLIENT_CERT_NAME = null;
    public static String SBG001_ENDPOINT = null;
    public static String SBG007_ENDPOINT = null;
    public static String SBG027_ENDPOINT = null;

    public static String CBPR_Auth_Sap = null;

    static {
        if (isSandbox()) {
            System.debug('sandbox');
            CBPR_Auth_Sap = 'Basic U0ZEQ19XU1VTRVI6cG9xMTIzNDU=';
            CLIENT_CERT_NAME = 'owdc_test';
            // SBG001_ENDPOINT = 'https://owdc-test.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG001_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG001';
            //SBG007_ENDPOINT = 'https://owdc-test.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG007_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG007';
            //SBG027_ENDPOINT = 'https://owdc-test.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG027_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG027';
            //SBG027_ENDPOINT = 'https://wdp.olympus.com.cn:44301/RESTAdapter/SBG027';
            // SBG027_ENDPOINT = 'http://wdp.olympus.com.cn:8089/RESTAdapter/SBG027';
            // SBG001_ENDPOINT = 'http://wdp.olympus.com.cn:44301/RESTAdapter/SBG001';
            //SBG001_ENDPOINT = 'https://owdc-test.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG001_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG001';
            SBG001_ENDPOINT = 'http://wdp.olympus.com.cn:8089/RESTAdapter/SBG001';
            //SBG007_ENDPOINT = 'https://owdc-test.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG007_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG007';
            SBG007_ENDPOINT = 'http://wdp.olympus.com.cn:8089/RESTAdapter/SBG007';
            //SBG027_ENDPOINT = 'https://owdc-test.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_T&receiverParty=&receiverService=&interface=SBG027_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG027';
            //SBG027_ENDPOINT = 'https://wdp.olympus.com.cn:44301/RESTAdapter/SBG027';
            SBG027_ENDPOINT = 'http://wdp.olympus.com.cn:8089/RESTAdapter/SBG027';
            
        } else {
            CBPR_Auth_Sap = 'Basic U0ZEQ19XU1VTRVI6cG9wMTIzNDU=';
            System.debug('production');
            CLIENT_CERT_NAME = 'sfdc_ocn';
            //SBG001_ENDPOINT = 'https://owdc.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_P&receiverParty=&receiverService=&interface=SBG001_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG001';
            SBG001_ENDPOINT = 'https://wdp.olympus.com.cn:44302/RESTAdapter/SBG001';
            //SBG007_ENDPOINT = 'https://owdc.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_P&receiverParty=&receiverService=&interface=SBG007_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG007';
            SBG007_ENDPOINT = 'https://wdp.olympus.com.cn:44302/RESTAdapter/SBG007';
            //SBG027_ENDPOINT = 'https://owdc.olympus.co.jp/XISOAPAdapter/MessageServlet?senderParty=&senderService=OCN_SFDC_P&receiverParty=&receiverService=&interface=SBG027_Sync_BC2GPI&interfaceNamespace=http%3A%2F%2Folympus.co.jp%2Fgpi%2FSBG027';
            
            SBG027_ENDPOINT = 'https://wdp.olympus.com.cn:44302/RESTAdapter/SBG027';
        }
    }
    
    // 受信用
    global class Monitoring {
        webservice String Tag;
        webservice String Sender;
        webservice String Receiver;
        webservice String MessageType;
        webservice String MessageGroupNumber;
        webservice String NumberOfRecord;
        webservice String TransmissionDateTime;
        webservice String Text;
    }
    //add for pipl sushanhu 20220311 start
   /*public static response sendToPiAWS(String rowDataStr, String endpoint,String awsToken) {

        Http http = new Http();
        HttpRequest req = new HttpRequest();
        HTTPResponse res;
        String resb;
        req.setHeader('Content-Type', 'application/json');
        req.setTimeout(120000);
        req.setEndpoint(endpoint);
        req.setMethod('POST');
        req.setHeader('pi-token', awsToken);
        req.setBody(rowDataStr);
        res = http.send(req);
        string ress = String.valueOf(res.getStatusCode()) ;
        resb = res.getBody();
        system.debug('ress:' + ress);
        return new response(ress, resb);
    }

    public static response getAwsToken(){
        String responseBody = AWSServiceTool.getAWSToken();
        return new response('success', responseBody);
    }
    public class response {
        public string status;
        public string responseBody;
        public response(string status, string responseBody ) {
            this.status         = status;
            this.responseBody   = responseBody;
        }
    }*/
    //add for pipl sushanhu 20220311 end
    /**
     * @return yyyyMMdd の日付文字列
     */
    public static String formatDate2Str(Date dt) {
        String rtn = null;
        if (dt == null) {
            return rtn;
        }
        rtn = String.valueOf(dt);
        rtn = rtn.replaceAll('-', '');
        if (rtn >= '40001231') {
            rtn = '99991231';
        } else if (rtn < '19000101') {
            rtn = '19000101';
        }
        return rtn;
    }

    public static Date parseStr2DateTimeDate(String pDateTime) {
        if (pDateTime == null || pDateTime.length() != 14) {
            return null;
        }
        return parseStr2Date(pDateTime.substring(0, 8));
    }
    public static Datetime parseStr2DateTime(String pDateTime) {
        if (pDateTime == null || pDateTime.length() != 14) {
            return null;
        }
        return parseStr2DateTime(pDateTime.substring(0, 8), pDateTime.substring(8, 14));
    }
    public static Datetime parseStr2DateTime(String pDate, String pTime) {
        Datetime rtn = null;
        try {
            if (pDate == null || pDate.length() != 8) {
                return rtn;
            } else if (pDate > '40001231') {
                pDate = '40001231';
            } else if (pDate < '19000101') {
                pDate = '19000101';
            }
            if (pDate == '19000101') {
                return null;
            }
            rtn = Datetime.newinstance(
                    Integer.valueOf(pDate.substring(0, 4)),
                    Integer.valueOf(pDate.substring(4, 6)),
                    Integer.valueOf(pDate.substring(6, 8)),
                    Integer.valueOf(pTime.substring(0, 2)),
                    Integer.valueOf(pTime.substring(2, 4)),
                    Integer.valueOf(pTime.substring(4, 6))
            );
        } catch (Exception ex) {
            System.debug(Logginglevel.ERROR, 'NFMUtil#parseStr2DateTime(' + pDate + ', ' + pTime + ')' + ex.getMessage());
        }
        return rtn;
    }
    /**
     * @param pStr yyyyMMdd の日付文字列
     */
    public static Date parseStr2Date(String pStr) {
        return parseStr2Date(pStr, true);
    }
    /**
     * @param pStr         yyyyMMdd の日付文字列
     * @param changeToNull 19000101以下の場合 null に変換するかどうか
     */
    public static Date parseStr2Date(String pStr, boolean changeToNull) {
        Date rtn = null;
        try {
            if (pStr == null || pStr.length() != 8) {
                return rtn;
            } else if (pStr > '40001231') {
                pStr = '40001231';
            } else if (pStr < '19000101') {
                pStr = '19000101';
            }
            if (pStr == '19000101' && changeToNull) {
                return null;
            }
            rtn = Date.newinstance(
                    Integer.valueOf(pStr.substring(0, 4)),
                    Integer.valueOf(pStr.substring(4, 6)),
                    Integer.valueOf(pStr.substring(6, 8))
            );
        } catch (Exception ex) {
            System.debug(Logginglevel.ERROR, 'NFMUtil#parseStr2Date(' + pStr + ')' + ex.getMessage());
        }
        return rtn;
    }
    
    /**
     * もしkeyがmapに存在しない場合、keyをそのまま戻る
     */
    public static String getMapValue(Map<String, String> transferMap, String col, String key, BatchIF_Log__c iflog) {
        String rtn = key;
        if (transferMap == null) {
            return rtn;
        }
        if (key == null) {
            return null;
        }
        if (col == null) {
            col = '';
        }
        rtn = transferMap.get(col + key);
        if (rtn == null) {
            iflog.ErrorLog__c += 'Warning! Please check [' + col + '] can not transfer key [' + key + ']\n';
            rtn = key;
        }
        return rtn;
    }

    /**
     * 先頭の指定文字をtrim
     *
     * @param trimChar 指定したtrim文字
     */
    public static String trimLeft(String orgStr, String trimChar) {
        String rtn = orgStr;
        if (orgStr == null) {
            return rtn;
        }
        if (trimChar == null) {
            return null;
        }
        rtn = orgStr.replaceAll('^' + trimChar + '+(?!$)', '');
        return rtn;
    }

    public static Boolean isSandbox() {
        //System.debug(URL.getSalesforceBaseUrl().getHost());
        //return URL.getSalesforceBaseUrl().getHost().left(2).equalsignorecase('cs');
        return [SELECT IsSandbox FROM Organization LIMIT 1].IsSandbox;

    }

     public static void sendToSap(String rowDataStr, String endpoint) {

        Http http = new Http();
        HttpRequest req = new HttpRequest();
        HTTPResponse res;
        String resb;

        req.setTimeout(120000);
        req.setEndpoint(endpoint);
        req.setMethod('POST');
        req.setHeader('Authorization', CBPR_Auth_Sap);
        req.setBody(rowDataStr);
 
        res = http.send(req);
        resb = res.getBody();
    }

    public static String sendToSapRet(String rowDataStr, String endpoint) {
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        HTTPResponse res;
        String resb;

        req.setTimeout(120000);
        req.setEndpoint(endpoint);
        req.setMethod('POST');
        req.setHeader('Authorization', CBPR_Auth_Sap);
        req.setBody(rowDataStr);
 
        res = http.send(req);
        resb = res.getStatus();
        return resb;
    }
    public static BatchIF_Log__c makeRowData(NFMUtil.Monitoring Monitoring, String NFMType, Object NFMData) {
        BatchIF_Log__c rowData = new BatchIF_Log__c();
        rowData.Type__c = NFMType;
        rowData.MessageGroupNumber__c = Monitoring.MessageGroupNumber;
        rowData.TransmissionDateTime__c = Monitoring.TransmissionDateTime;
        rowData.RowDataFlg__c = true;
        rowData.Log__c = '';
        rowData.ErrorLog__c = '';
        String rowDataStr = JSON.serialize(NFMData);
        if (rowDataStr.length() > 0) {
            Integer splitIdx = 1;
            while (rowDataStr.length() > 0) {
                if (splitIdx == 1) {
                    rowData.put('Log__c', rowDataStr.substring(0, (rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length())));
                } else if (splitIdx == 13) {
                    rowData.ErrorLog__c = rowDataStr;
                    break;
                } else {
                    rowData.put('Log' + splitIdx + '__c', rowDataStr.substring(0, (rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length())));
                }
                splitIdx++;
                rowDataStr = rowDataStr.substring((rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length()));
            }
        }
        return rowData;
    }
    public static BatchIF_Log__c saveRowData(NFMUtil.Monitoring Monitoring, String NFMType, Object NFMData) {
        BatchIF_Log__c rowData = new BatchIF_Log__c();
        rowData.Type__c = NFMType;
        rowData.MessageGroupNumber__c = Monitoring.MessageGroupNumber;
        rowData.TransmissionDateTime__c = Monitoring.TransmissionDateTime;
        rowData.RowDataFlg__c = true;
        rowData.Log__c = '';
        rowData.ErrorLog__c = '';
        insert rowData;
        String rowDataStr = JSON.serialize(NFMData);
        if (rowDataStr.length() > 0) {
            Integer splitIdx = 1;
            while (rowDataStr.length() > 0) {
                if (splitIdx == 1) {
                    rowData.put('Log__c', rowDataStr.substring(0, (rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length())));
                } else if (splitIdx == 13) {
                    rowData.ErrorLog__c = rowDataStr;
                    break;
                } else {
                    rowData.put('Log' + splitIdx + '__c', rowDataStr.substring(0, (rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length())));
                }
                splitIdx++;
                rowDataStr = rowDataStr.substring((rowDataStr.length() > MaxLogColumnLength ? MaxLogColumnLength : rowDataStr.length()));
            }
            update rowData;
        }
        return rowData;
    }
    

    public static String getRowDataStr(BatchIF_Log__c rowData) {
        String rowDataStr = rowData.Log__c;
        Integer splitIdx = 2;
        while (rowData.get('Log' + splitIdx + '__c') != null && String.isBlank('' + rowData.get('Log' + splitIdx + '__c')) == false) {
            rowDataStr += rowData.get('Log' + splitIdx + '__c');
            splitIdx++;
            if (splitIdx == 13) break;
        }
        if (String.isBlank(rowData.ErrorLog__c) == false) {
            rowDataStr += rowData.ErrorLog__c;
        }
        return rowDataStr;
    }
    //转换表转换后的数据
    public static Map<String,String> BatchIF_Transfer(String object_API_Name) {

        Map<String, String> result = 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 = :object_API_Name];
        for (BatchIF_Transfer__c t : transferList) {
            result.put(t.Column__c + t.External_value__c, t.Internal_value__c);
        }
        return result;
    }
//add for pipl sushanhu 20220311 start
    /*global class NFMResponse{
        public Boolean SFStatus;
        public String SFMessage;
        public StaticResponse staticResponse;
    }
    global class StaticResponse{
        public string status;
        public String Message;
        public StaticResponse(){
            status='0';
            Message='';
        }
    }
    public static NFMResponse getNFMResponse(){
        NFMResponse  result=new NFMResponse();
        result.staticResponse =new StaticResponse();
        return result;
        
    }*/
//add for pipl sushanhu 20220311 end

    public static Boolean EscapeSBG001TriggerHandler = false;
}