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

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

    /**
     * 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 autoGiveupStartDate = conf.Auto_Giveup_StartDate__c == null ? Date.valueOf('1970-01-01') : conf.Auto_Giveup_StartDate__c;
        return Database.getQueryLocator(
           [SELECT Id,
                   LostReport_Status_F__c,
                   LostReport__c,
                   Asset__c
              FROM LostReport_Detail__c
             WHERE DeleteLostReport_Detail_Reason__c = null
               AND CancelLostReport__c = false
               AND LostReport__r.Asset__c != null
               AND LostReport__r.LostReport_approval_time__c >= :autoGiveupStartDate
               AND LostReport__r.LostReport_approval_time__c != null
               AND LostReport__r.LostReport_approval_time__c <= :autoGiveupDate90
            ORDER BY Id]
        );
    }

    global void execute(Database.BatchableContext BC, List<SObject> ldList) {
        Savepoint sp = Database.setSavepoint();
        try{
            totalCount += ldList.size();
            Map<Id, Asset> assMap = new Map<Id, Asset>();
            List<LostReport_Detail__c> lsList = new List<LostReport_Detail__c>();
            for (SObject sa : ldList) {
                LostReport_Detail__c ld = (LostReport_Detail__c)sa;
                assMap.put(ld.Asset__c, new Asset(Id = ld.Asset__c
                                            , Status = FixtureUtil.assetStatusMap.get(FixtureUtil.AssetStatus.Dai_Fei_Qi.ordinal())
                                            , Tobe_Discarded_Date__c = tdy));
                ld.Auto_Lost_item_giveup__c = true;
                lsList.add(ld);
            }
            System.debug(totalCount);
            update lsList;
            update assMap.values();
        }
        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();
    }
}