@RestResource(urlMapping='/OFSEventCreate/*')
global with sharing class OFSEventCreateRest {
    private static final String HOSPITAL_STRING = '病院';
    private static final String AGENCY_STRING = '販売店';
    private static final String CAMPAIGN_STRING = '社外イベント';
    private static final String DEP_TYPE = '診療科';
    private static final String AGY_TYPE = '販売店';

    @HttpPost
    global static void doPost(String sub, String at2, String pt, String dt, Long stime, Long etime, String accid, String mainPlace, String cid, String oid, String mid, String loc) {
        system.debug('OFSEventCreateRest.start');
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');

        String jsonResponse;
        Date startDate;
        if (String.isBlank(dt) == false) {
            startDate = Date.valueOf(dt);           // yyyy-MM-dd の形式
        } else {
            startDate = Date.today();
        }
        Event e = new Event(
            OwnerId = UserInfo.getUserId(),
            ActivityDate = startDate,
            StartDateTime = Datetime.newInstance(stime),
            EndDateTime = Datetime.newInstance(etime),
            Activity_Type2__c = at2,
            Purpose_Type__c = pt,
            Main_Visit_Location__c = mainPlace
        );
        if (!String.isBlank(sub)) {
            e.Subject = sub;
        }else{
            //no subject
        }
        if(!String.isBlank(loc)){
            e.Location = loc;
        }else{
            //no Location
        }
        // 顧客
        String aid = accid;
        if (!String.isBlank(aid)) {
            Account acc = null;
            List<Account> accs = [select Id, RecordType.Name, Name from Account where Id = :aid];
            if (accs.size() <= 0) {
                //TODO error
                system.debug('Restaid:'+ aid);
            } else {
                acc = accs[0];
                e.whatid__c = acc.Id;
                e.Location = acc.Name;
            }
            // 診療科
            if (acc.RecordType.Name.startsWith(DEP_TYPE)) {
                if (String.isBlank(at2)) {
                    e.Activity_Type2__c = HOSPITAL_STRING;
                }
                // 引合
                if (!String.isBlank(oid)) {
                    List<Opportunity> opp = [select Id, Name from Opportunity where Id = :oid and AccountId = :aid and StageName in ('引合','注残','出荷') and RecordTypeId =:System.label.OFSEvent_1]; //niwu OFSEvent_1 -01210000000QekK
                    // 念のためマッチするかを判断
                    if (opp.size() > 0) {
                        e.Related_Opportunity1__c = opp[0].Name;
                        e.Related_Opportunity1_ID__c = opp[0].Id;
                    }
                }
                // サビコン
                if (!String.isBlank(mid)) {
                    List<Maintenance_Contract__c> mc = [select Id, Name from Maintenance_Contract__c where Id = :mid and Department__c = :aid];
                    // 念のためマッチするかを判断
                    if (mc.size() > 0) {
                        e.Related_Service1__c = mc[0].Name;
                        e.Related_Service1_ID__c = mc[0].Id;
                    }
                }
            // 販売店
            } else if (acc.RecordType.Name.startsWith(AGY_TYPE)) {
                if (String.isBlank(at2)) {
                    e.Activity_Type2__c = AGENCY_STRING;
                }
                // 引合
                if (!String.isBlank(oid)) {
                    List<Opportunity> opp = [select Id, Name from Opportunity where Id = :oid and (Agency1__c = :aid or Agency2__c = :aid) and StageName in ('引合','注残','出荷') and RecordTypeId =:System.Label.OFSEvent_1];
                    // 念のためマッチするかを判断
                    if (opp.size() > 0) {
                        e.Related_Opportunity1__c = opp[0].Name;
                        e.Related_Opportunity1_ID__c = opp[0].Id;
                    }
                }
            } else {
                // なにもしない by yu 20141215
            }
        // Campaign
        } else if (!String.isBlank(cid)) {
            Campaign cam = [select Id, Name from Campaign where Id = :cid];
            e.Location = cam.Name;
            e.whatid__c = cam.Id;
            if (String.isBlank(at2)) {
                e.Activity_Type2__c = CAMPAIGN_STRING;
            }
        } else {
            // TODO error
        }

        try {
            insert e;
            res.statusCode = 200;
            jsonResponse = '{"'+ System.Label.OFSErrorStatus +'": "'+ System.Label.OFSErrorSuccess +'", "'+ System.Label.OFSErrorMessage +'": "'+ e.Id +'", "refreshDate":"'+ startDate +'"}';
            res.responseBody = blob.valueOf(jsonResponse);
            return;
        } catch ( Exception ex ) {
            //error message:cannot update exception
            res.statusCode = 200;
            jsonResponse = '{"'+ System.Label.OFSErrorStatus +'": "'+ System.Label.OFSErrorFailure +'", "'+ System.Label.OFSErrorMessage +'": "'+ ex +'"}';
            res.responseBody = blob.valueOf(jsonResponse);
            return;
        }
    }
}