/**
 *
 */
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.sound.SoundTask;
import com.foc.sound.entity.SoundRecordingEntity;
import com.foc.util.DateUtil;
import com.foc.util.MapCounter;
import org.apache.http.client.utils.DateUtils;

import java.sql.*;
import java.util.*;
import java.util.Date;

/**
 * 注：已经弃用
 * <p>
 * # 每5分钟同步一次录音数据
 * *#2  1-23  *  *  *  root bash /mnt/foc/project/task/runsounds.sh
 * # 每天1点同步一次最近一天的数据
 * 10  0  *  *  * root bash /mnt/foc/project/task/runsoundsdaily.sh
 * 导出文件名称： jd-task-sounds-2.7.jar
 *
 * @author zhanglg
 * @version 1.0
 * @team IT Team
 * @time 2017年2月23日
 */

public class SoundTaskMain {
    public static void main(String[] args) {
        final String key = "sound.task.is.running";
        final String allTaskKey = "all.task.is.running";
        final String dailyTaskKey = "daily.task.is.running";
        long startTime = System.nanoTime();
        try {
            if (HistoryConfig.getInt(key, 0) == 1) {
                System.out.println("[SoundTaskMain]上次程序正在运行！跳过本次运行。。。");
                return;
            }
            if (HistoryConfig.getInt(allTaskKey, 0) == 1) {
                System.out.println("[SoundTaskMain][ALL]上次程序正在运行！跳过本次运行。。。");
                return;
            }
            if (HistoryConfig.getInt(dailyTaskKey, 0) == 1) {
                System.out.println("[SoundTaskMain][DAILY]上次程序正在运行！跳过本次运行。。。");
                return;
            }
            HistoryConfig.put("sound.task.last.time", DateUtil.getDateTime());
            HistoryConfig.put(key, "1");
            HistoryConfig.saveHistory();

            // 一个参数： 参数为向前加几分钟
            // 两个参数： 第一个参数向前加几分钟，第二个参数向后加几分钟
            int intValue1 = 1;
            int intValue2 = 2;
            if (args == null || args.length == 0 || args.length > intValue2) {

                args = new String[]{"-30", "10"};
            } else if (args.length == intValue1) {

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

                args = new String[]{args[0], args[1]};
            }
            // 开始日期位移天数
            final int start = Integer.valueOf(args[0]);
            // 结束日期位移天数
            final int days = Integer.valueOf(args[1]);

            String dateFrom = "2017-08-07 14:23:00";
            String dateTo = "2017-08-07 14:26:00";

            System.out.println("[SoundTaskMain]统计时间段[" + dateFrom + " ]TO[" + dateTo + " ]");
            startSoundTask(dateFrom, dateTo);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            HCFetcher.getInstance().shutdown();
            long endTime = System.nanoTime();
            long duration = endTime - startTime;
            System.out.println("[SoundTaskMain]结束[" + 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 startSoundTask(final String start, final String end) {
        SoundTask task = new SoundTask(new TaskSupporter() {

            @Override
            public String setBaseUrl(TaskTemplate taskTemplate) {
                // TODO Auto-generated method stub
                return GConstants.FOC_SOUND_RECORDS_URL + "?pageNo=" + taskTemplate.getPageIndex();
            }

            @Override
            public Map<String, String> setParams() {

                Map<String, String> params = new HashMap<>(3);
                params.put("pageSize", "1000");
                params.put("beginTime", start);
                params.put("endTime", end);
                return params;

            }

            @Override
            public void successHandle(JSONObject result) {
                // yes更新CALL表，NO更新sound表
                //之前获取的id
                int maxId = 0;
                String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
                String url = "jdbc:microsoft:sqlserver://10.72.23.187:1433;DatabaseName=edison200";

                try {
                    Class.forName(driver);
                    Connection conn = DriverManager.getConnection(url, "foctest", "123@abc");
                    PreparedStatement pstmt = conn.prepareStatement("select * from dbo.cdr where id>" + maxId + " order by id ASC");
                    ResultSet rs = pstmt.executeQuery();
                    List<SoundRecordingEntity> recordingEntities = new ArrayList<SoundRecordingEntity>();
                    while (rs.next()) {
                        SoundRecordingEntity recordingEntity = new SoundRecordingEntity();
                        recordingEntity.setCallNo(rs.getString("caller"));
                        recordingEntity.setAcceptNo(rs.getString("callee"));
                        recordingEntity.setBeginTime(rs.getDate("stm"));
                        recordingEntity.setEndTime(rs.getDate("edm"));
                        recordingEntity.setDuration(rs.getInt("elapsed"));
                        recordingEntity.setDownloadUrl(rs.getString("recfile"));
                        recordingEntity.setDownloadSize(rs.getLong("filesize"));
                        recordingEntity.setResult(rs.getString("callresult"));
                        recordingEntity.setChannelId(rs.getString("channelid"));
                        recordingEntities.add(recordingEntity);
                        System.out.println("id:" + rs.getInt("id")
                                + "callNo:" + rs.getString("caller")
                                + "acceptNo:" + rs.getString("callee")
                                + "beginTime:" + DateUtils.formatDate(rs.getDate("stm"), "yyyy-MM-dd HH:mm:ss")
                                + "EndTime:" + DateUtils.formatDate(rs.getDate("edm"), "yyyy-MM-dd HH:mm:ss")
                                + "Duration:" + rs.getInt("elapsed")
                                + "DownloadUrl:" + rs.getString("recfile")
                                + "DownloadSize:" + rs.getLong("filesize")
                                + "ChannelId:" + rs.getLong("channelid")
                                + "Result:" + rs.getString("callresult"));
                    }
                    rs.close();
                    pstmt.close();
                    conn.close();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public String setPageIndexProperty() {
                // TODO Auto-generated method stub
                return "foc.sound.page.index";
            }

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

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

            @Override
            public String getApiName() {
                // TODO Auto-generated method stub
                return "sound";
            }

            @Override
            public boolean finish() {
                // TODO Auto-generated method stub
                MapCounter.list(2);
                return false;
            }
        });
        task.run();
    }
}
