global with sharing class OTCLogisticsBatch implements Database.Batchable<sObject>, Database.AllowsCallouts{
    public String query;
    public String sodn;
    global OTCLogisticsBatch() {
        this.query = query;
    }
    global OTCLogisticsBatch(String sodn) {
        this.query = query;
        this.sodn = sodn;
    }
    global Database.QueryLocator start(Database.BatchableContext bc) {

        // 获取发货DN 中DN安装日期 不为空 
        query = 'select id,name from Statu_Achievements_DN__c where InstallDate__c = null and CreatedDate >= LAST_N_DAYS:30';
        if (sodn != null && sodn != '') {
            query += ' And Name = :sodn';
        }   
        // query += ' limit 50';
        System.debug('执行的SQL为：'+query);
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Statu_Achievements_DN__c> SadList) {
        // 存储 cn 号
        List<String> cnList = new List<String>();
        for (Statu_Achievements_DN__c i : SadList) {
            cnList.add(i.name.subString(2));
        }
        System.debug('打印数据：'+cnList);
        // 通过cn号到OTS物流运货单再进行一次数据过滤 
        List<String> statusList = new List<String>{'已签收', '签收异常', '已作废', '已合并', '已完成'};
        // List<waybill__c> waybillList = [select id,name,waybill_number__c,waybill_status__c from waybill__c where waybill_number__c in :cnList and waybill_status__c NOT IN :statusList];
        List<waybill__c> waybillList = [select id,name,waybill_number__c,waybill_status__c from waybill__c];
        // 通过过滤后的订单号去请求接口用于获取最新物流状态
        System.debug('打印已有的数据：'+waybillList);
        Map<String, String> wmap = new Map<String, String>();
        for (waybill__c w : waybillList) {
            wmap.put(w.waybill_number__c,w.waybill_status__c);
       }
       List<String> slist = new List<String>();
       for (String c : cnList) {
           String value = wmap.get(c);
           if (value == null) {
                slist.add(c);
                System.debug('添加的数据：'+c);
           }else {
            if (!statusList.contains(value)) {
                slist.add(c);
                System.debug('更新数据：'+c);
            }else {
                System.debug('没有要更新的数据');
            }
           }
       }
       if (slist.size()>0) {
            for (String s : slist) {
                NFM118Controller.executefuture('',s);
            }
       }
    }

    global void finish(Database.BatchableContext BC) {

    }
}