/**********************************************************************
 * @msg:
 *   1.上传OBPM的数据里需要包含申请人和其他共有权限的人，但不需要区分
 *   2.传输时使用员工编号，多人时用逗号分隔
*************************************************************************/
public without sharing class NFM703Controller {

    private static final String LOG_TYPE = 'NFM703';
    // private static final String API = '/admin/api/repair/save';
    public static String logstr;
    public static String status;      
    public static String ResponseBody;
    public static String Result;
    
    // public NFM703Controller() {
        // public GeDatas GeDatas;
        
    // }
    public class Response {
        public Result Result;
    }
    public Class Result{
        public String Result;
        public String Message;
    }
    public class NFM703 {
        // public GeDatas GeDatas;
        public NFMUtil.Monitoring Monitoring;
        public GeData[] GeData;
        
    }
    public Class GeData {
	    public String Num; //会议编码=TrainingCode__c
		public String Name; //会议名称
		public String StartDate; //开始日期=StartDate
		public String EndDate; //结束日期=EndDate
		public String ActivityTypeName; //活动形式
		public String ExpectedOlympusAttendance; //预计参会Olympus人数
		public String ExpectedHcpAttendance; //预计参会HCP人数
		public String BudgetType; //预算类型=Implementation_Purpose__c
		public String OfficeCategory; //科室分类=OfficeCategory__c
		public String MeetingType; //会议类型=Meeting_Type__c
		public String StateMaster; //省=State_Master__c
		public String CityMaster; //市=City_Master__c
		public String WorkshopPlace; //会场地点=WorkshopPlace__c
		public String HostName; //会议主办方=HostName__c
		public String CooperatorCompany; //会议承办方=cooperatorCompany__c
        public String SharedEditing; // 申请人+共同编辑人=Shared_Editing__c
    }
    @future(callout = true)
    public static void callout(String iflog_Id, List < String > camIdList) {
        executeNotFuture(iflog_Id, camIdList);
    }
    public static void executeNotFuture(String iflog_Id, List < String > camIdList) {
        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 = '';
        NFM703 gds = new NFM703();
        gds.GeData = new List < GeData > ();
        BatchIF_Log__c rowData = null;
	    List < Campaign > camList = [select id,
	    								TrainingCode__c,
	    								Name,Num__c,
	    								StartDate,
	    								EndDate,
	    								Implementation_Purpose__c,
	    								OfficeCategory__c,
	    								Meeting_Type__c,
	    								State_Master__r.Name,
	    								City_Master__r.Name,
	    								WorkshopPlace__c,
                                        Expected_Olympus_Attendance__c,
                                        Expected_Hcp_Attendance__c,
                                        Activity_Type_Name__c,
	    								HostName__c,
	    								cooperatorCompany__c, 
                                        Owner.Employee_No__c, 
                                        Shared_Editing__c, 
                                        Carbon_Copy__c, 
	    								IF_Approved__c from Campaign where id in: camIdList];
	    String logstr = ' ' + 'NumberOfRecord=' + camList.size() + '\n';


        NFMUtil.Monitoring mon = new NFMUtil.Monitoring();
        mon.Tag 				 = 'MSGH';
		mon.Sender 				 = 'SFDC';
		mon.Receiver 			 = 'OBPM';
		mon.MessageType 		 = 'NFM703';
		mon.MessageGroupNumber 	 = nowStr;
		mon.NumberOfRecord 		 = '' + camIdList.size();
		mon.TransmissionDateTime = nowStr;
		mon.Text = '';

        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 = 'Application_for_Conference_Adjudication__c')
                                          ];
        for (BatchIF_Transfer__c t : transferList) {
            transferMap.put(t.Column__c + t.Internal_value__c, t.External_value__c);
        }

        try {
        		
        	for (Campaign cam : camList) {
                GeData ged = new GeData();
                // ged.Num 			  = cam.TrainingCode__c;
                ged.Num 			  = cam.Num__c;
                ged.Name 			  = cam.Name;
        		ged.StartDate 		  = NFMUtil.formatDate2StrSpo(cam.StartDate);
        		ged.EndDate 		  = NFMUtil.formatDate2StrSpo(cam.EndDate);
                ged.BudgetType        = cam.Implementation_Purpose__c;
				ged.OfficeCategory 	  = NFMUtil.getMapValue(transferMap, 'OfficeCategory__c', cam.OfficeCategory__c, iflog);
				ged.MeetingType 	  = cam.Meeting_Type__c;
                ged.ActivityTypeName  = cam.Activity_Type_Name__c;
				ged.StateMaster 	  = cam.State_Master__r.Name;                 
				ged.CityMaster        = cam.City_Master__r.Name;
				ged.WorkshopPlace     = cam.WorkshopPlace__c;
				ged.HostName 		  = cam.HostName__c;
				ged.CooperatorCompany = cam.cooperatorCompany__c;
                ged.ExpectedOlympusAttendance = String.valueOf(cam.Expected_Olympus_Attendance__c);
                ged.ExpectedHcpAttendance = String.valueOf(cam.Expected_Hcp_Attendance__c);
                // 暂时定义为主担当，后续添加其他共享人
                ged.SharedEditing     = Modify_Sharing(cam.Owner.Employee_No__c, cam.Shared_Editing__c, cam.Carbon_Copy__c);
                gds.GeData.add(ged);

    		}

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


                logstr =  '\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 = '';


                NFM703 nfm703 = new NFM703();
                nfm703.GeData = new List < GeData >();
                nfm703.GeData = gds.GeData;
                nfm703.Monitoring = new NFMUtil.Monitoring();
                nfm703.Monitoring = Monitoring;

                rowData = NFMUtil.makeRowData(Monitoring, LOG_TYPE, nfm703);
                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;
        }
        // upsert iflog;

        System.debug(Logginglevel.DEBUG, 'NFM703_' + iflog.Name + ' end');
        iflog.Log__c = iflog.Log__c + logstr;
        // iflog.Log__c = logstr;
        upsert iflog;
	}
    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);
    }

    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 {
            NFMUtil.response response =
                NFMUtil.sendToSapStatusAndBody(rowDataStr, NFMUtil.NFM703_ENDPOINT);
            status = response.status;
            ResponseBody = response.responseBody;
            Response resultList = ( Response ) JSON.deserializeStrict(ResponseBody, Response.class);
            System.debug('NFM703Log--status->'+ status);
            Result = resultList.Result.Result;
            // status = ''
            // if ('OK'.equals(status)) {
            // if (ResponseBody.contains('00')) {
            if (Result.equals('00')) {
                logstr += ResponseBody+'\n';

                rowDataSFDC.retry_cnt__c = 0;
            } 
            else {
                rowDataSFDC = NFMUtil.LogAutoSend(rowDataSFDC, null, status);
            }
        } catch (Exception ex) {
            // TODO IOException
            // エラーが発生した場合
            System.debug(Logginglevel.ERROR, LOG_TYPE + iflog.Name + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, LOG_TYPE + iflog.Name + ':' + ex.getStackTraceString());
            logstr += ex.getMessage();
            iflog.ErrorLog__c += ex.getMessage() + '\n';
            iflog.ErrorLog__c += ex.getStackTraceString() + '\n';
            rowDataSFDC = NFMUtil.LogAutoSend(rowDataSFDC, null, status);
        }
        iflog.Log__c = logstr;
        upsert iflog;
        upsert rowDataSFDC;

    }

    public static String Modify_Sharing(String owner, String shared_editors, String carbon_copies) {
        if (String.isBlank(owner) && String.isBlank(shared_editors) && String.isBlank(carbon_copies)) {
            return '';
        }
        String ret = '';
        if (String.isNotBlank(owner)) {
            ret = owner;
        }
        if (String.isNotBlank(shared_editors)) {
            if (ret.length() > 0) {
                ret = ret + ',';
            }
            ret = ret + shared_editors;
        }
        if (String.isNotBlank(carbon_copies)) {
            if (ret.length() > 0) {
                ret = ret + ',';
            }
            ret = ret + carbon_copies;
        }
        return ret;
    }
}