package com.foc.task;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
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.flightdynamics.FlightDynamicsTask;
import com.foc.flightdynamics.service.FlightDynamicsService;
import com.foc.util.DateUtil;

/**
 * 每天定时同步昨天和今天的数据
 * 只同步航班动态数据
 * 
 * @team IT Team
 * @author renmb
 * @version 1.0
 * @time  2016年10月3日
 */
public class DynamicsTaskMain {

    public static void main(String[] args) {
//        Logger logger = Logger.getLogger(BefBasicArchiveMain.class);
        final String key = "dynamics.task.is.running";
        final long startTime = System.nanoTime();
        try {
            boolean isForce = false;
            if((args.length >= 3 && "F".equals((args[2])))){
                System.out.println("[DynamicsTaskMain]强制模式");
                isForce = true;
            }
            if (!isForce && HistoryConfig.getInt(key, 0) == 1) {
                System.out.println("[DynamicsTaskMain]上次程序正在运行！跳过本次运行。。。");
                return;
            }
            if (!isForce && HistoryConfig.getInt("all.task.is.running", 0) == 1) {
                System.out.println("[DynamicsTaskMain][ALL]上次程序正在运行！跳过本次运行。。。");
                return;
            }
            if (HistoryConfig.getInt("daily.task.is.running", 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"};
            }
//            args = new String[]{"2", "2"};
//            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("[DynamicsTaskMain]统计时间段["+dateFrom+" 00:00:00]TO["+dateTo+" 23:59:59]");
            
//            final Date modified = new Date();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            System.out.println("[DynamicsTaskMain][修改时间]"+sdf.format(modified));
            
            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);
            if(hour == 22 && minute >= 30 && minute < 45){// 晚上10点半同步一份原始的计划数据

                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();
        }
        /*
        // TODO Auto-generated method stub
        final ExecutorService threadPool = Executors.newCachedThreadPool();

        threadPool.execute(new Runnable() {// 5.3 航班动态接口

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

                    dailyFlag = true;
                }
                startFlightDynamicsTask(threadPool, start, days, dailyFlag, modified);
//                if(0>=start && 0<= days){// 优先同步今天的数据
//                    
//                    startFlightDynamicsTask(threadPool, 0);
//                }
//                for (int i = start; i <= days; i++) {// 航班动态 插入或更新从今天开始往后30天的数据
//                    if(i != 0){
//                        
//                        startFlightDynamicsTask(threadPool, i);
//                    }
//                }
            }
        });
        threadPool.shutdown();

        while (true) {
            if (threadPool.isTerminated()) {
                System.out.println("线程池结束了！");
                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();
                
                System.exit(0);
                break;
            }
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        */
    }
    
    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>();
            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();
        // threadPool.execute(flightDynamicsTask);

    }
}
