package com.seeyon.apps.src_automatic.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.src_automatic.service.IAutomaticService;
import com.seeyon.apps.src_automatic.util.MoblieMsgUtil;
import com.seeyon.ctp.common.AppContext;
//import com.seeyon.apps.src_automatic.task.PushAuCardTask;
//import com.seeyon.apps.src_bill_detail.manager.PushZcService;
import com.seeyon.ctp.common.quartz.QuartzHolder;
import com.seeyon.ctp.common.quartz.QuartzJob;
import com.seeyon.ctp.util.SDFCoder;
import com.seeyon.ctp.util.UUIDLong;
import com.seeyon.ctp.util.json.JSONUtil;

/**
 * 自动计算任务
 */
public class AutomaticTask implements QuartzJob {

    /** 日志管理器 */
    private final static Log log = LogFactory.getLog(AutomaticTask.class);

    /** 定义的任务插件ID */
//    private static String jobBeanId="pushCardTask";
    
    /** 定义的任务名称 */
//    public static String jobName="QuartzPushCardTask";
    
    /** 定义的任务插件ID */
    private static String jobBeanId="automaticTask";
    
    /** 定义的任务名称 */
    public static String jobName="QuartzAutomaticTask";
    
//    private PushZcService pushZcService;
    
    private volatile boolean running;
    
private IAutomaticService automaticService;
	
	public IAutomaticService getAutomaticService() {
		if (automaticService == null) {
			automaticService = (IAutomaticService) AppContext.getBean("automaticService");
		}
		return automaticService;
	}

	public void setAutomaticService(IAutomaticService automaticService) {
		this.automaticService = automaticService;
	}

    /**
     * {@inheritDoc}
     */
    @Override
    public void execute(Map<String, String> parameters) {
    	if(running) {
    		log.info("上次推送还在执行中，跳过本次数据推送");
    		return;
    	}
    	try {
    		SimpleDateFormat sdfTest = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:sss");
    		System.out.println(sdfTest.format(new Date()));
    		this.running = true;
    			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    			Date date = new Date();
    			String dateStr = sdf.format(date);
//    			获取需要发送短信的主表id
    			List<Map<String,Object>> datas = automaticService.getSendNote(dateStr);
    			for (Map<String,Object> maps : datas) {
//    				根据主表id获取需要发送的短信数据
    				List<Map<String,Object>> lists= automaticService.getSendNotes(maps.get("id").toString());
    				int succeed = 0;
    				int defeated = 0;
//    				int i = 1 ; 
    				for (Map<String,Object> map : lists) {
//    					System.out.println("给"+map.get("recipient")+"发短信，电话号码是："+map.get("phone")+"，需要发送的类容：“"+map.get("content")+"”");
    					if(map.get("phone")!=null) {
    						String[] phones = map.get("phone").toString().split(",");
    						int defeatedNum = 0;
//    						去除手机号重复
    						List<String> list = new ArrayList<String>();
    						for (int i = 0; i < phones.length; i++) {
    						   if (!list.contains(phones[i])) {
    						       list.add(phones[i]);
    						   }
    						}
    						phones = list.toArray(new String[list.size()]);
    						for (String phone : phones) {
    							if(phone.length()>0) {
//    								调用发送短信
    								String res = MoblieMsgUtil.sendMsg(phone, UUIDLong.longUUID() + "", map.get("content").toString());
    								JSONObject json = JSONUtil.parseJSONString(res, JSONObject.class);
//    								处理返回值
    								int codeint = json.getIntValue("result");
    								if(codeint == 0) {
//    									发送成功
    									succeed++;
    									if(defeatedNum<0) {
    										automaticService.updateNotes(codeint+"", null, map.get("id").toString());
    									}
//    									sb.append("短信发送成功:" + map.get("phone").toString() + ",");
    								} else {
//    									发送失败
    									defeated++;defeatedNum++;
    									automaticService.updateNotes(codeint+"", json.getString("desc"), map.get("id").toString());
//    									sb.append(json.getString("desc") + ",");
    								}
    							}
    						}
    					}
    				}
    				String content;
    				if(defeated==0){
    					content = "总共发送短信"+succeed+"条，成功"+succeed+"条。";
    				}else {
    					content = "总共发送短信"+(succeed+defeated)+"条，成功"+succeed+"条，失败"+defeated+"条，失败原因请查看日消息通知列表";
    				}
    				if(maps.get("field0002")!=null) {
    					automaticService.sendMsg(content, Long.valueOf(maps.get("field0002").toString()));
    				}
    			}
//    		pushZcService.calcBudget(false);
    	} catch(Exception e) {
    		log.error("循环发送短信发生异常：", e);
    	} finally {
    		this.running = false;
    	}
    }
    
	 /**
	 * interval 如果是true，则是间隔执行
     */
    public static void registerSyncTask(boolean interval, int our, int minute) {
//    	jobBeanId = "pushCardTask";
//    	jobName = "QuartzPushCardTask";
    	jobBeanId = "automaticTask";
    	jobName = "QuartzAutomaticTask";
    	log.info("注册预算定时计算任务" + jobName + "...");
		try {
			// 先删除任务
			QuartzHolder.deleteQuartzJob(jobName);
			// 设定时间 每天同步的
			// if ("aa".length() > 5) {
			if(interval) {
				int delta = (our * 60 + minute) * 60 * 1000;
            	Map<String, String> parameters = new HashMap<String, String>();
                QuartzHolder.newQuartzJob(jobName, new Date(), delta, jobBeanId, parameters);
			} else {
				Map<String, String> parameters = new HashMap<String, String>();
				// 设置时间
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date()); // 年月日 也可以具体到时分秒如calendar.set(2015, 10, 12,11,32,52);
				// 每日运行，只要改动 时间即可
				calendar.set(Calendar.HOUR_OF_DAY, our);
				calendar.set(Calendar.MINUTE, minute);
				calendar.set(Calendar.SECOND, 00);
				Date date = calendar.getTime();// date就是你需要的时间
				QuartzHolder.newQuartzJobPerDay(null, jobName, date, jobBeanId, parameters);
				log.info("注册短信推送定时计算任务" + jobName + ",成功");
			}
		} catch (Exception e) {
			log.error("注册预算定时计算任务失败", e);
		}
    }
    
//	public void setPushZcService(PushZcService pushZcService) {
//		this.pushZcService = pushZcService;
//	}
}
