global class TargetCustomerAssignmentBatch implements Database.Batchable<sObject>  , Database.Stateful{
   //SWAG-BHP42V    精琢技术  20191205 START 
    public String query;
    String opdId;//需要单独执行的OPD计划
    list<String> opdIdList;//需要批量执行的OPD计划
    global List<String> emailMessages = new List<String>();
    global Integer totalCount = 0; // 总件数
    global Integer failedCount = 0;

    Boolean IsNeedExecute = false; // 2021-03-08  mzy  WLIG-BYHD79  SFDC环境batch合并调查  是否符合执行条件

    global TargetCustomerAssignmentBatch() {

    }
    global TargetCustomerAssignmentBatch(String opdId) {
        this.opdId = opdId;
    }
    global TargetCustomerAssignmentBatch(List<String> opdIdList) {
        this.opdIdList = opdIdList;
    }

    global TargetCustomerAssignmentBatch(Boolean needExecute) {
        IsNeedExecute = needExecute;  // 2021-03-08  mzy  WLIG-BYHD79  SFDC环境batch合并调查  
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        //检索OPD计划中 的 Id，客户-目标客户的查找字段，战略科室ID
        String query ='select Id,OPD_Customers_Target__c,OCM_category_ID__c,OPDPlan_ImplementDate__c from OPDPlan__c where OPD_Customers_Target__c = null and OCM_category_ID__c  != null and OPDPlan_ImplementDate__c != null';
        
        //单独更新OPD计划
        if (!string.isblank(opdId)) {
            query += ' and id = :opdId ';
        }
        //批量更新OPD计划 
        if (opdIdList != null) {
            query += ' and id in: opdIdList ';
        }
            System.debug('sql语句：'+query);
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<OPDPlan__c> scList) {
        
        try{
            List<OPDPlan__c> opdPlanList  = new List<OPDPlan__c>();
            //当annual为空时 则有可能是4月1日创建的 则不用更新 第二天会更新
            System.debug('返回的数据：'+scList );
            

                //将OPD计划的战略科室id放到List 当做客户-目标客户的检索条件
                 Map<string, string> accsMap = new Map<string, string>();
                 //SWAG-BHP42V    精琢技术  20191209 START 
                 // 将OPD计划的战略科室id作为key ，本财年作为value 用于下面判断
                 Map<string, string> opdMap = new Map<string, string>();

                    for(OPDPlan__c op :scList ){
                        accsMap.put(op.OCM_category_ID__c, op.Id);
                        Date dateToday = op.OPDPlan_ImplementDate__c;
                        // Date yesterday = dateToday.addDays(-1);
                        Integer year = dateToday.year();
                        Integer month = dateToday.month();
                         if (month < 4) {
                             year -= 1;
                         }
                        // String ocmYear = year + '年度';
                        String annual = year - 1867 + 'P';
                        opdMap.put(op.OCM_category_ID__c,annual);
                    }

                System.debug('accsMap-->'+ accsMap);
                //检索OPD计划的战略科室的所有客户-目标客户
                List<Account_Number_of_target__c> anotList = [select Id,OCM_Period__c,Submit_Customer_target_new__c,Account__c 
                                                             from Account_Number_of_target__c 
                                                             where Account__c IN :accsMap.keySet()];
               //SWAG-BSC5WP 20201113 you 拿掉条件--Submit_Customer_target_new__c =true And  是防止 跨财年目标客户为空得情况
                                                             System.debug('anotList' + anotList.size());
                       for(Account_Number_of_target__c an :anotList ){
                            //判断是否为同一战略科室
                            String subStr = an.Account__c;
                            if(accsMap.containsKey(subStr.SubString(0,15))){
                                System.debug('anotList1' + anotList.size());
                                //判断本年度财年是否相同
                                if(opdMap.get(subStr.SubString(0,15)) == an.OCM_Period__c){
                                    System.debug('anotList2' + anotList.size());
                                    totalCount ++;
                                    OPDPlan__c opdplan =new OPDPlan__c();
                                    opdplan.Id = accsMap.get(subStr.SubString(0,15));
                                    //把目标客户Id 赋值给 opd计划 的查找字段
                                    opdplan.OPD_Customers_Target__c = an.Id;
                                    opdPlanList.add(opdplan);

                                } 
                            
                            }
                        }     
                
                //SWAG-BHP42V    精琢技术  20191209 END 
            System.debug('更新的数据：'+opdPlanList);

            //更新OPD计划对象上的客户-目标客户的查找字段
            if (opdPlanList.size() > 0) update opdPlanList;

            if (System.Test.isrunningTest()) {
                throw new ControllerUtil.myException('test。');
            }

        }catch(Exception e){
            emailMessages.add(e.getMessage());
            System.debug(emailMessages);
            failedCount ++;
            System.debug(failedCount);
        }
          
    }

    global void finish(Database.BatchableContext BC) {
            sendFieldEmail();
        //2021-06-07 mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
        if(!Test.isRunningTest() &&IsNeedExecute==true){
           List<Consum_Apply_Meta__mdt> camList = [SELECT Id
                        , Key__c
                        , ValueLong__c
                     FROM Consum_Apply_Meta__mdt
                    WHERE Package__c = 'InventoryAutoDeleteBatch'
                      AND Key__c = 'dateLimit'];
            Integer dateLimit = 2;
            for (Consum_Apply_Meta__mdt camt : camList) {
                dateLimit = Integer.valueOf(camt.ValueLong__c);
            } 
          //batch里调用下一个batch时，希望跟原有的Schedule里面传的条数保持一致
           Id execBTId = Database.executebatch(new ConsumApplyInventoryAutoDeleteBatch(dateLimit,true),200);
        }
        //2021-06-07  mzy  WLIG-BYHD79  SFDC环境batch合并调查 end
    }
    private void sendFieldEmail() {
            PretechBatchEmailUtil be = new PretechBatchEmailUtil();
            String[] toList = new String[] {UserInfo.getUserEmail()};
            String title = '更新OPD计划客户-目标客户失败';
            String[] ccList = new String[] {};
            if(System.Test.isRunningTest()){
                be.successMail('', 1);
            }
            if (emailMessages.size() > 0) {
                be.failedMail(toList, ccList, title, String.join(this.emailMessages, '\n'), totalCount, totalCount - failedCount, failedCount, '',false);
                be.send();
            }

    }
    //SWAG-BHP42V    精琢技术  20191205 END
}