package com.sys.bus.sys.task;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.cron4j.ITask;
import com.sys.bus.model.SysCode;
import com.sys.bus.model.LarkMsg;
import com.sys.bus.sys.model.DtBean;
import com.sys.bus.sys.lark.LarkUtil;
import com.sys.bus.syscode.service.SysCodeService;
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 LarkMsgTask implements ITask {
	Log log = LogFactory.getLog(this.getClass());
	static boolean flag = false;//防重复调用
	static String larkMsgTo = PropKit.get("larkMsgTo");
	static boolean devDebug = "true".equals(PropKit.get("devDebug"));
	static SysCodeService codeService = new SysCodeService();
	//static int checkMinute = 1;//检查重复消息间隔分钟数
	public void run() {
		if(!flag){
			log.info("进入 LarkMsgTask 。。。。开始发飞书消息");
			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 larkappid =  null;
			String larksecret =  null;
			String token = null;
			try {
				String sql = "SELECT * FROM ct_jx_larkmsg WHERE LARKMSG_RETRY < 5 and LARKMSG_CREATETIME> '"+sendTime+"'and (LARKMSG_STATUS is null or LARKMSG_STATUS='2')";
				List<LarkMsg> list = LarkMsg.dao.find(sql);
                if(list.size() ==0){
                	return;
				}
//				SysCode larkMinute = codeService.getSysCodeName("飞书重复消息间隔分钟数");
//                try{
//					if(larkMinute!= null){
//						checkMinute = Integer.parseInt(larkMinute.getSyscodeValue());
//					}
//                }catch (Exception e){
//                }

				larkappid = codeService.getSysCodeName("飞书appid").getSyscodeValue();
                larksecret = codeService.getSysCodeName("飞书secret").getSyscodeValue();
				 if(StringUtils.isBlank(larkappid) ||StringUtils.isBlank(larksecret)){
					 log.error("飞书配置不完整！退出飞书消息任务！");
					 return;
				 }
				 token = LarkUtil.getToken(larkappid, larksecret);
				if(StringUtils.isBlank(token)){
					return;
				}
				log.info("开始发送飞书。。。。 共计："+list.size());
				List<String> pidMsgs = new ArrayList<>();
				for(LarkMsg larkMsg:list){
					String status = "1";
					try {
						    String larkUserId = larkMsg.getLarkmsgTo();
						    String pid = larkMsg.getLarkmsgTopid();
						    String msg = larkMsg.getLarkmsgText();
							String pidMsg = pid + msg;
							if(pidMsgs.contains(pidMsg)){
								//重复消息不发送
							}else{
								if(devDebug && StringUtils.isNotBlank(larkMsgTo)){
									larkUserId = larkMsgTo;
								}else if(StringUtils.isBlank(larkUserId)){
									larkUserId = this.getLarkUserId(pid);
								}
								larkMsg.setLarkmsgTo(larkUserId);
								if(StringUtils.isNotBlank(larkUserId)){
									boolean success = this.sendMsg(larkUserId, msg,token);
									if(!success){
										status = "2";
									}else{
										pidMsgs.add(pidMsg);
									}
								}else{
									status = "2";
								}
							}

					} catch (Exception e) {
						log.error("飞书消息发送失败>"+larkMsg.getLarkmsgTo(),e);
						status = "2";
					}
					larkMsg.setLarkmsgRetry(larkMsg.getLarkmsgRetry()+1);
					larkMsg.setLarkmsgSendtime(currTime);
					larkMsg.setLarkmsgStatus(status);
					larkMsg.update();

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

		}else{
			log.error("飞书消息Task 任务进行中。。。。本次跳出任务");
		}
	}
	public boolean sendMsg(String larkUserId,String msg,String token){
		try{
			return LarkUtil.sendMsg(larkUserId, msg,token,60);
		}catch (Exception e){
			log.error("飞书消息发送失败",e);
			return false;
		}
	}

	/**
	 * 获取人员的飞书id
	 * @param pid
	 * @return
	 */
	public String getLarkUserId(String pid){
		DtBean person = new DtBean().dao().findFirst("select LARKPERSON_ID from  ct_jx_larkperson where LARKPERSON_PID =?", pid);
		if(person == null)return null;
		return person.getStr("LARKPERSON_ID");
	}
	public void stop() {
		log.info("------LarkMsgTask stop-------------");
	}

}
