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.flightdynamics.FlightDynamicsTask;
import com.foc.flightdynamics.service.FlightDynamicsService;
import com.foc.util.DateUtil;

import java.text.SimpleDateFormat;
import java.util.*;

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

    public static void main(String[] args) {
        final String key = "dynamics.task.is.running";
        final String stringValue = "F";
        final String allTaskKey = "all.task.is.running";
        final String dailyTaskKey = "daily.task.is.running";
        final int intValue2 = 2;
        final int intValue3 = 3;
        final long startTime = System.nanoTime();
        try {
            boolean isForce = false;
            if ((args.length >= intValue3 && stringValue.equals((args[intValue2])))) {
                System.out.println("[DynamicsTaskMain]强制模式");
                isForce = true;
            }
            if (!isForce && HistoryConfig.getInt(key, 0) == 1) {
                System.out.println("[DynamicsTaskMain]上次程序正在运行！跳过本次运行。。。");
                return;
            }
            if (!isForce && HistoryConfig.getInt(allTaskKey, 0) == 1) {
                System.out.println("[DynamicsTaskMain][ALL]上次程序正在运行！跳过本次运行。。。");
                return;
            }
            if (HistoryConfig.getInt(dailyTaskKey, 0) == 1) {
                System.out.println("[DynamicsTaskMain][DAILY]上次程序正在运行！跳过本次运行。。。");
                return;
            }
            HistoryConfig.put("dynamics.task.last.time", DateUtil.getDateTime());
            HistoryConfig.put(key, "1");
            HistoryConfig.saveHistory();

//            args = new String[]{"0", "0"};
            // 一个参数： 参数为向后加几天
            // 两个参数： 第一个参数为向前减减几天，第二个参数向后加几天
            if (args.length == 1) {

                args = new String[]{"-1", args[0]};
            } else if (args.length > 1) {

                args = new String[]{args[0], args[1]};
            } else {

                args = new String[]{"-1", "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("[DynamicsTaskMain]统计时间段[" + dateFrom + " 00:00:00]TO[" + dateTo + " 23:59:59]");

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            final String modified = sdf.format(new Date());
            System.out.println("[DynamicsTaskMain][修改时间]" + modified);

            boolean dailyFlag = false;
            Calendar calendar = Calendar.getInstance();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            // 晚上10点半同步一份原始的计划数据
            int hourValue = 22;
            int minuteValueL = 30;
            int minuteValueM = 45;
            if (hour == hourValue && minute >= minuteValueL && minute < minuteValueM) {

                dailyFlag = true;
            }
            startFlightDynamicsTask(start, days, dailyFlag, modified);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            HCFetcher.getInstance().shutdown();
            long endTime = System.nanoTime();
            long duration = endTime - startTime;
            System.out.println("[DynamicsTaskMain]结束[" + DateUtil.dateToStr(new Date(), DateUtil.TIMEF_FORMAT) + "]");
            System.out.println("执行总共用时：" + duration + "纳秒");
            System.out.println("执行总共用时格式化：" + DateUtil.getDurationTime(duration));
            HistoryConfig.put(key, "0");
            HistoryConfig.saveHistory();
        }
    }

    private static void startFlightDynamicsTask(final int start, final int end, final boolean dailyFlag, final String modified) {
        /**
         * 航班动态
         */
        FlightDynamicsTask flightDynamicsTask = new FlightDynamicsTask(new TaskSupporter() {

            private Map<String, String> flightDates = new HashMap<String, String>(3);
            private FlightDynamicsService flightDynamicsService = new FlightDynamicsService();

            @Override
            public String setBaseUrl(TaskTemplate taskTemplate) {

                return GConstants.FOC_FLIGHT_DYNAMIC_URL + "&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("stdStart", DateUtil.dateToStr(DateUtil.offsetDate(new Date(), start), DateUtil.DATE_FORMAT) + " 00:00:00");
                params.put("stdEnd", DateUtil.dateToStr(DateUtil.offsetDate(new Date(), end), DateUtil.DATE_FORMAT) + " 23:59:59");

                return params;
            }

            @Override
            public void successHandle(JSONObject result) {


                flightDynamicsService.insertFlightDynamicsData(result, modified, dailyFlag, flightDates);
            }

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

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

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

            @Override
            public String getApiName() {

                return "dynamics";
            }

            @Override
            public boolean finish() {
                // TODO Auto-generated method stub
                flightDynamicsService.finish(flightDates, modified);
                return false;
            }
        });

        flightDynamicsTask.run();

    }
}
