/**
 *
 */
package com.foc.task;

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;

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;

/**
 * 
 * @team IT Team
 * @author renmb
 * @version 1.0
 * @time 2016年11月28日
 */
public class FlightAssignmentTaskMain {
    public static void main(String[] args) {
//        String[] ids = "PN6345/PN6346".split("/");
//        for (String flightNo:ids) {
//            System.out.println("flightNo:"+flightNo);
//        }
//        System.exit(0);
        // Logger logger = Logger.getLogger(BefBasicArchiveMain.class);
        final String key = "assignment.task.is.running";
        if (HistoryConfig.getInt(key, 0) == 1) {
            System.out.println("[FlightSssignmentTaskMain]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        if (HistoryConfig.getInt("all.task.is.running", 0) == 1) {
            System.out.println("[FlightSssignmentTaskMain][ALL]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        if (HistoryConfig.getInt("daily.task.is.running", 0) == 1) {
            System.out.println("[FlightSssignmentTaskMain][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"};
        // 一个参数： 参数为向后加几天
        // 两个参数： 第一个参数为向前减减几天，第二个参数向后加几天
        if (args == null || args.length != 2) {
            
            args = new String[] { "0", "0" };
        }
        final int start = Integer.valueOf(args[0]);// 开始日期位移天数
        final int days = Integer.valueOf(args[1]);// 结束日期位移天数
//        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);
        
        threadPool.execute(new Runnable() {// 5.3 航班动态接口

            @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);//HistoryConfig.getValue("assignment.current.use.version", "");// 当前使用版本
                    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("[FlightSssignmentTaskMain]结束[" + 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>();
                //departStation=CTU&arrivalStation=SYX&flightNos=JD5178
                params.put("flightDate", flightDate);
//                params.put("departStation", "CTU");
//                params.put("flightDate", "2016-09-22");
//                params.put("arrivalStation", "SYX");
//                params.put("flightNos", "JD5178");
                
                return params;
            }

            @Override
            public void successHandle(JSONObject result) {
//                String flightDate = flightDate;
                
                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();
    }
}
