/**
 * ASE日报
 */
@RestResource(urlMapping = '/NFM607/*')
global with sharing class NFM607Rest {
    //add to AWS 回复 start sushanhu 20220225 
    static Boolean SFStatus=true;
    static String SFMessage='';
   //add to AWS 回复 end sushanhu 20220225 
    private static final String LOG_TYPE = 'NFM607';
    //add Response to aws 20220221 add sushanhu
    static NFMUtil.NFMResponse result = new NFMUtil.NFMResponse();

    global class GeData {
        public String mngCd; //  ASE管理编码
        public String activityDailyDate; //  活动日报日期
        public String strategicDepartmenCd; //战略科室编码
        public String departmentCd; //科室编码
        public String customerNm; //客户姓名
        public String activityID; //活动ID
        public String purposeOfVisit; //拜访目的
        public String activityDifferentiation; //活动区分

        public String taskItem;// 任务类型
        public String visitDistinction; //拜访区分

        public String activityStartTime; //活动开始时间
        public String activityEndTime; //活动结束时间
        public String workDesc; //工作描述
        // add 加密字段索引 add 20220210
        public String DataId; //加密字段索引
        //add 加密字段密文 20220210
        public String customerNmEncrypted; 
           //add             wangweipeng         2022/02/14      start
        public String customerTel;//客户手机号码
        public String workPlace;//工作场所
           //add             wangweipeng         2022/02/14      end
        //add 20220216 sushanhu start   
        public String customerTelEncrypted;
        public String workPlaceEncrypted;
        // add 20220216 sushanhu end


    }

    @HttpPost
    global static void execute() {
        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        List < GeData > ges = (List < GeData > ) JSON.deserializeStrict(strData, List < GeData > .class);
        system.debug('ges---'+ges);
        if (ges == 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, ges);
        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);
        //updata response toAWS 20220225 sushanhu start
        NFMUtil.NFMResponse result = NFMUtil.getNFMResponse();
        result.SFStatus=SFStatus;
        result.SFMessage=SFMessage;
        String jsonResponse =JSON.serialize(result);
        system.debug('result---'+jsonResponse);
        res.responseBody = blob.valueOf(jsonResponse);
        //updata response toAWS 20220225 sushanhu end
        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);
        List < GeData > itemMasterList = (List < GeData > ) JSON.deserialize(rowDataStr, List < GeData > .class);

        if (itemMasterList == null || itemMasterList.size() == 0) {
            return;
        }
        Savepoint sp = Database.setSavepoint();

        try {

            List < String > userList = new List < String > ();
            List < String > accountCodeList = new List < String > ();
            Map < String, GeData > geDataMap = new Map < String, GeData > ();
            Map<Date, Id> dateCalendarMap = new Map<Date, Id>();

            for (GeData ged: itemMasterList) {

                //验证数据完整性
                String dataComplete = verify(ged);
                if (!String.isBlank(dataComplete)) {
                    logstr += dataComplete;
                    continue;
                }
                geDataMap.put(ged.activityID, ged);
                userList.add(ged.mngCd);
                if (String.isNotBlank(ged.departmentCd)) {
                    accountCodeList.add(ged.departmentCd);
                }
                system.debug('date---'+Date.valueOf(ged.activityDailyDate));
                dateCalendarMap.put(Date.valueOf(ged.activityDailyDate), null);

            }
            GeData gd = new GeData();
            if (geDataMap.size() > 0) {


                // 获取社内用户
                // Map < String, Id > userMap = getUserMap(userList);
                // 获取客户
                Map < String, Account > accMap = getAccountMap(accountCodeList);
                // 获取ASE活动
                Map < String, ASEActivity__c > aSEActivityMap = getASEActivityMap(geDataMap);
                // 获取联系人
                Map<String,Id> contactMap = getContactMap(userList);
                List < ASEActivity__c > upsertASEList = new List < ASEActivity__c > ();
                // 获取奥林巴斯日历
                dateCalendarMap = getdateCalendarMap(dateCalendarMap);
                String activityIDStr = '活动ID [ \n';
                for (String activityID: geDataMap.keySet()) {
                    GeData ged = geDataMap.get(activityID);

                    if (!contactMap.containsKey(ged.mngCd)) {
                        logstr += 'DataError: ASE管理编码 [ ' + ged.mngCd + ' ] 对应的客户人员不存在 ，此条数据跳过，不执行!\n';
                        continue;
                    }
                    if (String.isNotBlank(ged.departmentCd) && !accMap.containsKey(ged.departmentCd)) {
                        logstr += 'DataError: 科室编码 [ ' + ged.departmentCd + ' ] 对应的客户不存在，此条数据跳过，不执行!\n';
                        continue;
                    }

                    String contactId =contactMap.get(ged.mngCd);

                    ASEActivity__c ASEAct = new ASEActivity__c();
                    if (aSEActivityMap.containsKey(ged.activityID)) {
                        ASEAct = aSEActivityMap.get(ged.activityID);
                    } 
                    
                    if (String.isNotBlank(ged.departmentCd)) {
                        ASEAct.Department__c = accMap.get(ged.departmentCd).Id;//科室
                        ASEAct.StrategicDepartment__c = accMap.get(ged.departmentCd).ParentId;//战略科室
                        ASEAct.Account__c = accMap.get(ged.departmentCd).Parent.ParentId;//医院    
                    }
                    // 所有人默认为 接口用户
                    ASEAct.OwnerId = '00510000000gmxH';//userMap.get(ged.mngCd);//所有人
                    ASEAct.ASEActivityCode__c = ged.activityID;//管理编码
                    ASEAct.activityStartTime__c = NFMUtil.parseStr2DateTime(ged.activityStartTime);//活动开始时间
                    ASEAct.activityEndTime__c = NFMUtil.parseStr2DateTime(ged.activityEndTime);//活动结束时间
                    ASEAct.WorkDesc__c = ged.workDesc;//工作描述（日报）

                    ASEAct.Activity_Purpose__c = ged.purposeOfVisit;//拜访目的
                    ASEAct.Purpose_Type__c = ged.activityDifferentiation;//活动区分
                    ASEAct.ServiceItem__c = ged.taskItem;//项目任务
                    ASEAct.VisitDistinction__c = ged.visitDistinction;//拜访区分

                    ASEAct.ASEActivityDate__c = Date.valueOf(ged.activityDailyDate);//活动日报日期
                    ASEAct.OlympusCalendar__c = dateCalendarMap.get(Date.valueOf(ged.activityDailyDate));
                    ASEAct.VisitStaff__c = ged.customerNm;
                    ASEAct.ReporterASE__c = contactId;//报告者
                    ASEAct.DurationInMinutes__c =  getDurationInMinutes(ged);//持续时间分钟
                    activityIDStr += ged.activityID +'\n';
                    //add             wangweipeng         2022/02/14      start
                    ASEAct.CustomerTel__c = ged.customerTel;//客户手机号码
                    ASEAct.WorkPlace__c = ged.workPlace;//工作场所
                    //add             wangweipeng         2022/02/14      end
                    ASEAct.AWS_Data_Id__c =ged.DataId;//加密索引 20220207
                    ASEAct.VisitStaffEncrypt__c=ged.customerNmEncrypted;//密文 20220207
                   //add sushanhu 2022/02/16 sart
                   ASEAct.CustomerTel_Encrypted__c=ged.customerTelEncrypted;
                   ASEAct.WorkPlace_Encrypted__c =ged.workPlaceEncrypted;
                    //add sushanhu 2022/02/16 end
                    upsertASEList.add(ASEAct);
                }

                if (upsertASEList.size() > 0) {
                    activityIDStr += ' ]\n';
                    upsert upsertASEList;
                    logstr += activityIDStr + 'ASE日报 保存成功 ';
                }

            }

            logstr += 'End\n';
            rowData.retry_cnt__c = 0; //必加
        } catch (Exception ex) {
            Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
            // エラーが発生した場合
            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 rowData;
        iflog.Log__c = logstr;
        if (iflog.Log__c.length() > 131072) {
            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
        }
        if (iflog.ErrorLog__c.length() > 32768) {
            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
        }
        upsert iflog;

    }

    // 计算持续时间分钟
    public static Integer getDurationInMinutes(GeData ged){
        
        String startTime = ged.activityStartTime.substring(0, 12)+'00';
        String endTime = ged.activityEndTime.substring(0, 12)+'00';
        Datetime startDateTime= NFMUtil.parseStr2DateTime(startTime);
        Datetime endDateTime= NFMUtil.parseStr2DateTime(endTime);

        return Integer.valueOf((endDateTime.getTime() - startDateTime.getTime()) / 1000 / 60);
    }
    // 获取奥林巴斯日历
    private static Map<Date, Id> getdateCalendarMap(Map<Date, Id> dateCalendarMap){
        if (dateCalendarMap.size() > 0) {
            for (OlympusCalendar__c cal : [
                        Select Id, Date__c
                        from OlympusCalendar__c
                        Where Date__c in :dateCalendarMap.keySet()
                    ]
                ) {
                dateCalendarMap.put(cal.Date__c, cal.Id);
            }
        }
        return dateCalendarMap;
    }


    // 获取联系人
    private static Map<String,Id> getContactMap(List < String > userList){
        Map<String,Id> result = new Map<String,Id>();
        List < Contact > contactList = [
            SELECT Id,CManageCode__c 
            FROM Contact 
            WHERE CManageCode__c IN: userList OR Employee_No_manual__c IN:userList];
        for (Contact con: contactList) {
            result.put(con.CManageCode__c, con.Id);
        }
        return result;
    }
    // 获取用户
    // private static Map < String, Id > getUserMap(List < String > userList) {

    //     Map < String, Id > result = new Map < String, Id > ();
    //     List < User > uList = [SELECT Id, Employee_No__c,Contact.CManageCode__c
    //         FROM User
    //         WHERE  IsActive = true AND (Employee_No__c IN: userList OR Contact.CManageCode__c IN:userList)
    //     ];
    //     for (User u: uList) {

    //         if (String.isNotBlank(u.Contact.CManageCode__c)) {
    //             result.put(u.Contact.CManageCode__c, u.Id);
    //         }
    //         result.put(u.Employee_No__c, u.Id); //员工编码
    //     }

    //     return result;

    // }
    // 获取科室
    private static Map < String, Account > getAccountMap(List < String > accountCodeList) {

        Map < String, Account > result = new Map < String, Account > ();
        if (accountCodeList.size() > 0) {
            List < Account > aList = [SELECT Id, ParentId,Parent.ParentId,Management_Code__c, Management_Code_Auto__c
                FROM Account
                WHERE Management_Code__c IN: accountCodeList
            ];

            for (Account acc: aList) {
                result.put(acc.Management_Code__c, acc); //科室编码
            }    
        }
        
        return result;
    }
    // 获取ASE日报
    private static Map < String, ASEActivity__c > getASEActivityMap(Map < String, GeData > geDataMap) {
        Map < String, ASEActivity__c > result = new Map < String, ASEActivity__c > ();
        List < ASEActivity__c > ASEList = [SELECT Id,ASEActivityCode__c  
            FROM ASEActivity__c
            WHERE ASEActivityCode__c IN: geDataMap.keySet()
        ];

        for (ASEActivity__c ASEAct: ASEList) {
            result.put(ASEAct.ASEActivityCode__c, ASEAct);

        }
        return result;
    }
    // 必填字段验证
    private static String verify(GeData ged) {
        String result = '';

        String activityID = '';
        if (ged.mngCd == null) {
            result += 'DataError: ASE管理编码 [ mngCd ] is null!\n';
        }
        if (ged.activityDailyDate == null) {
            result += 'DataError: 活动日报日期 [ activityDailyDate ] is null!\n';
        }
        
        if (ged.activityID == null) {
            result += 'DataError: 活动ID [ activityID ] is null!\n';
        } else {
            activityID = '活动ID [ ' + ged.activityID + ' ]\n';
        }
        if (ged.purposeOfVisit == null) {
            result += 'DataError: 拜访目的 [ purposeOfVisit ] is null!\n';
        }
        if (ged.activityDifferentiation == null) {
            result += 'DataError: 活动区分 [ activityDifferentiation ] is null!\n';
        }
        if (ged.activityStartTime == null) {
            result += 'DataError: 活动开始时间 [ activityStartTime ] is null!\n';
        }
        if (ged.activityEndTime == null) {
            result += 'DataError:  活动结束时间 [ activityEndTime ] is null!\n';
        }
        if (String.isBlank(ged.taskItem) ) {
            result += 'DataError:  任务类型 [ taskItem ] is null!\n';
        }
        if (String.isBlank(ged.visitDistinction) ) {
            result += 'DataError:  拜访区分 [ visitDistinction ] is null!\n';
        }
        // if (String.isBlank(ged.DataId) ) {
        //     result += 'DataError:  加密索引 [ DataId ] is null!\n';
        // }
        // if (String.isBlank(ged.customerNmEncrypted)) {
        //     result += 'DataError:  客户姓名密文 [ customerNmEncrypted ] is null!\n';
        // }
        
        if (String.isNotBlank(activityID) && String.isNotBlank(result)) {
            result = activityID + result;
        }
        
        return result;
    }

}