package com.sys.bus.sys.task;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.cron4j.ITask;
import com.jfplugin.mail.MailKit;
import com.sys.bus.model.Email;
import com.sys.bus.model.SysCode;
import com.sys.bus.model.WxMsg;
import com.sys.bus.model.WxPerson;
import com.sys.bus.sys.model.DtBean;
import com.sys.bus.sys.wx.WxUtil;
import com.sys.bus.syscode.service.SysCodeService;
import com.sys.core.utils.Tool;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class WxMsgTask implements ITask {
	Log log = LogFactory.getLog(this.getClass());
	static boolean flag = false;//防重复调用
	static String wxMsgTo = PropKit.get("wxMsgTo");
	static boolean devDebug = "true".equals(PropKit.get("devDebug"));
	static SysCodeService codeService = new SysCodeService();
	static int checkMinute = 1;//检查重复消息间隔分钟数
	public void run() {
		if(!flag){
			log.info("进入 WxMsgTask 。。。。开始发微信消息");
			flag = true;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Calendar calendar = Calendar.getInstance();
			String currTime = sdf.format(calendar.getTime());
			calendar.add(Calendar.MINUTE,-30);
			String sendTime = sdf.format(calendar.getTime());
			String wxcorpid =  null;
			String wxsecret =  null;
			String wxagentid =  null;
			String token = null;
			try {
				String sql = "SELECT * FROM ct_jx_wxmsg WHERE WXMSG_RETRY < 5 and WXMSG_CREATETIME> '"+sendTime+"'and (WXMSG_STATUS is null or WXMSG_STATUS='2')";
				List<WxMsg> list = WxMsg.dao.find(sql);
                if(list.size() ==0){
                	return;
				}
				SysCode wxMinute = codeService.getSysCodeName("微信重复消息间隔分钟数");
                try{
					if(wxMinute!= null){
						checkMinute = Integer.parseInt(wxMinute.getSyscodeValue());
					}
                }catch (Exception e){
                }

				wxcorpid = codeService.getSysCodeName("wxcorpid").getSyscodeValue();
				 wxsecret = codeService.getSysCodeName("wxsecret").getSyscodeValue();
				 wxagentid = codeService.getSysCodeName("wxagentid").getSyscodeValue();
				 if(StringUtils.isBlank(wxcorpid) ||StringUtils.isBlank(wxsecret)||StringUtils.isBlank(wxagentid)){
					 log.error("微信配置不完整！退出微信消息任务！");
					 return;
				 }
				 token = WxUtil.getToken(wxcorpid, wxsecret);
				if(StringUtils.isBlank(token)){
					return;
				}
				int wxAgentId = Integer.valueOf(wxagentid);
				log.info("开始发送微信。。。。 共计："+list.size());
				for(WxMsg wxMsg:list){
					String status = "1";
					try {
						    String wxUserId = wxMsg.getWxmsgTo();
						    String pid = wxMsg.getWxmsgTopid();
						    String msg = wxMsg.getWxmsgText();

						    if(devDebug && StringUtils.isNotBlank(wxMsgTo)){
								wxUserId = wxMsgTo;
							}else if(StringUtils.isBlank(wxUserId)){
								wxUserId = this.getWxUserId(pid);
							}
							wxMsg.setWxmsgTo(wxUserId);
							if(StringUtils.isNotBlank(wxUserId)){
								boolean success = this.sendMsg(wxUserId, msg,true,token,wxAgentId);
								if(!success){
									status = "2";
								}
							}else{
								status = "2";
							}


					} catch (Exception e) {
						log.error("微信消息发送失败>"+wxMsg.getWxmsgTo(),e);
						status = "2";
					}
					wxMsg.setWxmsgRetry(wxMsg.getWxmsgRetry()+1);
					wxMsg.setWxmsgSendtime(currTime);
					wxMsg.setWxmsgStatus(status);
					wxMsg.update();

				}
			} catch (Exception e) {
				log.error("微信消息发送失败>",e);
			}finally{
				flag = false;
			}

		}else{
			log.error("微信消息Task 任务进行中。。。。本次跳出任务");
		}
	}
	public boolean sendMsg(String wxUserId,String msg,boolean checkSameMsg,String token, int wxagentid){
		try{
			return WxUtil.sendMsg(wxUserId, msg,token,wxagentid,checkSameMsg?checkMinute:0);
		}catch (Exception e){
			log.error("微信消息发送失败",e);
			return false;
		}
	}
//	public String getWxUserId(String pid){
//		List<WxPerson> persons = WxPerson.dao.find("select * from ct_jx_wxperson where wxperson_pid =?",pid);
//		if(persons == null || persons.size()==0){
//			log.error("发送微信消息失败，未找到匹配的微信员工信息");
//			return null;
//		}
//		if(persons.size()>1){
//			log.error("发送微信消息失败，匹配到多个微信员工信息");
//			return null;
//		}
//		return persons.get(0).getWxPersonId();
//	}

	/**
	 * 获取人员的微信id
	 * @param pid
	 * @return
	 */
	public String getWxUserId(String pid){
		DtBean person = new DtBean().dao().findFirst("select fidnum from  t_bd_person where fid =?", pid);
		if(person == null)return null;
		return person.getStr("fidnum");
	}
	public void stop() {
		log.info("------WxMsgTask stop-------------");
	}

}
