@RestResource(urlMapping='/OFSEventEdit/*')
global with sharing class OFSEventEditRest {

    @HttpPost
    global static void doPost() {
        system.debug('OFSEventEditRest.start');
        Map<String, String> requestMap = (Map<String, String>) JSON.deserializeStrict(RestContext.request.requestBody.toString(), Map<String, String>.class);
        Map<String, String> responseMap = createDailyReport(requestMap);
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        String jsonResponse = JSON.serialize(responseMap);
        res.responseBody = blob.valueOf(jsonResponse);
        system.debug('OFSEventEditRest.end');
    }
    public static Map<String, String> createDailyReport(Map<String, String> requestMap) {
        system.debug('createDailyReport.start');
        String sub = requestMap.get('sub');
        String at2 = requestMap.get('at2');
        String pt = requestMap.get('pt');
        Long stime = String.isBlank(requestMap.get('stime')) == false ? Long.valueOf(requestMap.get('stime')) : null;
        System.debug('createDailyReport stime=' + requestMap.get('stime') + ', stime=' + stime);
        Long etime = String.isBlank(requestMap.get('etime')) == false ? Long.valueOf(requestMap.get('etime')) : null;
        String eid = requestMap.get('eid');
        String result = requestMap.get('result');
        String accId = requestMap.get('accId');
        String accName = requestMap.get('accName');
        String mainPlace = requestMap.get('mainPlace');
        String opp1Id = requestMap.get('opp1Id');
        String opp1 = requestMap.get('opp1');
        String opp2Id = requestMap.get('opp2Id');
        String opp2 = requestMap.get('opp2');
        String opp3Id = requestMap.get('opp3Id');
        String opp3 = requestMap.get('opp3');
        String mcId = requestMap.get('mcId');
        String mcName = requestMap.get('mcName');

        Date d = Datetime.newInstance(stime).date();
        Event e = [select Subject, Activity_Type2__c, Id, ActivityDate, EventC_ID__c, StartDateTime, EndDateTime from Event where Id = :eid];
        return createDailyReport2(d, e, sub, at2, pt, stime, etime, eid, result, accId, accName, mainPlace,
                opp1Id, opp1, opp2Id, opp2, opp3Id, opp3, mcId, mcName);
    }
    public static Map<String, String> createDailyReport2(Date d, Event e,
            String sub, String at2, String pt, Long stime, Long etime, String eid, String result, String accId, String accName, String mainPlace,
            String opp1Id, String opp1, String opp2Id, String opp2, String opp3Id, String opp3, String mcId, String mcName
    ) {
        system.debug('createDailyReport2.start eid=' + eid);
        if (String.isBlank(eid)) {
            Map<String, String> rtnMap = new Map<String, String>();
            rtnMap.put(System.Label.OFSErrorStatus, System.Label.OFSErrorFailure);
            rtnMap.put(System.Label.OFSErrorMessage, 'activity id is required');
            return rtnMap;
        }
        Event__c ec;
        if (e.EventC_ID__c != null && String.isNotBlank(e.EventC_ID__c)) {
        	ec = [select Id, Description__c, Event_ID__c, Subject__c, StartDateTime__c, EndDateTime__c, Activity_Type2__c from Event__c where Id = :e.EventC_ID__c];
        } else {
        	List<Event__c> ecList = [select Id, Description__c, Event_ID__c, Subject__c, StartDateTime__c, EndDateTime__c, Activity_Type2__c from Event__c where Event_ID__c = :eid];
        	if (ecList.size() <= 0) {
        		ec = null;
        	} else {
        		ec = ecList[0];
                system.debug('createDailyReport ec.Id=' + ec.Id);
        	}
        }
        
        //todo check dailyreport
        if (ec != null) {
        	ec.Description__c = result;
        	ec.Subject__c = sub;
        	ec.Activity_Type2__c = at2;
        	ec.Purpose_Type__c = pt;
            ec.Main_Visit_Location__c = mainPlace;
        	ec.StartDateTime__c = Datetime.newInstance(stime);
        	ec.EndDateTime__c = Datetime.newInstance(etime);
        	ec.Event_ID__c = eid;
        	if (String.isNotBlank(accName)) {
        		ec.Location__c = accName;
        		ec.Free_Input__c = true;
        		if (String.isNotBlank(accId)) {
        			ec.Account_ID__c = accId;
	        		ec.Free_Input__c = false;
	        		ec.whatid__c = accId;
        		}
        	}
//            if (String.isBlank(v1Id) == false) {
//                ec.Visitor1__c = v1Name;
//                ec.Visitor1_ID__c = v1Id;
//            }
//            if (String.isBlank(v2Id) == false) {
//                ec.Visitor2__c = v2Name;
//                ec.Visitor2_ID__c = v2Id;
//            }
//            if (String.isBlank(v3Id) == false) {
//                ec.Visitor3__c = v3Name;
//                ec.Visitor3_ID__c = v3Id;
//            }
//            if (String.isBlank(v4Id) == false) {
//                ec.Visitor4__c = v4Name;
//                ec.Visitor4_ID__c = v4Id;
//            }
//            if (String.isBlank(v5Id) == false) {
//                ec.Visitor5__c = v5Name;
//                ec.Visitor5_ID__c = v5Id;
//            }
        	if (String.isNotBlank(opp1Id)) {
        		ec.Related_Opportunity1__c = opp1;
        		ec.Related_Opportunity1_ID__c = opp1Id;
        	} else {
        		ec.Related_Opportunity1__c = null;
        		ec.Related_Opportunity1_ID__c = null;
        	}
//        	if (String.isNotBlank(opp2Id)) {
//        		ec.Related_Opportunity2__c = opp2;
//        		ec.Related_Opportunity2_ID__c = opp2Id;
//        	} else {
//                ec.Related_Opportunity2__c = null;
//                ec.Related_Opportunity2_ID__c = null;
//        	}
//        	if (String.isNotBlank(opp3Id)) {
//        		ec.Related_Opportunity3__c = opp3;
//        		ec.Related_Opportunity3_ID__c = opp3Id;
//        	} else {
//                ec.Related_Opportunity3__c = null;
//                ec.Related_Opportunity3_ID__c = null;
//        	}
        	if (String.isNotBlank(mcId)) {
        		ec.Related_Service1__c = mcName;
        		ec.Related_Service1_ID__c = mcId;
        	} else {
                ec.Related_Service1__c = null;
                ec.Related_Service1_ID__c = null;
        	}
        	try {
                update ec;
                Map<String, String> rtnMap = new Map<String, String>();
                rtnMap.put(System.Label.OFSErrorStatus, System.Label.OFSErrorSuccess);
                rtnMap.put(System.Label.OFSErrorMessage, ec.Id);
                rtnMap.put('refreshDate', '' + d);
                return rtnMap;
            } catch ( Exception ex ) {
                //error message:cannot update exception
                Map<String, String> rtnMap = new Map<String, String>();
                rtnMap.put(System.Label.OFSErrorStatus, System.Label.OFSErrorFailure);
                rtnMap.put(System.Label.OFSErrorMessage, '' + ex);
                return rtnMap;
            }
        } else {
            List<Daily_Report__c> drList = [SELECT Id, Status__c FROM Daily_Report__c WHERE OwnerId =:UserInfo.getUserId() and Reported_Date__c =:d];
            Daily_Report__c dr;
            if (drList.size() <= 0) {
                dr = new Daily_Report__c();
                dr.Reporter__c = UserInfo.getUserId();
                dr.Status__c = '作成中';
                dr.Daily_Report_Data_Type__c = '通常';
                dr.Reported_Date__c = d;
                dr.Working_Time_From__c = Datetime.newInstance(d.year(), d.month(), d.day(), 9, 0, 0);
                dr.Working_Time_To__c = Datetime.newInstance(d.year(), d.month(), d.day(), 18, 0, 0);
                try {
                    insert dr;
                } catch ( Exception ex ) {
                    //error message:cannot update exception
                    Map<String, String> rtnMap = new Map<String, String>();
                    rtnMap.put(System.Label.OFSErrorStatus, System.Label.OFSErrorFailure);
                    rtnMap.put(System.Label.OFSErrorMessage, '' + ex);
                    return rtnMap;
                }
            } else {
               dr = drList[0];
            }
  
			ec = new Event__c();
			ec.Description__c = result;
	    	ec.Subject__c = sub;
	    	ec.Activity_Type2__c = at2;
            ec.Purpose_Type__c = pt;
            ec.Main_Visit_Location__c = mainPlace;
	    	ec.StartDateTime__c = Datetime.newInstance(stime);
	    	ec.EndDateTime__c = Datetime.newInstance(etime);
	    	ec.ActivityDate__c = d;
	    	ec.Daily_Report__c = dr.Id;
	    	ec.Event_ID__c = eid;
	    	if (String.isNotBlank(accName)) {
        		ec.Location__c = accName;
        		ec.Free_Input__c = true;
        		if (String.isNotBlank(accId)) {
        			ec.Account_ID__c = accId;
	        		ec.Free_Input__c = false;
	        		ec.whatid__c = accId;
        		}
        	}
//            if (String.isBlank(v1Id) == false) {
//                ec.Visitor1__c = v1Name;
//                ec.Visitor1_ID__c = v1Id;
//            }
//            if (String.isBlank(v2Id) == false) {
//                ec.Visitor2__c = v2Name;
//                ec.Visitor2_ID__c = v2Id;
//            }
//            if (String.isBlank(v3Id) == false) {
//                ec.Visitor3__c = v3Name;
//                ec.Visitor3_ID__c = v3Id;
//            }
//            if (String.isBlank(v4Id) == false) {
//                ec.Visitor4__c = v4Name;
//                ec.Visitor4_ID__c = v4Id;
//            }
//            if (String.isBlank(v5Id) == false) {
//                ec.Visitor5__c = v5Name;
//                ec.Visitor5_ID__c = v5Id;
//            }
        	if (String.isNotBlank(opp1Id)) {
        		ec.Related_Opportunity1__c = opp1;
        		ec.Related_Opportunity1_ID__c = opp1Id;
        	}
        	if (String.isNotBlank(opp2Id)) {
        		ec.Related_Opportunity2__c = opp2;
        		ec.Related_Opportunity2_ID__c = opp2Id;
        	}
        	if (String.isNotBlank(opp3Id)) {
        		ec.Related_Opportunity3__c = opp3;
        		ec.Related_Opportunity3_ID__c = opp3Id;
        	}
        	if (String.isNotBlank(mcId)) {
        		ec.Related_Service1__c = mcName;
        		ec.Related_Service1_ID__c = mcId;
        	}
	    	try {
                insert ec;
                Map<String, String> rtnMap = new Map<String, String>();
                rtnMap.put(System.Label.OFSErrorStatus, System.Label.OFSErrorSuccess);
                rtnMap.put(System.Label.OFSErrorMessage, ec.Id);
                rtnMap.put('drId', '' + dr.Id);
                rtnMap.put('refreshDate', '' + d);
                return rtnMap;
            } catch ( Exception ex ) {
                //error message:cannot update exception
                Map<String, String> rtnMap = new Map<String, String>();
                rtnMap.put(System.Label.OFSErrorStatus, System.Label.OFSErrorFailure);
                rtnMap.put(System.Label.OFSErrorMessage, '' + ex);
                return rtnMap;
            }
        }
    }
}