/**
 * FSE日报
 */
@RestResource(urlMapping = '/NFM608/*')
global with sharing class NFM608Rest {
    public static final String LOG_TYPE = 'NFM608';
    global class GeData {
        public String mngCd; //工程师管理编码
        public String departmentCd; //科室编码
        public String applicantId; //报修人ID
        public String synchroDate; //同步日期
        public String replyID; //活动草稿ID
        public String visitInfo; //任务类型
        public String visitStartDate; //开始时间
        public String visitEndDate; //结束时间
        public String replyResult; //应对结果
        public String visitDistinction; //拜访区分
        public String visitPurpose; //拜访目的
        public String activityDifferentiation; //活动区分
    }
    @HttpPost
    global static void doPost() {
        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        
        GeData ged = (GeData) JSON.deserializeStrict(strData, GeData.class);

        if (ged == null) {
            return;
        }

        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = LOG_TYPE;
        iflog.ErrorLog__c = '';
        iflog.Log__c = 'callout start\n';

        BatchIF_Log__c rowData = NFMUtil.makeRowData(iflog, LOG_TYPE, ged);
        insert rowData;
        if (String.isBlank(rowData.Log__c) == false) {
            executefuture(rowData.Id);
        }

        // JSONを戻す
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        String jsonResponse = '{"status": "Success", "Message":"成功"}';
        res.responseBody = Blob.valueOf(jsonResponse);
        return;

    }
    @future(callout = true)
    global static void executefuture(String rowData_Id) {
        main(rowData_Id);
    }
    global static void main(String rowData_Id) {
        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id =: rowData_Id];
        String logstr = rowData.MessageGroupNumber__c + ' start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = LOG_TYPE;
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;
        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        GeData ged = (GeData) JSON.deserialize(rowDataStr, GeData.class);
        if (ged == null) {
            return;
        }
        Savepoint sp = Database.setSavepoint();
        try {

            // 必填字段验证 Start
            String dataComplete = verify(ged);
            // 必填字段验证 End
            if (!String.isBlank(dataComplete)) {
                logstr += dataComplete;
            } else {


                String mngCd = ged.mngCd;
                // 获取社内用户Id
                Id userId = getUserId(mngCd); 
                if (userId == null) {
                    logstr += '社内用户 [ ' + mngCd + ' ],不存在或未启用或已离职，此条数据跳过不执行!\n';
                    return;
                }
                // 获取日报
                Daily_Report__c drc = getDaily_Report(ged, userId);

                // 获取科室
                Account departmentAccount = getdepartmentAccount(ged.departmentCd);
                if (departmentAccount == null) {
                    logstr += '客户 [ ' + ged.departmentCd + ' ] 不存在或已无效，此条数据跳过不执行\n';
                    return;
                }

                String strType = getVisitType(ged.visitDistinction);
                if (String.isBlank(strType)) {
                    logstr += '拜访区分 [ ' + ged.visitDistinction + ' ]无效，此条数据跳过不执行 \n';
                    return;
                }
                // 查找访问对象
                String contactId = null;
                if (String.isNotBlank(ged.applicantId)) {
                    contactId = getContact(ged.applicantId,departmentAccount.Id);
                    if (String.isBlank(contactId)) {
                        logstr += '访问对象 [ ' + ged.applicantId + ' ] 不存在或不在 客户 [ '+departmentAccount.Name+'('+ged.departmentCd+')下 ]，数据正常保存，特此记录\n';
                    }    
                }

                Event__c report = new Event__c();
                report.ServicePlatformCode__c = ged.replyID;//AWS活动编码
                report.Account_ID__c = departmentAccount.Id;//科室
                report.whatid__c = departmentAccount.Id;
                // report.VisitType__c = ged.visitInfo;//任务类型
                report.Visitor1_ID__c = contactId; //訪問者1
                report.StartDateTime__c = NFMUtil.parseStr2DateTime(ged.visitStartDate);//开始时间
                report.ActivityDate__c = NFMUtil.parseDateTimeStr2Date(ged.visitStartDate);//活动日期
                report.EndDateTime__c = NFMUtil.parseStr2DateTime(ged.visitEndDate);//结束时间
                report.Description__c = ged.replyResult;//结果

                report.Location__c = departmentAccount.Name; //位置

                report.Activity_Type2__c = strType;//拜访区分
                // report.Activity_PurposeEscFSE__c  = ged.visitPurpose;//拜访目的
                // report.Purpose_TypeFSE__c  = ged.activityDifferentiation;//活动区分
                report.Daily_Report__c = drc.Id;//日报
                insert report;
                logstr +=  '报告一览 [ '+ged.replyID+' ] 保存成功！\n';
            }
            
            rowData.retry_cnt__c = 0; //必加
        } catch (Exception ex) {
            // エラーが発生した場合
            Database.rollback(sp);
            logstr += '\n' + ex.getMessage();
            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;

            // 异常重发
            rowData = NFMUtil.LogAutoSend(rowData, ex, null);
            update iflog;
        } 
        finally {
            update rowData;
            iflog.Log__c = logstr;
            update iflog;
        }


    }
    // 查找 访问科室
    private static Account getdepartmentAccount(String departmentCd) {
        Account acc = [select Id, Name from Account where Management_Code__c =: departmentCd];
        return acc;

    }

    // 查找 对应科室下的拜访对象
    public static String getContact(String applicantId,String departmentAccountId) {
        String contactId = null;
        List < Contact > contactList = [SELECT Id FROM Contact WHERE CManageCode__c =: applicantId AND AccountId =:departmentAccountId];
        if (contactList.size() > 0) {
            contactId = contactList[0].Id;
        }
        return contactId;
    }
    // 获取日报，不存在 创建
    private static Daily_Report__c getDaily_Report(GeData ged, Id userId) {
        Daily_Report__c result = new Daily_Report__c();
        // 获取 活动日期
        Date visitStartDate = null;
        if (ged.visitStartDate.length() >= 8) {
            visitStartDate = NFMUtil.parseStr2Date(ged.visitStartDate.subString(0, 8));
        }


        List < Daily_Report__c > drcs = [select Id, Reporter__r.Employee_No__c from Daily_Report__c where Reported_Date__c =: visitStartDate and Reporter__r.Employee_No__c =: ged.mngCd];
        if (drcs.size() > 0) {
            result = drcs[0];
        } else {
            // 创建日报
            result = createDR(userId, visitStartDate);
            insert result;
        }
        return result;
    }


    // 获取有效的社内用户
    private static Id getUserId(String mngCd) {
        Id userId = null;
        User user = [SELECT Id, Employee_No__c, Contact.CManageCode__c
            FROM User
            WHERE IsActive = true AND Stay_or_not__c = '在职'
            AND Employee_No__c =: mngCd
        ];
        userId = user != null ? user.Id : null;
        return userId;
    }
    // 日报字段赋值
    private static Daily_Report__c createDR(id userId, Date reportDate) {

        Daily_Report__c report = new Daily_Report__c();
        report.Reporter__c = userId;
        report.Status__c = '作成中';
        report.Daily_Report_Data_Type__c = '通常';
        report.Reported_Date__c = reportDate;
        report.Working_Time_From__c =
            Datetime.newInstance(reportDate.year(),
                reportDate.month(),
                reportDate.day(), 8, 45, 0);
        report.Working_Time_To__c =
            Datetime.newInstance(reportDate.year(),
                reportDate.month(),
                reportDate.day(),
                17, 30, 0);
        report.OwnerId = userId;
        return report;
    }
    
    private static String getVisitType(String visitDistinction) {
        String result = null;
        Map < String, String > VisitTypeMap = new Map < String, String > ();
        VisitTypeMap.put('公司工作', '社内活動');
        VisitTypeMap.put('用户拜访', '病院');
        VisitTypeMap.put('经销商支持', '販売店');
        VisitTypeMap.put('学术会议', '社外イベント');
        VisitTypeMap.put('移动', '移動');
        VisitTypeMap.put('休假', '休暇');
        result = VisitTypeMap.get(visitDistinction);
        return result;
    }
    // 字段验证
    private static String verify(GeData ged) {
        String result = '';
        String replyID = '';
        if (ged.mngCd == null) {
            result += 'DataError: 工程师管理编码 [ mngCd ] is null!\n';
        }
        if (String.isBlank(ged.replyID)) {
            result += 'DataError: 活动草稿ID [ replyID ] is null!\n';
        } else {
            replyID = '活动草稿ID [ ' + ged.replyID + ' ]\n';
        }

        if (ged.departmentCd == null) {
            result += 'DataError: 科室编码 [ departmentCd ] is null!\n';
        }
        if (ged.synchroDate == null) {
            result += 'DataError: 同步日期 [ synchroDate ] is null!\n';
        }
        if (String.isBlank(ged.visitDistinction)) {
            result += 'DataError: 拜访区分 [ visitDistinction ] is null!\n';
        }
        if (String.isBlank(ged.visitStartDate)) {
            result += 'DataError: 开始时间  [ visitStartDate ] is null!\n';
        }

        if (String.isBlank(ged.visitEndDate)) {
            result += 'DataError: 结束时间  [ visitEndDate ] is null!\n';
        }
        if (String.isNotBlank(replyID) && String.isNotBlank(result)) {
            result = replyID + result;
        }
        return result;
    }
}