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

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.utils.DateUtils;

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.sound.service.SoundService;
import com.foc.util.DateUtil;
import com.foc.util.MapCounter;

/**
 * 
 * @team IT Team
 * @author zhanglg
 * @version 1.0
 * @time  2017年2月23日
 */

public class SoundTaskMain {
    public static void main(String[] args) {
        final String key = "sound.task.is.running";
        long startTime = System.nanoTime();
        try {
        if (HistoryConfig.getInt(key, 0) == 1) {
            System.out.println("[SoundTaskMain]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        if (HistoryConfig.getInt("all.task.is.running", 0) == 1) {
            System.out.println("[SoundTaskMain][ALL]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        if (HistoryConfig.getInt("daily.task.is.running", 0) == 1) {
            System.out.println("[SoundTaskMain][DAILY]上次程序正在运行！跳过本次运行。。。");
            return;
        }
        HistoryConfig.put("sound.task.last.time", DateUtil.getDateTime());
        HistoryConfig.put(key, "1");
        HistoryConfig.saveHistory();
      
        // 一个参数： 参数为向前加几分钟
        // 两个参数： 第一个参数向前加几分钟，第二个参数向后加几分钟
        if(args == null || args.length ==0 || args.length > 2){
            
            args = new String[]{"-30", "10"};
        } else if(args.length == 1){
            
            args = new String[]{ args[0], "0"};
        } else if(args.length == 2){
            
            args = new String[]{args[0], args[1]};
        }
        final int start = Integer.valueOf(args[0]);// 开始日期位移天数
        final int days = Integer.valueOf(args[1]);// 结束日期位移天数
//        String dateFrom = DateUtil.dateToStr(DateUtil.offsetMinute(new Date(), start), DateUtil.TIMEF_FORMAT);
//        String dateTo   = DateUtil.dateToStr(DateUtil.offsetMinute(new Date(), days), DateUtil.TIMEF_FORMAT);
//        
//        String dateFrom = "2017-08-04 00:00:00";//DateUtil.dateToStr(DateUtil.offsetDate(new Date(), start), DateUtil.DATE_FORMAT);
//        String dateTo   = "2017-08-04 23:59:59";DateUtil.dateToStr(DateUtil.offsetDate(new Date(), days), DateUtil.DATE_FORMAT);
//        
//        String dateFrom = DateUtil.dateToStr(DateUtil.offsetDate(new Date(), start), DateUtil.DATE_FORMAT);
//        String dateTo   = DateUtil.dateToStr(DateUtil.offsetDate(new Date(), days), DateUtil.DATE_FORMAT);
        
        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() {
          
            private  SoundService service=new SoundService();
            @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<>();
//                params.put("pageNo", taskTemplate.getPageIndex());
                params.put("pageSize","1000");
                params.put("beginTime", start);
                params.put("endTime", end);
                return params;
                
            }
            @Override
            public void successHandle(JSONObject result) {
                // yes更新CALL表，NO更新sound表
//                service.insertData(result, start, end, GConstants.getValue("call.record.to", GConstants.YES));
                int maxId = 0;//之前获取的id
                //同步数据
//                List<Integer> list= service.getSoundMaxId();
//                if(list!=null && list.size()>0){
//                	maxId = list.get(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>();
	      		 int newMaxId = 0;
	      		   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"));
		      			recordingEntities.add(recordingEntity);
		      			newMaxId = rs.getInt("id");
		      			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")
		      			+"Result:"+rs.getString("callresult"));
	      		   }
//	      		 service.insertData(recordingEntities, start, end, GConstants.getValue("call.record.to", GConstants.YES));
//	      		 service.updateSoundmaxId(newMaxId,maxId);  
	      		 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();
    }
}
