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.Date;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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

    public static void main(String[] args) {
        final String key = "ods.change.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("[OdsChangeTaskMain]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        if (HistoryConfig.getInt(allTaskKey, 0) == 1) {
            System.out.println("[OdsChangeTaskMain][ALL]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        if (HistoryConfig.getInt(dailyTaskKey, 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();
        // 一个参数： 参数为向后加几天
        // 两个参数： 第一个参数为向前减减几天，第二个参数向后加几天
        int argsLengthValue1 = 1;
        int argsLengthValue2 = 2;
        if (args == null || args.length == 0 || args.length > argsLengthValue2) {
            args = new String[]{"-1", "0"};
        } else if (args.length == argsLengthValue1) {
            args = new String[]{"-1", args[0]};
        } else if (args.length == argsLengthValue2) {
            args = new String[]{args[0], args[1]};
        }
        // 开始日期位移天数
        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();
        // 5.2 ODS飞行计划调整单接口
        threadPool.execute(new Runnable() {

            @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();
    }
}
