global class LoanerAutoGiveupBatch 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();

    private static final Map<String,Schema.RecordTypeInfo>  DEVELOPERNAMEMAP  = Schema.SObjectType.Rental_Apply__c.getRecordTypeInfosByDeveloperName();//记录类型 20201119 ljh add

    /**
     * コンスタント
     */
    global LoanerAutoGiveupBatch() {
    }


    /**
     * startには、queryを実行、备品Set明细を検索
     */
    global Database.QueryLocator start(Database.BatchableContext BC) {
        bp3_Setting__c conf = bp3_Setting__c.getOrgDefaults();
        Date autoGiveupDate90 = tdy.addDays(-(conf.Lonar_Auto_GiveUp_Day__c == null ? 90 : Integer.valueOf(conf.Lonar_Auto_GiveUp_Day__c)));
        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(
           [SELECT Id,
                   LostReport_Detail__c,
                   RA_RecordTypeId__c,
                   Is_Body__c,
                   LostReport_Detail__r.LostReport_Status_F__c,
                   LostReport_Detail__r.LostReport__c,
                   Asset__c
              FROM Rental_Apply_Equipment_Set_Detail__c
             WHERE Lost_item_giveup__c = false
               AND Check_lost_Item_F__c = '欠品'
               AND Return_DeliverySlip__c = null
               AND Auto_Giveup_Compare_Day__c >= :autoGiveupStartDate
               AND Auto_Loaner_Giveup_StartCalculating_Date__c != null
               AND (    // 非固定资产
                        (Internal_Asset_number_c__c = null
                            AND Auto_Loaner_Giveup_StartCalculating_Date__c <= :autoGiveupDate30
                        )
                        // 固定资产
                     OR (Internal_Asset_number_c__c != null
                            AND Auto_Loaner_Giveup_StartCalculating_Date__c <= :autoGiveupDate90
                        )
                    )
            ORDER BY Id]
        );
    }

    global void execute(Database.BatchableContext BC, List<SObject> saList) {
        Savepoint sp = Database.setSavepoint();
        try{
            totalCount += saList.size();
            System.debug(totalCount);
            List<LostReport_Detail__c> lsList = new List<LostReport_Detail__c>();
            String ra_RecordTypeId = DEVELOPERNAMEMAP.get('AgencyRequest').getRecordTypeId();
            Set<Id> assIdSet = new Set<Id>();
            for (SObject sa : saList) {
                Rental_Apply_Equipment_Set_Detail__c raesd = (Rental_Apply_Equipment_Set_Detail__c)sa;
                if (raesd.RA_RecordTypeId__c.substring(0,15) == ra_RecordTypeId.substring(0,15)
                    && raesd.Is_Body__c
                ) {
                    assIdSet.add(raesd.Asset__c);
                }
                if (String.isNotBlank(raesd.LostReport_Detail__c) && raesd.LostReport_Detail__r.LostReport_Status_F__c != '已批准') {
                    lsList.add(raesd.LostReport_Detail__r);
                }
            }

            if (assIdSet.size() > 0) {
                List<Id> assIdList = new List<Id>();
                assIdList.addAll(assIdSet);
                FixtureUtil.delOtOLinkData(assIdList);
            }
            System.debug(totalCount);
            // ToDo 遗失报告如果需要集計的话。需要设置公式字段到Text字段
            //update by rentx 2021-05-14 start 1635
            // LostReportHandler.Loaner_AutoGiveup(saList, lsList, null);
            LostReportHandler.Loaner_AutoGiveup(saList, lsList, null, null);
            //update by rentx 2021-05-14 end 1635
        }
        catch (Exception e) {
            emailMessages.add(e.getMessage());
            System.debug(emailMessages);
            failedCount += saList.size();
            System.debug(failedCount);
            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();
        Id execBTId = Database.executeBatch(new InventoryAutoGiveupBatch(), 200);
    }
}