package com.chinacreator.process.job;

import com.chinacreator.process.dao.WotvAiqyDao;
import com.chinacreator.process.util.DesUtil;
import com.chinacreator.process.util.SHAUtil;
import com.chinacreator.process.util.URLUtil;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class WotvAiqyJob {

	private static Logger logger = Logger.getLogger(WotvAiqyJob.class);
	
	@Autowired
	private WotvAiqyDao dao;
	
//	public String useridstr ="18672981516,15611520384,15611112361,15510291698";
	//public String useridstr ="18672981516,18673197465";
    public String useridstr ="18673197465,17673136322";
	public void doProcess() throws Exception {
		logger.info(">>>>>>>>>>>定时任务开始<<<<<<<<<<");
		
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_MONTH, -1);
		
		String logdate = new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
		if(dao.querySMS(logdate)>0) {
			logger.info(">>>>>>已经处理。");
			return;
		}
		
		int count = dao.queryData();
		if(count<=0) {
			logger.info(">>>>>>没有新增收货地址，不需要发送短信。");
			dao.insert(logdate, "无需短信提醒", "1");
			return;
		}
		
		String [] userids = useridstr.split(",");
		if(userids== null || userids.length<=0 || "".equals(useridstr.trim())) {
			//String [] useridsMR = {"18672981516","15611520384"};
			String [] useridsMR = {"18673197465","17673136322"};
			userids = useridsMR;
		}
		
		String content=new SimpleDateFormat("yyyy年MM月dd日").format(cal.getTime())+"有新增收货地址，详情登录后台查看。需及时处理。";
		if(userids.length>0) {
			for(String userid:userids) {
				String resp = null;
				try {
					resp = sendSMS(userid, content);
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					logger.info(userid +"," + content + ","+resp);
				}
			}
		}
		
		dao.insert(logdate, Arrays.toString(userids), "0");
		
	}
	
	
    private static String sendSMS (String userid,String content){
		try {
			String smsid="1907120";
			String key= "wd9sjdh2";
			
			String timestamp = System.currentTimeMillis()/1000+"";
			String usermob =  DesUtil.encode(userid,  key);
			String sign = SHAUtil.shaEncode(smsid+usermob+timestamp+content+key).toLowerCase();
			
			usermob = URLEncoder.encode(usermob,"utf-8");
			content = URLEncoder.encode(content,"utf-8");
			String url = "http://111.206.133.54/smsbusi/sms/send?userid="+usermob+"&smsid="+smsid+"&timestamp="+timestamp+"&sign="+sign+"&content="+content;
			String resp = URLUtil.get(url);
			
			System.out.println(url+","+resp);
			return resp;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
}


	

