global class OpportunityUpdateSendEmailBatch implements Database.Batchable<sObject>,Database.Stateful {
    private List<String> idList = null;

    global OpportunityUpdateSendEmailBatch() {
       
    }

    global OpportunityUpdateSendEmailBatch(List<String> temp) {
       idList = temp;
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        //每日执行，询价今日有更新、三个月未更新、六个月未更新三种情况发邮件提醒，九个月未更新询价取消并发邮件提醒。
        Date yesterDay = Date.today().addDays(-1);
        if(idList != null && idList.size()!=0){
            return Database.getQueryLocator([select Id,Name,IsSendEmail__c,IsUpdate__c,OppUpdateDate__c,ThreeMonths__c,SixMonths__c,NineMonths__c,Province__c,ProductSegment__c,OneYear__c,
                OppUpdateAddress__c,Cancel_Fail_Approve__c,InquiryNumber__c,Cancel_reason_D__c,Cancel_Reason_Text_D__c,CancelReason__c,CancelReasonText__c 
                from Opportunity where (((ProductSegment__c = 'NDT' or ProductSegment__c = 'ANI') and RecordTypeId = '012280000005hjO') or ProductSegment__c = 'RVI' or ProductSegment__c = 'IE' or ProductSegment__c = 'BS') and CreatedBy.IsActive = true 
                and IsSendEmail__c=true and StageName != 'Closed Won' and StageName != 'Closed Lost' and StageName != 'Closed Cancel' and ((IsUpdate__c = true and OppUpdateDate__c > :yesterDay.addMonths(-3)) or 
                (OppUpdateDate__c <= :yesterDay.addMonths(-3) and OppUpdateDate__c > :yesterDay.addMonths(-6) and ThreeMonths__c = false) or 
                (OppUpdateDate__c <= :yesterDay.addMonths(-6) and OppUpdateDate__c > :yesterDay.addMonths(-9) and SixMonths__c = false) or 
                (OppUpdateDate__c <= :yesterDay.addMonths(-9) and OppUpdateDate__c > :yesterDay.addMonths(-12) and NineMonths__c = false) or 
                (OppUpdateDate__c <= :yesterDay.addMonths(-12) and OneYear__c = false)) and Id in :idList]);
        }else{
            return Database.getQueryLocator([select Id,Name,IsSendEmail__c,IsUpdate__c,OppUpdateDate__c,ThreeMonths__c,SixMonths__c,NineMonths__c,Province__c,ProductSegment__c,OneYear__c,
                OppUpdateAddress__c,Cancel_Fail_Approve__c,InquiryNumber__c,Cancel_reason_D__c,Cancel_Reason_Text_D__c,CancelReason__c,CancelReasonText__c 
                from Opportunity where (((ProductSegment__c = 'NDT' or ProductSegment__c = 'ANI') and RecordTypeId = '012280000005hjO') or ProductSegment__c = 'RVI' or ProductSegment__c = 'IE' or ProductSegment__c = 'BS') and CreatedBy.IsActive = true
                and IsSendEmail__c=true and StageName != 'Closed Won' and StageName != 'Closed Lost' and StageName != 'Closed Cancel' and ((IsUpdate__c = true and OppUpdateDate__c > :yesterDay.addMonths(-3)) or 
                (OppUpdateDate__c <= :yesterDay.addMonths(-3) and OppUpdateDate__c > :yesterDay.addMonths(-6) and ThreeMonths__c = false) or 
                (OppUpdateDate__c <= :yesterDay.addMonths(-6) and OppUpdateDate__c > :yesterDay.addMonths(-9) and SixMonths__c = false) or 
                (OppUpdateDate__c <= :yesterDay.addMonths(-9) and OppUpdateDate__c > :yesterDay.addMonths(-12) and NineMonths__c = false) or 
                (OppUpdateDate__c <= :yesterDay.addMonths(-12) and OneYear__c = false))]);
        }
    }

    global void execute(Database.BatchableContext BC, list<Sobject> scope) {
        Date yesterDay = Date.today().addDays(-1);
        List<Opportunity> oppList = new List<Opportunity>();
        for(Sobject obj : scope){
            Opportunity opp = (Opportunity)obj;
            if(opp.IsUpdate__c == true && opp.OppUpdateDate__c == yesterDay){
                if(opp.ProductSegment__c == 'NDT' || opp.ProductSegment__c == 'ANI'){
                    //分野不同需要发送到不同的人 NDT郭爽：00528000000YVMP ANI李文珺：00528000000YSSm
                    String members = System.label.OppUpdateAddressMember;
                    if (String.isNotBlank(members)) {
                        if(opp.ProductSegment__c == 'NDT'){
                            opp.OppUpdateAddress2__c = members.split('_')[0];
                        }else if(opp.ProductSegment__c == 'ANI'){
                            opp.OppUpdateAddress2__c = members.split('_')[1];
                        }
                    }
                    String memberId = getMember(opp.ProductSegment__c,opp.Province__c);
                    opp.OppUpdateAddress__c = memberId;
                    if(memberId == '00528000000YVJk'){
                       opp.OppUpdateAddress__c = '00528000006hJeB';
                    }
                    opp.IsUpdate__c = false;
                    opp.IsUpdate_temp__c = true;
                    oppList.add(opp);
                    continue;
                }
                if(opp.ProductSegment__c == 'RVI'){
                    opp.IsUpdate__c = false;
                    opp.IsUpdate_temp__c = true;
                    oppList.add(opp);
                    continue;
                }
                
            }
            if(opp.OppUpdateDate__c <= yesterDay.addMonths(-3) && opp.OppUpdateDate__c > yesterDay.addMonths(-6) && opp.ThreeMonths__c == false){
                opp.ThreeMonths_temp__c = true;
                opp.ThreeMonths__c = true;
                opp.AutoClosedDate__c = getAutoClosedDate(opp.ProductSegment__c,opp.OppUpdateDate__c);
                oppList.add(opp);
                continue;
            }
            if (opp.OppUpdateDate__c <= yesterDay.addMonths(-6) && opp.OppUpdateDate__c > yesterDay.addMonths(-9) && opp.SixMonths__c == false) {
                opp.SixMonths_temp__c = true;
                opp.SixMonths__c = true;
                opp.AutoClosedDate__c = getAutoClosedDate(opp.ProductSegment__c,opp.OppUpdateDate__c);
                oppList.add(opp);
                continue;
            }
            if (opp.OppUpdateDate__c <= yesterDay.addMonths(-9) && opp.OppUpdateDate__c > yesterDay.addMonths(-12) && opp.NineMonths__c == false) {
                opp.NineMonths_temp__c = true;
                opp.NineMonths__c = true;
                opp.AutoClosedDate__c = getAutoClosedDate(opp.ProductSegment__c,opp.OppUpdateDate__c);
                if(opp.ProductSegment__c == 'NDT' || opp.ProductSegment__c == 'ANI'){
                    opp.IsSendEmail__c = false;
                    opp.StageName = 'Closed Cancel';
                    opp.Cancel_Fail_Approve__c = 'Pass';
                    opp.Cancel_reason_D__c = 'Other';
                    opp.Cancel_Reason_Text_D__c = '编号为：'+opp.InquiryNumber__c+'的询价，9个月未有进展，已被CRM系统自动取消。';
                    opp.CancelReason__c = 'Other';
                    opp.CancelReasonText__c = '编号为：'+opp.InquiryNumber__c+'的询价，9个月未有进展，已被CRM系统自动取消。';
                    String memberId = getMember(opp.ProductSegment__c,opp.Province__c);
                    opp.OppUpdateAddress__c = memberId;
                    if(memberId == '00528000000YVJk'){
                       opp.OppUpdateAddress__c = '00528000006hJeB';
                    }
                    
                }
                oppList.add(opp);
                continue;
            }
            if(opp.OppUpdateDate__c <= yesterDay.addMonths(-12) && opp.OneYear__c == false){
                if(opp.ProductSegment__c != 'NDT' && opp.ProductSegment__c != 'ANI'){
                    opp.OneYear__c = true;
                    opp.OneYear_temp__c = true;
                    opp.IsSendEmail__c = false;
                    opp.StageName = 'Closed Cancel';
                    opp.Cancel_Fail_Approve__c = 'Pass';
                    opp.Cancel_reason_D__c = 'Other';
                    opp.Cancel_Reason_Text_D__c = '询价编号'+opp.InquiryNumber__c+',询价名称'+opp.Name+'，已经有一年未进行任何信息更新，已经由系统调整为取消状态，不能再进行任何操作，请了解，谢谢';
                    opp.CancelReasonText__c = '询价编号'+opp.InquiryNumber__c+',询价名称'+opp.Name+'，已经有一年未进行任何信息更新，已经由系统调整为取消状态，不能再进行任何操作，请了解，谢谢';
                    oppList.add(opp);
                }
            }
        }

        if(oppList.size() >0 ) update oppList;
    }

    global void finish(Database.BatchableContext BC) {

    }

    private Date getAutoClosedDate(String productSegment,Date oppUpdateDate){
        if(productSegment == 'NDT' || productSegment == 'ANI'){
            return oppUpdateDate.addMonths(9);
        }else{
            return oppUpdateDate.addMonths(12);
        }
    }

    private String getMember(String type,String province){
        if (String.isNotBlank(type) && String.isNotBlank(province)) {
            if (type == 'NDT') {

                String NDTGuanZhao = System.label.NDTGuanZhao;
                String NDTLiuJianHua = System.label.NDTLiuJianHua;
                String NDTPanWei = System.label.NDTPanWei;
                String NDTYuDaZhi = System.label.NDTYuDaZhi;
               
                if(NDTGuanZhao.indexOf(province) != -1){
                    return NDTGuanZhao.split('_')[1];
                }
                if(NDTLiuJianHua.indexOf(province) != -1){
                    return NDTLiuJianHua.split('_')[1];
                }
                if(NDTPanWei.indexOf(province) != -1){
                    return NDTPanWei.split('_')[1];
                }
                if(NDTYuDaZhi.indexOf(province) != -1){
                    return NDTYuDaZhi.split('_')[1];
                }
            }else if (type == 'ANI') {
                String ANIGuanZhao = System.label.ANIGuanZhao;
                String ANILiuJianHua = System.label.ANILiuJianHua;
                String ANIPanWei = System.label.ANIPanWei;
                String ANIYuDaZhi = System.label.ANIYuDaZhi;
                if(ANIGuanZhao.indexOf(province) != -1){
                    return ANIGuanZhao.split('_')[1];
                }
                if(ANILiuJianHua.indexOf(province) != -1){
                    return ANILiuJianHua.split('_')[1];
                }
                if(ANIPanWei.indexOf(province) != -1){
                    return ANIPanWei.split('_')[1];
                }
                if(ANIYuDaZhi.indexOf(province) != -1){
                    return ANIYuDaZhi.split('_')[1];
                }
            }
        }
        return null;
    }
}