/**
 *
 */
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.flight.assignment.FlightAssignmentService;
import com.foc.flight.assignment.FlightAssignmentTask;
import com.foc.util.DateUtil;
import com.foc.util.IdWorker;
import com.foc.version.VersionService;

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;

/**
 * # 同步飞行计划书数据
 * *#3  4-23  *  *  * root bash /mnt/foc/project/task/runassigment.sh
 * 导出文件名称：jd-task-assigment-2.0.jar
 *
 * @author renmb
 * @version 1.0
 * @team IT Team
 * @time 2016年11月28日
 */
public class FlightAssignmentTaskMain {
    public static void main(String[] args) {
        final String key = "assignment.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("[FlightAssignmentTaskMain]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        if (HistoryConfig.getInt(allTaskKey, 0) == 1) {
            System.out.println("[FlightAssignmentTaskMain][ALL]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        if (HistoryConfig.getInt(dailyTaskKey, 0) == 1) {
            System.out.println("[FlightAssignmentTaskMain][DAILY]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        HistoryConfig.put("assignment.task.last.time", DateUtil.getDateTime());
        HistoryConfig.put(key, "1");
        HistoryConfig.saveHistory();
        long startTime = System.nanoTime();

        //args = new String[]{"0", "0"};
        // 一个参数： 参数为向后加几天
        // 两个参数： 第一个参数为向前减减几天，第二个参数向后加几天
        int argsLengthValue = 2;
        if (args == null || args.length != argsLengthValue) {
            args = new String[]{"0", "0"};
        }
        // 开始日期位移天数
        final int start = Integer.valueOf(args[0]);
        // 结束日期位移天数
        final int days = Integer.valueOf(args[1]);

        // TODO Auto-generated method stub
        final ExecutorService threadPool = Executors.newCachedThreadPool();
        final VersionService versionService = new VersionService();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String modified = sdf.format(new Date());
        System.out.println("[OdsTaskMain][修改时间]" + modified);
        // 5.3 航班动态接口
        threadPool.execute(new Runnable() {

            @Override
            public void run() {

                for (int i = start; i <= days; i++) {

                    String dateFrom = DateUtil.dateToStr(DateUtil.offsetDate(new Date(), i), DateUtil.DATE_FORMAT);
                    System.out.println("[FlightSssignmentTaskMain]航班日期[" + dateFrom + "]");
                    final String currentVersion = IdWorker.getNextId("V");
                    // 当前使用版本
                    final String lastVersion = versionService.getCurrentVersion("ASSIGNMENT", dateFrom);
                    System.out.println("[FlightSssignmentTaskMain]FROM VERSION[" + lastVersion + "]TO[" + currentVersion + "]");

                    startFlightAssignmentTask(threadPool, lastVersion, currentVersion, 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("[FlightAssignmentTaskMain]结束[" + 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 startFlightAssignmentTask(ExecutorService threadPool,
                                                  final String lastVersion, final String currentVersion, final int offset, final String modified) {
        /**
         * 航班动态
         */
        FlightAssignmentTask flightDynamicsTask = new FlightAssignmentTask(new TaskSupporter() {

            final FlightAssignmentService service = new FlightAssignmentService();
            final String flightDate = DateUtil.dateToStr(DateUtil.offsetDate(new Date(), offset), DateUtil.DATE_FORMAT);
            private boolean hasNewData = false;

            @Override
            public String setBaseUrl(TaskTemplate taskTemplate) {

                return GConstants.FOC_FLIGHT_ASSIGNMENT_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("flightDate", flightDate);
                return params;
            }

            @Override
            public void successHandle(JSONObject result) {
                boolean ret = service.handle(currentVersion, flightDate, result, modified);
                if (!hasNewData && ret) {
                    hasNewData = true;
                }
            }

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

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

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

            @Override
            public String getApiName() {

                return "assignment";
            }

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

                if (hasNewData) {

                    System.out.println("【finish】本次有新数据，需要删除老数据!");
                    service.finish(flightDate, lastVersion, currentVersion);
                } else {

                    System.out.println("【finish】本次未获取到新数据，古不做处理！");
                }

                return false;
            }
        });

        flightDynamicsTask.run();
    }
}
