global class InventoryAutoGiveupBatch 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();
    Boolean IsNeedExecute = false;
    
    /**
     * コンスタント
     */
    global InventoryAutoGiveupBatch() {
    }
    global InventoryAutoGiveupBatch(Boolean NeedExecute) {
        this.IsNeedExecute = NeedExecute;
    }

    /**
     * startには、queryを実行、备品Set明细を検索
     */
    global Database.QueryLocator start(Database.BatchableContext BC) {
        bp3_Setting__c conf = bp3_Setting__c.getOrgDefaults();
        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;
        String query = 'SELECT Id,LostReport_Detail__c,LostReport_Detail__r.LostReport_Status_F__c,LostReport_Detail__r.LostReport__c';
        query+= ' FROM Inventory_Detail__c';
        query+= ' WHERE Auto_Lost_item_giveup__c = false AND Inventory_Deviation__c < 0 AND Internal_Asset_Flg__c = true AND Inventory_Time__c != null';
        query+= ' AND Auto_Loaner_Giveup_StartCalculating_Date__c >= :autoGiveupStartDate AND Auto_Loaner_Giveup_StartCalculating_Date__c != null AND Auto_Loaner_Giveup_StartCalculating_Date__c <= :autoGiveupDate30 ORDER BY Id';
        if(Test.isRunningTest()){
            query += ' limit 1';
        }
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<SObject> ldList) {
        Savepoint sp = Database.setSavepoint();
        try{
            totalCount += ldList.size();
            List<LostReport_Detail__c> lsList = new List<LostReport_Detail__c>();
            for (SObject sa : ldList) {
                Inventory_Detail__c ld = (Inventory_Detail__c)sa;
                if (String.isNotBlank(ld.LostReport_Detail__c) && ld.LostReport_Detail__r.LostReport_Status_F__c != '已批准') {
                    lsList.add(ld.LostReport_Detail__r);
                }
            }
            System.debug(totalCount);
            //update by rentx 2021-05-14 start 1635
            // LostReportHandler.Loaner_AutoGiveup(null, lsList, ldList);
            LostReportHandler.Loaner_AutoGiveup(null, lsList, ldList, null);
            //update by rentx 2021-05-14 end 1635
        }
        catch (Exception e) {
            emailMessages.add(e.getMessage());
            failedCount += ldList.size();
            Database.rollback(sp);
        }
    }
    global 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();

        //2022/2/21 pk 发货七天还未到货数 start
        if(!Test.isRunningTest() && IsNeedExecute==true){
            //batch里调用下一个batch时，希望跟原有的Schedule里面传的条数保持一致
            Id execBTId = Database.executebatch(new Consumable7daysBatch(true),200);
        }
        //2022/2/21 pk 发货七天还未到货数 end
    }
}