//update by rentx 20210520 start 1635
// global class TransferLoanerAutoGiveupBatch implements Database.Batchable<sObject>{
public without sharing class TransferLoanerAutoGiveupBatch implements Database.Batchable<sObject> , Database.Stateful {
    // global List<String> emailMessages = new List<String>();
    // global Integer totalCount = 0; // 总件数
    // global Integer failedCount = 0;
    // global Date tdy = Date.today();
//update by rentx 20210520 end 1635

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

    public List<String> emailMessages = new List<String>();
    public Integer totalCount = 0; // 总件数
    public Integer failedCount = 0;
    public Date tdy = Date.today();

    public TransferLoanerAutoGiveupBatch() {
    }

    //还没上线 先注释掉
    // 2021-03-05  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
     public TransferLoanerAutoGiveupBatch(Boolean NeedExecute) {
         this.IsNeedExecute = NeedExecute;
     }
    // 2021-03-05  mzy  WLIG-BYHD79  SFDC环境batch合并调查  end

    public Database.QueryLocator start(Database.BatchableContext bc) {
        bp3_Setting__c conf = bp3_Setting__c.getOrgDefaults();
        //当前时间的前90天
        //update by rentx 20210607 start 把90天断念调整为1天
        Date autoGiveupDate90 = tdy.addDays(-(conf.Lonar_Auto_GiveUp_Day__c == null ? 90 : Integer.valueOf(conf.Lonar_Auto_GiveUp_Day__c)));
        // Date autoGiveupDate90 = tdy.addDays(-1);
        //update by rentx 20210607 end
        //当前时间的前30天
        Date autoGiveupDate30 = Date.today().addDays(-(conf.Auto_GiveUp_Day__c == null ? 30 : Integer.valueOf(conf.Auto_GiveUp_Day__c)));
        Date autoGiveupStartDate = conf.Auto_Giveup_StartDate__c == null ? Date.valueOf('1970-01-01') : conf.Auto_Giveup_StartDate__c;
        return Database.getQueryLocator(
            //update by rentx 2021-05-11 start 1635
           [SELECT Id
                   ,LostReport_Detail__c
                   ,LostReport_Detail__r.LostReport_Status_F__c
                   ,LostReport_Detail__r.LostReport__c 
                FROM TransferApplyDetail__c
                WHERE Lost_item_giveup__c = false
                AND Check_lost_Item_F__c = '欠品'
                AND Redeliver_SlipNo__c = null
                //取消注释by rentx 2021-05-19 start 1635
                AND Auto_Giveup_Compare_Day__c >= :autoGiveupStartDate 
                //取消注释by rentx 2021-05-19 end 1635
                AND Auto_Loaner_Giveup_StartCalculating_Date__c != null
                AND (    // 非固定资产
                        // (Internal_Asset_number_key__c = null
                        (Loaner_asset_no__c = null
                            AND Auto_Loaner_Giveup_StartCalculating_Date__c <= :autoGiveupDate30
                        )
                        // 固定资产
                     // OR (Internal_Asset_number_key__c != null
                     OR (Loaner_asset_no__c != null
                        //update by rentx 2021-05-13 start 1635 固定资产时时 确认遗失30天后断念 未确认遗失90天后断念
                        // AND ((Confirm_Lost_Date__c = null AND Auto_Loaner_Giveup_StartCalculating_Date__c <= :autoGiveupDate90)
                        //     OR (Confirm_Lost_Date__c != null AND Auto_Loaner_Giveup_StartCalculating_Date__c <= :autoGiveupDate30))
                            AND Auto_Loaner_Giveup_StartCalculating_Date__c <= :autoGiveupDate90
                        //update by rentx 2021-05-13  end 1635 
                        )
                    )
            ORDER BY Id]
        );
    }

    public void execute(Database.BatchableContext BC, list<TransferApplyDetail__c> tadList) {
        Savepoint sp = Database.setSavepoint();
        try{
            totalCount += tadList.size();
            //System.debug(totalCount);
            List<LostReport_Detail__c> lsList = new List<LostReport_Detail__c>();
            for (TransferApplyDetail__c tad : tadList) {
                //update by rentx 2021-05-14 start
                //拿到已提交未审批通过的遗失报告明细 去调回 之前是被注释掉的 
                if (String.isNotBlank(tad.LostReport_Detail__c) && tad.LostReport_Detail__r.LostReport_Status_F__c != '已批准') {
                    lsList.add(tad.LostReport_Detail__r);
                }
                //注释byrentx2021-05-14 start 
                // tad.Lost_item_giveup__c = true;
                // tad.Loaner_Giveup_Time__c = Datetime.now();
            }
            // update tadList;
            //注释byrentx20210514 end
            //System.debug(totalCount);
            // ToDo 遗失报告如果需要集計的话。需要设置公式字段到Text字段
            LostReportHandler.Loaner_AutoGiveup(null, lsList, null,tadList);
            // 上面这个调用的之前也是被注释掉了,
            //update by rentx 2021-05-14 send 1635

        }
        catch (Exception e) {
            emailMessages.add(e.getMessage());
            System.debug(emailMessages);
            failedCount += tadList.size();
            System.debug(failedCount);
            Database.rollback(sp);
        }        
    }

    public void finish(Database.BatchableContext BC) {
        
        BatchEmailUtil be = new BatchEmailUtil();
        String[] toList = new String[]{UserInfo.getUserEmail()};
        String title = '调拨自动断念';
        String[] ccList = new String[] {};
        if(this.emailMessages.size() == 0){
            be.successMail(toList, ccList, title, totalCount);
        }else{
            String emailLabel = 'BatchNotify';
            for (OrgWideEmailAddress tmpEmailObj : [SELECT Id, Address, DisplayName 
                    FROM OrgWideEmailAddress
                    WHERE DisplayName like :emailLabel]) {
                ccList.add(tmpEmailObj.Address);
            }
            be.failedMail(toList, ccList, title,
                String.join(this.emailMessages, '\n'),
                totalCount, totalCount - failedCount, failedCount);
        }
        be.send();

        //还没上线 先注释掉
        // 2021-03-05  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
        // if(!Test.isRunningTest() &&IsNeedExecute==true){
            //batch里调用下一个batch时，希望跟原有的Schedule里面传的条数保持一致
            // Id execBTId = Database.executebatch(new PowerBIUpdateBatch(true),200);
        // }
        // 2021-03-05  mzy  WLIG-BYHD79  SFDC环境batch合并调查  end

    }
}