/** 备品智能化
 * 2023-10-30 Add by dzk 
 * 日历新建事件按钮,VF页面转换为LWC页面
 * 与原新建事件功能一致
 */
public without sharing class lexCreateEventButton {
    // 获取开始日期时间
    @AuraEnabled
    public static Datetime  getNowDateTime(){
        try{
            Datetime nowDate = Datetime.Now().addDays(1);
            return nowDate;
        }
        catch(Exception e){
            System.debug(LoggingLevel.INFO, '*** e: ' + e);
            return null;
        }
    }

    // 获取结束日期时间
    @AuraEnabled
    public static Datetime  getEndDateTime(){
        try{
            Datetime nowDate = Datetime.Now().addDays(1);
            Datetime endDate = nowDate.addMinutes(30);
            return endDate;
        }
        catch(Exception e){
            System.debug(LoggingLevel.INFO, '*** e: ' + e);
            return null;
        }
    }

    @AuraEnabled
    public static String  getUserJobCategory(){
        try{
            User LoginUser = [SELECT Id, Name, Job_Category__c  FROM User WHERE Id = :UserInfo.getUserId()];
            return LoginUser.Job_Category__c;
        }
        catch(Exception e){
            System.debug(LoggingLevel.INFO, '*** e: ' + e);
            return null;
        }
    }

    // 询价填值时,获取询价下的报价行项目信息
    @AuraEnabled
    public static List<ProLine>  getOppQuoteItems(String records,String recordId){
        try{
            List<ProLine> ProLineList = new List<ProLine>();
            List<ProLine> ProLineOldList = 
            (List<ProLine>)System.JSON.deserialize(records, List<ProLine>.class);
            List<ProLine> ProLineNewList = new List<ProLine>();
            Map<String,ProLine> ProLineNewMap = new Map<String,ProLine>();
            for(ProLine pro : ProLineOldList){
                if(pro.QuoteId == null){
                    ProLineNewList.add(pro);
                    ProLineNewMap.put(pro.ProductModel, pro);
                }
            }

            if(String.isNotBlank(recordId)){
                ProLineNewList = null;
                List<Opportunity> opp = [SELECT Id, Estimation_Id__c FROM Opportunity WHERE Id =: recordId];
                List<QuoteLineItem> quoteItemList = [SELECT Id, Quantity, Product2.Name, QuoteId,
                                                            Product2.Key_product_147P__c,Quote.Quote_No__c,
                                                            Product2.ProductCode, Product2.Fixture_Model_No_T__c,
                                                            OppIsLendMark__c, Product2.RentalSubject__c
                                                            FROM QuoteLineItem
                                                            WHERE Product2.RentalSubject__c = true 
                                                            AND QuoteId =: opp[0].Estimation_Id__c
                                                            AND Product2.Fixture_Model_No_F__c != null
                                                            AND Product2.Category5__c != '虚拟'
                                                            AND ((Product2.SFDA_Status__c = '停止' 
                                                                AND Product2.Manual_Entry__c = false 
                                                                AND Product2.Loaner_categoryII__c IN ('台车','监视器','录像设备'))
                                                            OR (Product2.SFDA_Status__c != '停止'  
                                                                OR Product2.Manual_Entry__c = true)) ];
                for(QuoteLineItem quoLine : quoteItemList){
                    if(ProLineNewMap.get(quoLine.Product2.Fixture_Model_No_T__c) != null){
                       ProLineNewMap.get(quoLine.Product2.Fixture_Model_No_T__c).QuoteId = quoLine.QuoteId;
                       ProLineNewMap.get(quoLine.Product2.Fixture_Model_No_T__c).QuoteNo = quoLine.Quote.Quote_No__c;
                    }else{
                        ProLine proNew = new ProLine();
                        proNew.Id = quoLine.Id;
                        proNew.Name = quoLine.Product2.Name;
                        proNew.Quantity = 1;
                        proNew.ProductCode = quoLine.Product2.ProductCode;
                        proNew.ProductModel = quoLine.Product2.Fixture_Model_No_T__c;
                        if(String.isNotBlank(quoLine.Product2.Key_product_147P__c)){
                            proNew.FixtureModel = quoLine.Product2.Key_product_147P__c.substring(3);
                        }
                        proNew.QuoteId = quoLine.QuoteId;
                        proNew.QuoteNo = quoLine.Quote.Quote_No__c;
                        ProLineNewMap.put(proNew.ProductModel, proNew);
                    }
                }
                for (ProLine mapValue : ProLineNewMap.values()) {
                    ProLineList.add(mapValue);
                }
                return ProLineList;
            }else{
                return ProLineNewList;
            }    
        }
        catch(Exception e){
            System.debug(LoggingLevel.INFO, '*** e: ' + e + e.getLineNumber() + '行');
            return null;
        }
    }

    // 事件保存
    @AuraEnabled
    public static String  saveEvent(String records,String products){
        Event targetEvent = new Event();
        task__c taskActive = new task__c();
        List<Account> accList = new List<Account>();
        Set<String> departIdSet = new Set<String>();
        Maintenance_Contract__c mc = new Maintenance_Contract__c();
        Map<String, String> accToDepMap = new Map<String, String>();
        Map<String, Account_Number_of_target__c> accToNumTarget = new Map<String, Account_Number_of_target__c>();

        try{
            String taskAccName = '';
            String taskAccType = '';
            String taskType = '';
            User LoginUser = [SELECT Id, Name, Job_Category__c  FROM User WHERE Id = :UserInfo.getUserId()];
            Map<String, Object> eventLineMap = (Map<String, Object>) JSON.deserializeUntyped(records);
            
            targetEvent.StartDateTime = (Datetime)JSON.deserialize('"' + String.valueOf(eventLineMap.get('StartTime')) + '"', Datetime.class);
            targetEvent.EndDateTime = (Datetime)JSON.deserialize('"' + String.valueOf(eventLineMap.get('EndTime')) + '"', Datetime.class);
            Long startTime = targetEvent.StartDateTime.getTime();
            Long endTime = targetEvent.EndDateTime.getTime();
            targetEvent.DurationInMinutes = Integer.valueOf((endTime - startTime) / 1000 / 60);

            String whatId = String.valueOf(eventLineMap.get('AccountId'));
            String conId = String.valueOf(eventLineMap.get('ContactId'));
            String oppId = String.valueOf(eventLineMap.get('OpportunityId'));
            String mainConId = String.valueOf(eventLineMap.get('ServiceId'));
            String ActivityType2 = String.valueOf(eventLineMap.get('ActivityType2'));
            String ActivityPurposeFSE = String.valueOf(eventLineMap.get('ActivityPurposeFSE'));//拜访目的
            String PurposeTypeFSE = String.valueOf(eventLineMap.get('PurposeTypeFSE'));//活动区分
            String subject = eventLineMap.get('Subject') != null ? String.valueOf(eventLineMap.get('Subject')) : null;
            targetEvent.OwnerId = Userinfo.getUserId();
            targetEvent.EventStatus__c = '02 接受';
            targetEvent.Subject = String.isNotBlank(subject) ? subject + '-' + ActivityPurposeFSE : ActivityPurposeFSE;
            targetEvent.Activity_Type2__c = ActivityType2;
            targetEvent.Visitor1_ID__c = conId;
            taskActive.taskStatus__c = '02 接受'; 
            taskActive.assignee__c = UserInfo.getUserId(); 
            taskActive.taskDifferent__c = '主动任务';
            taskActive.ConfirmDate__c = Date.today(); 
            taskActive.GeneratePlan__c = true; 
            taskActive.Activity_Date__c = targetEvent.StartDateTime.date();

            if (LoginUser.Job_Category__c == '销售服务') {
                targetEvent.Activity_PurposeFSE__c = ActivityPurposeFSE;
                targetEvent.Purpose_TypeFSE__c = PurposeTypeFSE;
            } else {
                targetEvent.Activity_PurposeEscFSE__c = ActivityPurposeFSE;
                targetEvent.Purpose_TypeEscFSE__c = PurposeTypeFSE;
            } 
            targetEvent.Activity_Purpose__c = ActivityPurposeFSE;
            targetEvent.Purpose_Type__c = PurposeTypeFSE;

            if(!String.isBlank(whatId)){
                if(whatId.startsWith('001')){
                    Account acc = [SELECT Id, Name,RecordType.Name,Parent_RecordType__c FROM Account WHERE Id = :whatId];
                    targetEvent.Location = acc.Name;
                    taskAccName = acc.Name;
                    targetEvent.Subject += '(' + targetEvent.Location + ')';
                    taskActive.account__c = whatId;
                    targetEvent.whatid__c = whatId;
                    
                    accList = 
                        [select id, name, Department_Class__c 
                         from Account 
                         where id = :whatId];
                    for (Account acc1 : accList) {
                        departIdSet.add(acc1.Department_Class__c);
                        accToDepMap.put(acc1.Id, acc1.Department_Class__c);
                    }
                    List<Account> accDepList = 
                        [select id, name, 
                         (select id, OCM_Period__c, 
                          Is_Target_Account_Energy__c, 
                          Is_Target_Account__c, OCM_Category__c 
                          from Account_target_acc__r 
                          order by OCM_Period__c desc limit 1) 
                         from Account where id = :departIdSet];
                    for (Account accdep : accDepList) {
                        for (Account_Number_of_target__c accnum : accdep.Account_target_acc__r) {
                            accToNumTarget.put(accdep.Id, accnum);
                            break;
                        }
                    }
                    if(!String.isBlank(oppId)){
                        taskActive.OpportunityId__c = oppId;
                        targetEvent.Related_Opportunity1_ID__c = oppId;
                        List<Opportunity> opp = [SELECT Id,Name,Competitor__c,
                                                  Close_Forecasted_Date__c,
                                                  Created_Day__c,StageName__c,
                                                  Bid_Date__c,Closing_Bid_Date__c 
                                            FROM Opportunity 
                                            WHERE Id = :oppId 
                                            // AND AccountId = :whatId 
                                            AND StageName = '引合'
                                        ];
                        if(opp.size() > 0){
                            targetEvent.Related_Opportunity1__c = opp[0].Name;
                            taskActive.OppCompetitorDbt__c = opp[0].Competitor__c;
                            taskActive.CloseForecastedDateDbt__c = opp[0].Close_Forecasted_Date__c;
                            taskActive.OpportunityStatusDbt__c = opp[0].StageName__c;
                            taskActive.OppCreateDateDbt__c = opp[0].Created_Day__c;
                            taskActive.Bid_DateDbt__c = opp[0].Bid_Date__c;
                            taskActive.Closing_Bid_DateDbt__c = opp[0].Closing_Bid_Date__c;
                        }
                    }
                    if(!String.isBlank(mainConId)){
                        mc = [SELECT Id,Name,Management_Code__c,
                                     RecordType_DeveloperName__c 
                                FROM Maintenance_Contract__c 
                                WHERE Id = :mainConId AND Department__c = :whatId];
                            targetEvent.Related_Service1__c = mc.Name +' '+mc.Management_Code__c;
                            targetEvent.Related_Service1_ID__c = mainConId;
                            targetEvent.Related_Service1_Code__c = mc.Management_Code__c;
                    }
                }
                if (whatId.startsWith('701')) {
                    Campaign camlist = [SELECT Id, Name FROM Campaign WHERE Id = :whatId];
                    taskAccName = camlist.name;
                    targetEvent.Location = camlist.Name;
                    targetEvent.Subject += '(' + targetEvent.Location + ')';
                    targetEvent.whatid__c = camlist.Id;
                }
                if (ActivityType2 == '病院') {
                    taskAccType = '用户拜访';
                }
                if (ActivityType2 == '販売店') {
                    taskAccType = '经销商支持';
                }
                if (ActivityType2 == '社外イベント') {
                    taskAccType = '学术会议';
                }
                if (LoginUser.Job_Category__c.equals('销售推广')) {
                    if (ActivityType2 == '病院') {
                        if (!String.isBlank(oppId)) { 
                            taskType = System.Label.OpportunityFollow; // 询价跟进任务
                        } else if (Boolean.valueOf(eventLineMap.get('IsOPDPlan')) == true) {
                            taskType = System.Label.OPD; // OPD任务
                            
                        } else if (!accToNumTarget.isEmpty() && !accToDepMap.isEmpty() && (accToNumTarget.get(accList[0].Department_Class__c).Is_Target_Account_Energy__c == 1 )) {
                             taskType = System.Label.TargetAccountVisit; // 目标客户拜访任务
                        }  else if (!accToNumTarget.isEmpty() && !accToDepMap.isEmpty() && (accToNumTarget.get(accList[0].Department_Class__c).OCM_Category__c == 'H1' || accToNumTarget.get(accList[0].Department_Class__c).OCM_Category__c == 'H0')) {
                             taskType = System.Label.visitHLevel; // H层拜访任务
                        } else {
                            taskType = System.Label.DailyVisit;// 日程拜访任务
                        }
                    }
                    if (ActivityType2 == '販売店') {
                        taskType = System.Label.AgencyVisit; // 经销商支持任务
                    }
                    if (ActivityType2 == '社外イベント') {
                        taskType = System.Label.campaignFollow; // 学术会议跟进任务
                    }
                } else {
                    taskType = System.Label.DailyVisit; //日常拜访
                    //20201123 zh 创建主动任务与维修合同关联 start
                    if (String.isNotBlank(mainConId) &&
                        mc.RecordType_DeveloperName__c == 'VM_Contract') {
                        taskType = System.Label.VMContract; //多年保修任务
                    }
                    if (String.isNotBlank(mainConId) && 
                        mc.RecordType_DeveloperName__c == 'NewMaintenance_Contract'
                            || mc.RecordType_DeveloperName__c == 'Maintenance_Contract') {
                        taskType = System.Label.MaintenanceTask; //维修合同任务(消费率预警)
                    }
                }
                NewMaintenanceReport_Task__c tempNMCT ;
                if ('合同季报'.equals(String.valueOf(PurposeTypeFSE))){
                    taskType = System.Label.SLA; //SLA任务

                    // 关联服务合同报告书任务
                    if(String.isNotBlank(mainConId) &&
                        mc.RecordType_DeveloperName__c == 'NewMaintenance_Contract'){
                        List<NewMaintenanceReport_Task__c> tempNMCTList = [SELECT Id FROM 
                                                                            NewMaintenanceReport_Task__c 
                                                                            WHERE NewMaintenance_Contract__c =:mainConId
                                                                            AND Distribution_Start_Date__c <= :Date.today() 
                                                                            AND Distribution_End_Date__c >= :Date.today()];
                        if(tempNMCTList.size()>0){
                            tempNMCT = tempNMCTList.get(0);
                        }
                    }
                }
    
                if('合同点检'.equals(String.valueOf(PurposeTypeFSE))){
                    taskType = System.Label.InspectupTask; //点检任务
                }
                taskActive.RecordTypeId = taskType;
                taskActive.Name = taskAccType + ':' + taskAccName;
                taskActive.RecordTypeId = taskType;
                if(String.isNotBlank(mainConId)){
                    taskActive.Maintenance_Contract__c = mainConId;
                }

                if(tempNMCT !=null){
                   taskActive.NewMaintenanceReport_Task__c =  tempNMCT.Id;
                }
            }

            insert targetEvent;
            insert taskActive;
            targetEvent.Task_ID__c = taskActive.Id;
            update targetEvent;
            if (Boolean.valueOf(eventLineMap.get('IsOPDPlan'))) {
                System.debug('是否选中OPD计划');
                targetEvent.noOpp_Reason__c = String.valueOf(eventLineMap.get('NoOppReason'));
                saveOPDPlan(targetEvent,products);
            }
            return targetEvent.Id;
        }
        catch(Exception e){
            String originalString = e.getMessage();
            String extractedContent = originalString.substringBetween('EXCEPTION,', ': [');
            System.debug(LoggingLevel.INFO, '*** e: ' + e  + e.getLineNumber() + '行');
            return extractedContent;
        }
    }

    @AuraEnabled
    public static String  saveLogic(String records,String products){
        try{
            String ErrorMessage = '';
            Map<String, Object> eventLineMap = (Map<String, Object>) JSON.deserializeUntyped(records);
            
            List<ProLine> ProLineList = 
            (List<ProLine>)System.JSON.deserialize(products, List<ProLine>.class);
            Date today = Date.today();
            DateTime startDateTime;
            DateTime endDateTime;
            Date startDate;
            Date endDate;
           
            if(String.isBlank(String.valueOf(eventLineMap.get('StartTime')))){
                ErrorMessage = '请输入开始时间';
            }else{
                startDateTime = (Datetime)JSON.deserialize('"' + String.valueOf(eventLineMap.get('StartTime')) + '"', Datetime.class);
                startDate = startDateTime.Date();
            }
            if(String.isBlank(String.valueOf(eventLineMap.get('EndTime'))) && ErrorMessage == ''){
                ErrorMessage = '请输入结束时间' ;
            }else{
                endDateTime = (Datetime)JSON.deserialize('"' + String.valueOf(eventLineMap.get('EndTime')) + '"', Datetime.class);
                endDate = endDateTime.Date();
            }
            String oppId = String.valueOf(eventLineMap.get('OpportunityId'));
            String ActivityType2 = String.valueOf(eventLineMap.get('ActivityType2'));
            String ActivityPurposeFSE = String.valueOf(eventLineMap.get('ActivityPurposeFSE'));//拜访目的
            if (startDate <= today && ErrorMessage == '') {
               ErrorMessage = '请输入今天以后的日期';
            }
            if (startDate > today.addDays(60) && ErrorMessage == '') {
                ErrorMessage = '请输入60天以内的日期';
            }
            if(startDateTime > endDateTime && ErrorMessage == ''){
                ErrorMessage = '结束日期必须大于开始日期';
            }
            if(startDate != endDate && ErrorMessage == ''){
                ErrorMessage = '开始时间 和 结束时间 必须在同一天';
            }
            if((ActivityType2 == ''
                || ActivityPurposeFSE == '') && ErrorMessage == ''){
                ErrorMessage = '请输入必填值';
            }
            if(ActivityType2 == '病院' && ErrorMessage == '' && String.isBlank(String.valueOf(eventLineMap.get('AccountId')))){
                ErrorMessage = '科室不能为空';
            }
            if (Boolean.valueOf(eventLineMap.get('IsOPDPlan'))){
                 if (ProLineList.size() == 0 && ErrorMessage == '') {
                    ErrorMessage = '【opd计划】勾选时且关联询价时，计划出借的备品必须填写';
                    // isError = true;
                }
                if(String.isBlank(oppId) && String.isBlank(String.valueOf(eventLineMap.get('NoOppReason'))) && ErrorMessage == '') {
                    ErrorMessage = '【opd计划】勾选时，涉及的询价为空，必须填写无询价申请理由';
                }
                if(String.isNotBlank(oppId)){
                    Opportunity opp = [SELECT Id,Name,StageName FROM Opportunity WHERE Id = :oppId];
                    if(opp.StageName=='敗戦' || opp.StageName=='削除' || opp.StageName=='注残' || opp.StageName=='出荷' || opp.StageName=='完了'){
                        ErrorMessage = '涉及的询价状态为：失单、取消、注残、发货、完毕，不允许创建OPD计划';                
                    }
                } 
            }
            if(ErrorMessage == ''){
                ErrorMessage = 'Success';
            }
            return ErrorMessage;
        }
        catch(Exception e){            
            String originalString = e.getMessage();
            String extractedContent = originalString.substringBetween('EXCEPTION,', ': [');
            System.debug(LoggingLevel.INFO, '*** e: ' + e  + e.getLineNumber() + '行');
            return extractedContent;
        }
    }
    

    public static void saveOPDPlan(Event event,String products) {
        OPDPlan__c opdPlan = new OPDPlan__c();
        opdPlan.OwnerId =  event.OwnerId;
        opdPlan.Activity_Type2__c = event.Activity_Type2__c;
        opdPlan.StartDateTime__c = event.StartDateTime;
        opdPlan.EndDateTime__c = event.StartDateTime.addMinutes(event.DurationInMinutes);
        if(event.OPD_Plan__c == null){
            opdPlan.OPDPlan_ImplementDate__c = event.StartDateTime.date();
        }
        if (event.Activity_Type2__c == '病院' && String.isNotBlank(event.whatid__c)) {
            opdPlan.Account_Laboratory__c = event.whatid__c;
        } else if (event.Activity_Type2__c == '販売店' && String.isNotBlank(event.whatid__c)) {
            opdPlan.Account_Dealer__c = event.whatid__c;
        } else if (event.Activity_Type2__c == '社内活動' && String.isNotBlank(event.whatid__c)) {
            opdPlan.Account_Laboratory__c = event.whatid__c;
        } else if (event.Activity_Type2__c == '社外イベント' && String.isNotBlank(event.whatid__c)) {
            opdPlan.Campaign__c = event.whatid__c;
        }
        if (String.isNotBlank(event.Visitor1_ID__c)) {
            opdPlan.Visitor1_ID__c = event.Visitor1_ID__c;
        }
        if(String.isNotBlank(event.Related_Opportunity1__c)){
            opdPlan.Related_Opportunity1__c = event.Related_Opportunity1__c;
        }
        if (String.isNotBlank(event.Related_Opportunity1_ID__c)) {
            opdPlan.Related_Opportunity1_ID__c = event.Related_Opportunity1_ID__c;
            opdPlan.NoOpp_Reason__c = null;  
        }else{
            opdPlan.NoOpp_Reason__c = event.noOpp_Reason__c;  
        }
        opdPlan.Related_Service1__c = event.Related_Service1__c;
        if (String.isNotBlank(event.Related_Service1_ID__c)) {
            opdPlan.Related_Service1_ID__c = event.Related_Service1_ID__c;
        }
        opdPlan.Activity_PurposeFSE__c = event.Activity_PurposeFSE__c;
        opdPlan.Purpose__c = event.Subject;
        opdPlan.Purpose_TypeFSE__c = event.Purpose_TypeFSE__c;
        opdPlan.Purpose_Type__c = event.Purpose_Type__c;
        opdPlan.Activity_Purpose__c = event.Activity_Purpose__c;
        
        opdPlan.OPDType__c = '事件';
        opdPlan.RentalReson__c = 'OPD'; 
        opdPlan.Task_ID__c = event.Task_ID__c;

        insert opdPlan;
        event.Opd_Plan__c = opdPlan.Id;
        update event;

        String quantity = '';
        String quantityNo = '';
        String quantitySys = '';
        RecordType recordType = [SELECT Id,Name FROM RecordType WHERE SobjectType = 'Plan_Rental_Equipment__c' AND Name = '事件'];
        List<ProLine> ProLineList = 
            (List<ProLine>)System.JSON.deserialize(products, List<ProLine>.class);
        List<Plan_Rental_Equipment__c> ineuqipments = new List<Plan_Rental_Equipment__c>();
        for(ProLine pro : ProLineList){
            Plan_Rental_Equipment__c planRE = new Plan_Rental_Equipment__c();
            planRE.Event_ID__c = event.Id;
            planRE.Quote__c = pro.QuoteId;
            planRE.RecordTypeId = recordType.Id;
            planRE.Name = pro.Name;
            planRE.Rental_Equipment__c = pro.Name;
            planRE.Rental_Quantity__c = String.valueOf(pro.Quantity);
            planRE.OPD_Plan__c = opdPlan.Id;
            planRE.ProductCode__c = pro.ProductCode;
            planRE.MDM_Model_No__c = pro.ProductModel;
            planRE.FixtureModel__c = pro.FixtureModel;
            planRE.Opportunity__c = event.Related_Opportunity1_ID__c;
            ineuqipments.add(planRE);
            if(String.isNotBlank(pro.FixtureModel)){
                quantitySys += pro.FixtureModel + '*' + pro.Quantity + '; ';
            }
            if(pro.QuoteId == null){
                quantity += pro.ProductModel + '*' + pro.Quantity + '; ';
            }else{
                quantityNo += pro.ProductModel + '*' + pro.Quantity + '; ';
            }
        }
        insert ineuqipments;
        opdPlan.PlanProdDetail__c = quantityNo + quantity;
        opdPlan.EquipmentNotFromOpp__c = quantity;
        opdPlan.EquipmentFromOpp__c = quantityNo;
        opdPlan.PlanProdDetailSys__c = quantitySys;
        opdPlan.Status__c = '提交';

        update opdPlan;
        LexOPDSupplementaryController.newRentalApply(opdPlan.Id);

    }
    public class ProLine {
        @AuraEnabled
        public String Id { get; set; } 
        @AuraEnabled
        public Integer Quantity { get; set; } 
        @AuraEnabled
        public String Name { get; set; } 
        @AuraEnabled
        public String QuoteNo { get; set; } 
        @AuraEnabled
        public String QuoteId { get; set; } 
        @AuraEnabled
        public String ProductCode { get; set; }  
        @AuraEnabled
        public String ProductModel { get; set; } 
        @AuraEnabled
        public String FixtureModel { get; set; } 
    } 
}