/*2022-05-13  you
* 更新产品咨询单
* 没有确认的，确认天数=今天-创建日----自动 batch
* 有确认的（存在最小日期） 确认天数=最小日期-创建日-----触发器
* ocm管理省中对应的GI，SP助理变化，产品咨询单也变
*/
global class UpdateInquiryFormConfirmationBatch implements Database.Batchable<sObject> {
    public String query;
    public String inqid;
    private BatchIF_Log__c iflog;
    private String stb_Flag;//20220614 WLIG-CER9NQ you

    global UpdateInquiryFormConfirmationBatch() {
        this.query = query;
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'UpdateInquiryFormConfirmationBatch start\n';
        iflog.ErrorLog__c = '';
        insert iflog;
        stb_Flag=System.label.SetPersonalTargetBatch_Flag;
    }

    global UpdateInquiryFormConfirmationBatch(String inqid) {
        this.inqid = inqid;
        this.query = query;
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'UpdateInquiryFormConfirmationBatch start\n';
        iflog.ErrorLog__c = '';
        insert iflog;
        stb_Flag=System.label.SetPersonalTargetBatch_Flag;
    }

    global Database.QueryLocator start(Database.BatchableContext BC) {

        query = 'select TimeoutDays__c, Id,CreateDate__c from Inquiry_form__c where CreateDate__c != null and MinimumDate__c =null';  
        if (inqid != null && inqid !='') {
           query += ' and id = :inqid ';
        }
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Inquiry_form__c> inquiryList) {
        system.debug('==='+inquiryList.size());
        updateTimeoutDays(inquiryList,iflog);
        
        //20220518 you SWAG-CBUB2W start
        Map<String, OCM_Management_Province__c> mpMap = new Map<String, OCM_Management_Province__c>();
        List<OCM_Management_Province__c> ocmList = [select id, Name, GI_assistant__c,SP_assistant__c from OCM_Management_Province__c];
        system.debug('==ocmList='+ocmList.size());
       // 取得OCSM管理省的GI,SP 助理
        for (OCM_Management_Province__c mp : ocmList) {
            mpMap.put(mp.Name, mp);
        }
         updateGISPAssistant(mpMap, iflog);
        //20220518 you SWAG-CBUB2W end
    }
    //确认天数赋值
    public static void updateTimeoutDays(List<Inquiry_form__c> inquiryList, BatchIF_Log__c iflog) {
        String dateToday = String.valueOf(Date.today());
        for(Inquiry_form__c inq:inquiryList){
            String crdate = String.valueOf(inq.CreateDate__c);

            String confdate=calendarUtil.getWorkDayNum(crdate,dateToday);
            if(Integer.valueOf(confdate) > 5){
                inq.TimeoutDays__c = Integer.valueOf(confdate)-5;

             }else{
                inq.TimeoutDays__c = null;
             }
             inq.Confirmation_days__c =null;
            //inq.Confirmation_days__c =Integer.valueOf(confdate);
            system.debug(inq.id+'=相差几天=='+confdate +'==创建日=='+crdate+'==今天=='+dateToday);
        }
        Integer indexCon = 0;
        if(null!=inquiryList && inquiryList.size()>0){
           system.debug('inquiryList==='+inquiryList); 
           Database.SaveResult[] lsrUpdateCon = Database.update(inquiryList, false); 
            for (Database.SaveResult lsrChild : lsrUpdateCon) {

                if (!lsrChild.isSuccess()) {
                    iflog.Is_Error__c = 3;
                    Database.Error emsg = lsrChild.getErrors()[0];
                    iflog.ErrorLog__c += 'confdays: ' + inquiryList.get(indexCon).TimeoutDays__c + ' \n'
                                         + 'inquiryID: ' + inquiryList.get(indexCon).Id + '\n ConLog:' + emsg.getMessage() + '\n';
                    system.debug('lsrChild.isSuccess()=='+iflog.ErrorLog__c); 
                }
                indexCon ++ ;   
            } 
        }
    }  
    public static void updateGISPAssistant(Map<String, OCM_Management_Province__c> mpMap, BatchIF_Log__c iflog) {
         List<Inquiry_form__c> updateInquiryFormList =
            [select id, GI_assistant__c, SP_assistant__c,OCM_man_province_cus__c,IfGotoDepartment__c from Inquiry_form__c
        where (GI_assistant__c !=null or SP_assistant__c !=null)
        and IfGotoDepartment__c = false ]; //还没有转移科室的，说明助理还需要操作，这个时候如果ocsm助理改变，这边也跟着改变
        system.debug('==updateInquiryFormList='+updateInquiryFormList.size());
        for (Inquiry_form__c ifo : updateInquiryFormList) {
            system.debug('==mpMap='+mpMap+'==ifo.OCM_man_province_cus__c=='+ifo.OCM_man_province_cus__c);
            if(null!=mpMap && mpMap.containsKey(ifo.OCM_man_province_cus__c)){
               OCM_Management_Province__c omp = mpMap.get(ifo.OCM_man_province_cus__c);
                if (omp != null) {
                    if(ifo.GI_assistant__c != omp.GI_assistant__c){
                       ifo.GI_assistant__c = omp.GI_assistant__c;
                    }
                    if(ifo.SP_assistant__c != omp.SP_assistant__c){
                       ifo.SP_assistant__c = omp.SP_assistant__c;
                    }
                }
             }
        }
        Integer indexCon = 0;
        Database.SaveResult[] lsrUpdateInq = Database.update(updateInquiryFormList, false);
        for (Database.SaveResult lsrChild : lsrUpdateInq) {
            if (!lsrChild.isSuccess()) {
                iflog.Is_Error__c = 3;
                Database.Error emsg = lsrChild.getErrors()[0];
                iflog.ErrorLog__c += 'GI助理: ' + updateInquiryFormList.get(indexCon).GI_assistant__c + ' \n'
                                     +'SP助理: ' + updateInquiryFormList.get(indexCon).SP_assistant__c + ' \n'
                                     + 'InquiryFormID: ' + updateInquiryFormList.get(indexCon).Id + '\n ConLog:' + emsg.getMessage() + '\n';

            }
            indexCon ++ ;
        }
    }  

    global void finish(Database.BatchableContext BC) {
        system.debug('=====iflog:' + iflog.id+'==='+iflog.ErrorLog__c);
        iflog.Log__c += 'UpdateInquiryFormConfirmationBatch finish()\n';
        iflog.Log__c += '\nUpdateInquiryFormConfirmationBatch end';

        String tmp = iflog.ErrorLog__c;
        if (tmp.length() > 65000) {
            tmp = tmp.substring(0, 65000);
            tmp += ' ...have more lines...';
            iflog.ErrorLog__c = tmp;
        }
        String tmp2 = iflog.Log__c;
        if (tmp2.length() > 65000) {
            tmp2 = tmp2.substring(0, 65000);
            tmp2 += ' ...have more lines...';
            iflog.Log__c = tmp2;
        }
        if (System.Label.Log_IO_Flag == 'Keep') {
            system.debug('jinlaile');
            update iflog;
        } else if (System.Label.Log_IO_Flag == 'Auto') {
            system.debug('jinlaile1');
            if (iflog.Is_Error__c > 0) {
                update iflog;
            }
        }
        //20220614 WLIG-CER9NQ you
        if (stb_Flag=='true') {
          Database.executeBatch(new SetPersonalTargetBatch(), 20);
        }

    }
    @TestVisible private static void test() {
    }
}