package com.foc.task;

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;

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;

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

    public static void main(String[] args) {
        final String key = "ods.task.is.running";
        final String allTaskKey = "all.task.is.running";
        final String dailyTaskKey = "daily.task.is.running";
        if (HistoryConfig.getInt(key, 0) == 1) {
            System.out.println("[OdsTaskMain]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        if (HistoryConfig.getInt(allTaskKey, 0) == 1) {
            System.out.println("[OdsTaskMain][ALL]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        if (HistoryConfig.getInt(dailyTaskKey, 0) == 1) {
            System.out.println("[OdsTaskMain][DAILY]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        HistoryConfig.put("ods.task.last.time", DateUtil.getDateTime());
        HistoryConfig.put(key, "1");
        HistoryConfig.saveHistory();
        long startTime = System.nanoTime();
        // 一个参数： 参数为向后加几天
        // 两个参数： 第一个参数为向前减减几天，第二个参数向后加几天
        int argsLength = 2;
        if (args == null || args.length == 0 || args.length > argsLength) {
            args = new String[]{"-1", "0"};
        } else if (args.length == 1) {
            args = new String[]{"-1", args[0]};
        } else if (args.length == argsLength) {
            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) {
            String argsValue = "-1";
            if (argsValue.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("[OdsTaskMain]统计时间段[" + dateFrom + "]TO[" + dateTo + "]");


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String modified = sdf.format(new Date());
        System.out.println("[OdsTaskMain][修改时间]" + modified);
        // TODO Auto-generated method stub
        final ExecutorService threadPool = Executors.newCachedThreadPool();
        // 5.1 ODS飞行计划接口（亦即机组排班接口）
        threadPool.execute(new Runnable() {

            @Override
            public void run() {
                // 优先同步今天的数据
                if (0 >= start && 0 <= days) {

                    startODSTask(threadPool, 0, modified);
                }
                for (int i = start; i <= days; i++) {
                    if (i != 0) {
                        // 插入或更新ods数据
                        startODSTask(threadPool, i, modified);
                    }
                }
            }
        });
        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 startODSTask(ExecutorService threadPoolSecond, final int offsetDateIndex, final String modified) {
        /**
         * ODS飞行计划
         */
        ODSTask oDSTask = new ODSTask(new TaskSupporter() {

            final ODSService oDSService = new ODSService();
            final String flightDate = DateUtil.dateToStr(DateUtil.offsetDate(new Date(), offsetDateIndex), DateUtil.DATE_FORMAT);

            @Override
            public String setBaseUrl(TaskTemplate taskTemplate) {

                return GConstants.FOC_ODS_URL + "&companyCodes=CBJ&pageParam.pageIndex=" + taskTemplate.getPageIndex()
                        + "&pageParam.pageSize=" + GConstants.PAGE_SIZE;
            }

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

                Map<String, String> params = new TreeMap<String, String>();
                params.put("flightDate", flightDate);
                return params;
            }

            @Override
            public void successHandle(JSONObject result) {

                oDSService.insertOdsData(result, modified);
            }

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

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

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

            @Override
            public String getApiName() {

                return "ods";
            }

            @Override
            public boolean finish() {
                // TODO Auto-generated method stub

                oDSService.finish(flightDate, modified);
                return false;
            }
        });

        oDSTask.run();

    }
}
