package com.foc.task;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.alibaba.fastjson.JSONObject;
import com.foc.TaskSupporter;
import com.foc.TaskTemplate;
import com.foc.conf.GConstants;
import com.foc.conf.HistoryConfig;
import com.foc.fetcher.HCFetcher;
import com.foc.ods.ODSTask;
import com.foc.ods.service.ODSService;
import com.foc.util.DateUtil;

/**
 * 每天定时同步昨天和今天的数据
 * 只同步ODS数据
 * *#1  *  *  *  *  root bash /mnt/foc/project/task/runodschangetask.sh
 * 导出文件名称： jd-task-odschange-2.0.jar
 * 
 * @team IT Team
 * @author renmb
 * @version 1.0
 * @time  2016年10月3日
 */
public class ODSChangeTaskMain {

    public static void main(String[] args) {
//        System.out.println(DateUtil.getDateTime().replaceAll("[-|:|\\s]", "")+".json");
//        System.exit(0);
//        Logger logger = Logger.getLogger(BefBasicArchiveMain.class);
        final String key = "ods.change.task.is.running";
        if (HistoryConfig.getInt(key, 0) == 1) {
            System.out.println("[ODSChangeTaskMain]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        if (HistoryConfig.getInt("all.task.is.running", 0) == 1) {
            System.out.println("[ODSChangeTaskMain][ALL]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        if (HistoryConfig.getInt("daily.task.is.running", 0) == 1) {
            System.out.println("[ODSChangeTaskMain][DAILY]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        HistoryConfig.put("ods.change.task.last.time", DateUtil.getDateTime());
        HistoryConfig.put(key, "1");
        HistoryConfig.saveHistory();
        long startTime = System.nanoTime();
        // 一个参数： 参数为向后加几天
        // 两个参数： 第一个参数为向前减减几天，第二个参数向后加几天
        if(args == null || args.length ==0 || args.length > 2){
            
            args = new String[]{"-1", "0"};
        } else if(args.length == 1){
            
            args = new String[]{"-1", args[0]};
        } else if(args.length == 2){
            
            args = new String[]{args[0], args[1]};
        }
//        Calendar calendar = Calendar.getInstance();
//        int hour = calendar.get(Calendar.HOUR_OF_DAY);
//        int timeOffset = GConstants.getIntValue("start.time.offset.hour", 8);
//        if(hour>timeOffset){
//            if("-1".equals(args[0])){
//                args[0] = "0";
//            }
//        }
        final int start = Integer.valueOf(args[0]);// 开始日期位移天数
        final int days = Integer.valueOf(args[1]);// 结束日期位移天数
        String dateFrom = DateUtil.dateToStr(DateUtil.offsetDate(new Date(), start), DateUtil.DATE_FORMAT);
        String dateTo   = DateUtil.dateToStr(DateUtil.offsetDate(new Date(), days), DateUtil.DATE_FORMAT);
        
        System.out.println("[ODSChangeTaskMain]统计时间段["+dateFrom+"]TO["+dateTo+"]");
        
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String modified = sdf.format(new Date());
        System.out.println("[ODSChangeTaskMain][修改时间]"+modified);
        // TODO Auto-generated method stub
        final ExecutorService threadPool = Executors.newCachedThreadPool();

        threadPool.execute(new Runnable() {// 5.2 ODS飞行计划调整单接口

            @Override
            public void run() {
                
                startODSChangeTask(threadPool, modified, start, days);
            }
        });
        threadPool.shutdown();

        while (true) {
            if (threadPool.isTerminated()) {
                System.out.println("线程池结束了！");
                HCFetcher.getInstance().shutdown();
                
                long endTime = System.nanoTime();
                long duration = endTime - startTime;
                System.out.println("执行存储过程总共用时：" + duration + "纳秒");
                System.out.println("执行存储过程总共用时格式化：" + DateUtil.getDurationTime(duration));
                HistoryConfig.put(key, "0");
                HistoryConfig.saveHistory();
                
                System.exit(0);
                break;
            }
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    private static void startODSChangeTask(ExecutorService threadPoolSecond, final String modified, final int startDateIndex, final int offsetDateIndex) {
        /**
         * ODS飞行计划调整单
         */
        ODSTask oDSChangeTask = new ODSTask(new TaskSupporter() {

            @Override
            public String setBaseUrl(TaskTemplate taskTemplate) {
                return GConstants.FOC_ODS_CHANGE_URL + "&pageParam.pageIndex=" + taskTemplate.getPageIndex()
                        + "&pageParam.pageSize=" + GConstants.PAGE_SIZE;
            }

            @Override
            public Map<String, String> setParams() {

                Map<String, String> params = new TreeMap<String, String>();
                
                String fltChangeDateFrom = DateUtil.dateToStr(DateUtil.offsetDate(new Date(), startDateIndex), DateUtil.DATE_FORMAT);
                String fltChangeDateTo   = DateUtil.dateToStr(DateUtil.offsetDate(new Date(), offsetDateIndex), DateUtil.DATE_FORMAT);
                params.put("fltChangeDateFrom", fltChangeDateFrom+" 00:00:00");
                params.put("fltChangeDateTo",   fltChangeDateTo+" 23:59:59");
                return params;
            }

            @Override
            public void successHandle(JSONObject result) {
                ODSService oDSService = new ODSService();
                oDSService.insertOdsChangesAndDetailData(result, modified);
            }

            @Override
            public String setPageIndexProperty() {
                return "foc.ods.change.page.index";
            }

            @Override
            public boolean isGet() {
                return false;
            }

            @Override
            public boolean isPost() {
                return true;
            }
            
            @Override
            public String getApiName() {
                
                return "ods.change";
            }

            @Override
            public boolean finish() {
                // TODO Auto-generated method stub
                return false;
            }
        });
        oDSChangeTask.run();
    }
}
