/**
 * 2022-06-15 sx 询价跟进任务
 */

global class TenderResultConfirmTaskBatch implements Database.Batchable<sObject> {
    
    Integer opporTotal = 0;
    Integer taskTotal = 0;
    
    BatchIF_Log__c log = new BatchIF_Log__c();
    
    public TenderResultConfirmTaskBatch() {
    }
    //20220715 you 招标任务 start
    List<String> TenderIds = new List<String>();
    global TenderResultConfirmTaskBatch(List<String> tenIds){
        this.TenderIds = tenIds;
    }
    //20220715 you 招标任务 end
    global Database.QueryLocator start(Database.BatchableContext bc){
        String query = 'Select Id, Opportunity__c, Tender_information__c, '
                     + 'Tender_information__r.status__c, Tender_information__r.TenderManageCode__c,Tender_information__r.RecordTypeId, Tender_information__r.CreatedDate,'
                     + 'Opportunity__r.OwnerId, Opportunity__r.AccountId, Opportunity__r.StageName__c, '
                     + 'Opportunity__r.Assistant_Applied_Date__c, Opportunity__r.Cnt_Lost_cancel_Draft__c, Opportunity__r.ConfirmationofAward__c, '
                     + 'Opportunity__r.Contract_DB_complite_day__c, Opportunity__r.Contract_Authorize_Lock__c, '
                     + 'Opportunity__r.ConfirmationofAward_createTime__c ' 
                     + 'FROM Tender_Opportunity_Link__c '
                     + 'WHERE Tender_information__r.InfoType__c = \'3：结果\' ' 
                     + 'AND (Tender_information__r.subInfoType__c = \'3-5：中标通知\' OR Tender_information__r.subInfoType__c = \'3-6：合同公告\') '
                     + 'AND Tender_information__r.RecordTypeId = \'01210000000VLUI\' ';
                    
        //20220715 you 招标任务 start
        if(TenderIds !=null && TenderIds.size() > 0){
              query += 'AND Opportunity__c in :TenderIds';
            //query += 'AND Tender_information__c in :TenderIds ';
        }else{
             query += 'AND Tender_information__r.LastModifiedDate = LAST_N_DAYS:2';
        }
        query += ' ORDER BY Opportunity__c, Tender_information__r.CreatedDate';
        //20220715 you 招标任务 end
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Tender_Opportunity_Link__c> toppLinkList){
        log.Type__c='TenderResultConfirm_Task';
        String logstr = 'Batch execute start' + '\r\n 查询结果 :' + toppLinkList;

        Set<Id> oppIds = new Set<Id>();
        for (Tender_Opportunity_Link__c tol : toppLinkList) {
            oppIds.add(tol.Opportunity__c);
        }
        
        //20220718  筛选一下有无任务的询价，取消也需要新建
        List<Task__c> taskList = [
                SELECT Id,OpportunityId__c,taskStatus__c 
                FROM task__c 
                WHERE OpportunityId__c in :oppIds 
                AND (RecordType.Name = '中标结果确认' OR RecordType.Name = '失单报告任务')
                AND (taskStatus__c = '02 接受' OR taskStatus__c = '03 完成')];
        system.debug('test1-----'+taskList);
        Map<String,Task__c> mapTask = new Map<String,Task__c>();
        for(Task__c t: taskList){
            mapTask.put(t.OpportunityId__c, t);
        }

        // 记录类型：中标结果确认
        Id winBiddingTask_TaskId = Schema.SObjectType.task__c.getRecordTypeInfosByDeveloperName().get('winBiddingTask').getRecordTypeId();
        
        Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>();
        Map<Id, Task__c> taskMap = new Map<Id, Task__c>();

        for(Tender_Opportunity_Link__c topp : toppLinkList){
            system.debug('test3'+topp.Opportunity__c);
            logstr += 'Batch execute ' + '\r\n 询价进入for----- :'+ topp;
            // 已存在有效状态任务的询价，不用再次产生任务
            if (mapTask.isEmpty() 
                || (!mapTask.isEmpty() && !mapTask.containsKey(topp.Opportunity__c))){

                //1.内部确认状态为05.询价中且关联询价的状态1为询价 且 价格申请 不等于 真 -- > 创建并派发任务
                if (topp.Tender_information__r.status__c == '05.询价中' && topp.Opportunity__r.StageName__c == '询价' && topp.Opportunity__r.Assistant_Applied_Date__c == null){
                    logstr += 'Batch execute ' + '\r\n 询价进入第一个判断条件----- :'+ topp.Opportunity__c ;
                    Task__c tempTask = new Task__c();
                    tempTask.RecordTypeId = winBiddingTask_TaskId;
                    tempTask.taskDifferent__c = '被动任务';
                    tempTask.taskStatus__c = '02 接受';       //任务状态2
                    tempTask.assignee__c = topp.Opportunity__r.OwnerId;    //被分配者
                    tempTask.account__c = topp.Opportunity__r.AccountId;
                    tempTask.Name = '中标结果确认：' + topp.Tender_information__r.TenderManageCode__c;  //招标项目.SFDC编码
                    tempTask.OwnerId = topp.Opportunity__r.OwnerId;   //所有人
                    tempTask.OpportunityId__c = topp.Opportunity__c;
                    tempTask.Tender_information_Task__c = topp.Tender_information__c;       //招标项目
                    tempTask.ConfirmDate__c = Date.today();
                    
                    if (taskMap.isEmpty() || !taskMap.containsKey(topp.Opportunity__c)) {
                       taskMap.put(topp.Opportunity__c, tempTask);                 
                    }
                    
                    //更新询价  Task_createTime__c  
                    if(oppMap.isEmpty() || !oppMap.containsKey(topp.Opportunity__c)){
                        Opportunity tempOpp  = new Opportunity();
                        tempOpp.Id = topp.Opportunity__c;
                        tempOpp.Task_createTime__c = Date.today();
                        oppMap.put(topp.Opportunity__c, tempOpp);
                    }
                }
            }

            //2. 存在已提交的失单报告或者询价状态1=失单 -- >中标确认：竞争对手中标
            // 招标项目中的中标确认更改在Batch中更新
            if (topp.Opportunity__r.Cnt_Lost_cancel_Draft__c > 0 || topp.Opportunity__r.StageName__c == '失单'){
                logstr += 'Batch execute ' + '\r\n 询价进入第二个判断条件----- :'+ topp.Opportunity__c ;
                //中标确认字段赋值竞争对手中标
                if(oppMap.isEmpty() || !oppMap.containsKey(topp.Opportunity__c)){
                    Opportunity tempOpp  = new Opportunity();
                    tempOpp.Id = topp.Opportunity__c;
                    tempOpp.ConfirmationofAward__c = '竞争对手中标';
                    oppMap.put(topp.Opportunity__c, tempOpp);
                }
            }

            //3.已完成合同申请 --> 中标确认：OLY中标
            // 招标项目中的中标确认更改在Batch中更新
            if (topp.Opportunity__r.Contract_DB_complite_day__c != null && topp.Opportunity__r.Contract_Authorize_Lock__c){
                logstr += 'Batch execute ' + '\r\n 询价进入第三个判断条件----- :'+ topp.Opportunity__c ;
                //中标确认字段赋值竞争对手中标
                if(oppMap.isEmpty() || !oppMap.containsKey(topp.Opportunity__c)){
                    Opportunity tempOpp  = new Opportunity();
                    tempOpp.Id = topp.Opportunity__c;
                    tempOpp.ConfirmationofAward__c = 'OLY中标';
                    oppMap.put(topp.Opportunity__c, tempOpp);
                }
            }
        }

        try {
            if (!taskMap.isEmpty()) {
                insert taskMap.values();
                logstr += 'Batch execute ' + '\r\n 任务数据 :'+ taskMap.size() + taskMap.values() ;
            }

            if (!oppMap.isEmpty()) {
                update oppMap.values();
                logstr += 'Batch execute ' + '\r\n 询价数据 :'+ oppMap.size() + oppMap.values() ;
            }
           
            
            logstr += '\nend';
        } catch(Exception ex) {
            //发生错误的情况
            System.debug(Logginglevel.ERROR, 'NFM112_' + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM112_' + ':' + ex.getStackTraceString());
            logstr += ex.getMessage();
            log.ErrorLog__c += ex.getMessage() + '\n';
            log.ErrorLog__c += ex.getStackTraceString() + '\n';
        }

        log.Log__c = logstr;
        insert log;
    }

    global void finish(Database.BatchableContext BC) {
        system.debug('opporTotal======'+opporTotal);
        system.debug('taskTotal======'+taskTotal);        
    }
}