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

import com.foc.conf.GConstants;
import com.foc.conf.HistoryConfig;
import com.foc.fetcher.HCFetcher;
import com.foc.sound.entity.SoundRecordingEntity;
import com.foc.sound.service.SoundService;
import com.foc.util.DBHelper;
import com.foc.util.DateUtil;

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

/**
 * # 每分钟同步一次安科录音记录（直接读取安科数据库） 
 * *#1  *  *  *  * root bash /mnt/foc/project/task/rundbsounds.sh
 * 导出文件名称： jd-task-db-sound-2.20.jar
 * @team BBDTEK IT Team
 * @author renmb
 * @version 1.0
 * @time  2017年9月1日
 */
public class SoundDbTaskMain {

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

            SoundService service = new SoundService();
//            args = new String[]{"1", "6000"};
            // 一个参数： 参数为向前加几分钟
            // 两个参数： 第一个参数向前加几分钟，第二个参数向后加几分钟
            if (args.length == 2) {
            	Long minId = Long.parseLong(args[0]);//service.getSoundMaxId(0L)+1;
                System.out.print("minId:["+minId+"] TO ");
                Long maxId = Long.parseLong(args[1]);//6005L;
                System.out.println("maxId:["+maxId+"]大概["+(maxId-minId+1)+"]条");
                int size = GConstants.getIntValue("page.size", 1000);
                int count = 0;
                while(minId<=maxId){
                    long endId = minId+size-1;
                    if(endId>maxId){
                        
                        endId = maxId;
                    }
                    System.out.println("id:["+minId+","+endId+"]");
                    count = startSoundTask(service, minId, endId);
                    System.out.println("id:["+minId+","+endId+"]:"+count);
                    minId = minId+size;
                }
//                service.updateSoundmaxId(minId);
            } else{
                // 获取soundMaxId出错时不应从0开始，退出本次运行即可，不影响下次同步
//                Long minId = service.getSoundMaxId(0L)+1;
                Long minId = service.getSoundMaxId(Long.MAX_VALUE - 1) + 1;
                System.out.println("minId:["+minId+"]");
                Long maxId = getMaxIdFromAnke(1L);
                System.out.println("maxId:["+maxId+"]大概["+(maxId-minId+1)+"]条");
                int size = GConstants.getIntValue("page.size", 1000);
                int count = 0;
                while(minId<=maxId){
//                    System.out.println("count:["+minId+","+(minId+size-1)+"]:");
//                    count = startSoundTask(service, minId, minId+size-1);
//                    System.out.println("count:"+count);
//                    minId = minId+size;
                    
                    long endId = minId+size-1;
                    if(endId>maxId){
                        
                        endId = maxId;
                    }
                    System.out.println("id:["+minId+","+endId+"]");
                    count = startSoundTask(service, minId, endId);
                    System.out.println("id:["+minId+","+endId+"]:"+count);
                    minId = minId+size;
                }
                
//                do{// 循环遍历整个表
//                    
//                    count = startSoundTask(service, minId, minId+size);
//                    System.out.println("count:"+count);
//                    minId = minId+size+1;
//                } while(count>=size);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            HCFetcher.getInstance().shutdown();
            long endTime = System.nanoTime();
            long duration = endTime - startTime;
            System.out.println("[SoundDbTaskMain]结束[" + 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 int startSoundTask(final SoundService service, final Long minId, final Long maxId) {

        String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
        String url =  GConstants.getValue("anke.database.url", "jdbc:microsoft:sqlserver://10.72.23.187:1433;DatabaseName=edison200");
        String username = GConstants.getValue("anke.database.username", "foctest");
        String password = GConstants.getValue("anke.database.password", "123@abc");
        String tableName = "dbo.cdr";
        
        
//        String driver = "com.mysql.jdbc.Driver";
//        String url = "jdbc:mysql://127.0.0.1:3306/edison200?useUnicode=true&characterEncoding=utf-8";
//        String username = "root";
//        String password = "";
//        String tableName = "dbocdr";
        
        Connection conn = null;
        ResultSet rs = null;
        PreparedStatement pstmt = null;
        int count = 0;
        try {
            System.out.println("[SoundTaskMain]统计ID段[" + minId + " ]TO[" + maxId + " ]大概["+(maxId-minId+1)+"]条");
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
            pstmt = conn
                    .prepareStatement("select * from "+tableName+" where id BETWEEN " + minId + " AND "+maxId+" order by id ASC");
            rs = pstmt.executeQuery();
//            List<SoundRecordingEntity> recordingEntities = new ArrayList<SoundRecordingEntity>();
            Long newMaxId = 0L;
            List<Map<String, Object>> sounds = new ArrayList<>();
            while (rs.next()) {
                SoundRecordingEntity recordingEntity = new SoundRecordingEntity();
                recordingEntity.setId(String.valueOf(rs.getInt("id")));
                recordingEntity.setCallNo(rs.getString("caller"));
                recordingEntity.setAcceptNo(rs.getString("callee"));
                recordingEntity.setBeginTime(DateUtil.stringToDate(rs.getString("stm"), "yyyy-MM-dd HH:mm:ss"));
                recordingEntity.setEndTime(DateUtil.stringToDate(rs.getString("edm"), "yyyy-MM-dd HH:mm:ss"));
                recordingEntity.setDuration(rs.getInt("elapsed"));
                String downLoadUrl = "";
                if(rs.getString("recfile")!=null && !"".equals(rs.getString("recfile"))){
                	
                	downLoadUrl = rs.getString("recfile").replace("D:\\edison_rec", "http://10.72.23.187");
                }
                recordingEntity.setDownloadUrl(downLoadUrl);
                recordingEntity.setDownloadSize(rs.getLong("filesize"));
                recordingEntity.setResult(rs.getString("callresult"));
//                recordingEntities.add(recordingEntity);
                
                Map<String, Object> row = new HashMap<>();
                row.put("id", rs.getObject("id"));
                row.put("caller", rs.getObject("caller"));
                row.put("callee", rs.getObject("callee"));
                row.put("stm", rs.getObject("stm"));
                row.put("edm", rs.getObject("edm"));
                row.put("elapsed", rs.getObject("elapsed"));
                row.put("recfile", rs.getObject("recfile"));
                row.put("filesize", rs.getObject("filesize"));
                row.put("direct", rs.getObject("direct"));
                row.put("callresult", rs.getObject("callresult"));
                
                sounds.add(row);
                
//                service.inserSoundtDataFromDb(recordingEntity);// 将数据插入主表
                service.insert(recordingEntity, "0");// 将数据保存到分表，0表示插入测试表，1表示插入正式表
                Long id = rs.getLong("id");
                if(newMaxId<id){
                    
                    newMaxId = id;
                }
                count++;
            }
            if(newMaxId>0){
                
                System.out.println("UPDATE foc_soundmax_id SET id="+newMaxId);
//              service.updateSoundmaxId(newMaxId);
                DBHelper.update("foc", "UPDATE foc_soundmax_id SET id="+newMaxId);
            }
            DBHelper.insert("foc", "dbocdr", sounds);
            return count;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
            } catch (Exception e2) {}
            try {
                pstmt.close();
            } catch (Exception e2) {}
            try {
                conn.close();
            } catch (Exception e2) {}
        }
        return 0;
    }

    
    
    private static Long getMaxIdFromAnke(final Long defaultId) {

      String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
      String url =  GConstants.getValue("anke.database.url", "jdbc:microsoft:sqlserver://10.72.23.187:1433;DatabaseName=edison200");
      String username = GConstants.getValue("anke.database.username", "foctest");
      String password = GConstants.getValue("anke.database.password", "123@abc");
      String tableName = "dbo.cdr";
      
//      
//      String driver = "com.mysql.jdbc.Driver";
//      String url = "jdbc:mysql://127.0.0.1:3306/edison200?useUnicode=true&characterEncoding=utf-8";
//      String username = "root";
//      String password = "";
//      String tableName = "dbocdr";
      
      Connection conn = null;
      ResultSet rs = null;
      PreparedStatement pstmt = null;
      try {
          Class.forName(driver);
          conn = DriverManager.getConnection(url, username, password);
          pstmt = conn
                  .prepareStatement("select MAX(id) AS maxid from "+tableName);
          rs = pstmt.executeQuery();
          while (rs.next()) {
              
              return rs.getLong("maxid");
          }
      } catch (ClassNotFoundException e) {
          e.printStackTrace();
      } catch (SQLException e) {
          e.printStackTrace();
      } finally {
          try {
              rs.close();
          } catch (Exception e2) {}
          try {
              pstmt.close();
          } catch (Exception e2) {}
          try {
              conn.close();
          } catch (Exception e2) {}
      }
      return defaultId;
  }
}
