/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.syswarning.service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.sms.SMSUtils;
import com.jeeplus.common.utils.JedisUtils;
import com.jeeplus.common.utils.SendMailUtil;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysmodular.dao.SysModularDao;
import com.jeeplus.modules.sysmodular.dao.SysModularFieldDao;
import com.jeeplus.modules.sysmodular.entity.SysModular;
import com.jeeplus.modules.sysmodular.entity.SysModularField;
import com.jeeplus.modules.syswarning.dao.SysWarningLogDao;
import com.jeeplus.modules.syswarning.dao.SysWarningRoleDao;
import com.jeeplus.modules.syswarning.dao.SysWarningUserDao;
import com.jeeplus.modules.syswarning.entity.SysWarningLog;
import com.jeeplus.modules.syswarning.entity.SysWarningRole;
import com.jeeplus.modules.syswarning.entity.SysWarningUser;
import com.jeeplus.modules.workcatalogueitem.entity.WorkCatalogueItem;
import com.jeeplus.modules.workchangejob.entity.WorkChangeJob;
import com.jeeplus.modules.workchangejob.entity.WorkChangeJobUser;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import com.jeeplus.modules.workstaff.dao.WorkStaffAchivesDao;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.syswarning.entity.SysWarning;
import com.jeeplus.modules.syswarning.dao.SysWarningDao;
import redis.clients.jedis.Jedis;

/**
 * 系统预警Service
 * @author chenyuping
 * @version 2018-08-14
 */
@Service
@Transactional(readOnly = true)
public class SysWarningService extends CrudService<SysWarningDao, SysWarning> {
	@Autowired
	private SysWarningRoleDao sysWarningRoleDao;
	@Autowired
	private SysWarningUserDao sysWarningUserDao;
	@Autowired
	private SysWarningDao sysWarningDao;
	@Autowired
	private WorkStaffAchivesDao workStaffAchivesDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private SysWarningLogDao sysWarningLogDao;
    @Autowired
    private SysModularFieldDao sysModularFieldDao;
	@Autowired
	private SysModularDao sysModularDao;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;

	public SysWarning get(String id) {
		return super.get(id);
	}
	
	public List<SysWarning> findList(SysWarning sysWarning) {
		sysWarning.setCompanyId(UserUtils.getSelectCompany().getId());
		return super.findList(sysWarning);
	}
	
	public Page<SysWarning> findPage(Page<SysWarning> page, SysWarning sysWarning) {
		sysWarning.setPage(page);
		page.setList(findList(sysWarning));
		return page;
	}
	
	@Transactional(readOnly = false)
	public void save(SysWarning sysWarning) {
		String sql=sysWarning.getSqlString()
				.replaceAll("&ensp;"," ")
				.replaceAll("&emsp;"," ")
				.replaceAll("&nbsp;"," ")
				.replaceAll("&amp;"," ")
				.replaceAll("lt;","<")
				.replaceAll("gt;",">")
				.replaceAll("\'","'");
		sysWarning.setSqlString(sql);
		super.save(sysWarning);
		this.updateList(sysWarning);
	}
	@Transactional(readOnly = false)
	public void updateList(SysWarning sysWarning) {
		if(sysWarning.getSysWarningRoleList()!=null&&sysWarning.getSysWarningRoleList().size()>0){
			for (SysWarningRole sysWarningRole :sysWarning.getSysWarningRoleList()) {
				if (StringUtils.isBlank(sysWarningRole.getId()) ) {
						sysWarningRole.preInsert();
						sysWarningRole.setWarningId(sysWarning.getId());
						sysWarningRoleDao.insert(sysWarningRole);
				} else {
						sysWarningRole.preUpdate();
						sysWarningRole.setWarningId(sysWarning.getId());
						sysWarningRoleDao.update(sysWarningRole);

				}
			}
		}
		if(sysWarning.getSysWarningUserList()!=null&&sysWarning.getSysWarningUserList().size()>0){
			for (SysWarningUser sysWarningUser :sysWarning.getSysWarningUserList()) {
				if (StringUtils.isBlank(sysWarningUser.getId()) ) {
						sysWarningUser.preInsert();
						sysWarningUser.setWarningId(sysWarning.getId());
						sysWarningUserDao.insert(sysWarningUser);
				} else {
						sysWarningUser.preUpdate();
						sysWarningUser.setWarningId(sysWarning.getId());
						sysWarningUserDao.update(sysWarningUser);
				}
			}
		}
	}
	@Transactional(readOnly = false)
	public void delete(SysWarning sysWarning) {
		super.delete(sysWarning);
		if(sysWarning.getSysWarningRoleList()!=null&&sysWarning.getSysWarningRoleList().size()>0){
			for(SysWarningRole sysWarningRole:sysWarning.getSysWarningRoleList()){
				sysWarningRoleDao.delete(sysWarningRole);
			}
		}
		if(sysWarning.getSysWarningUserList()!=null&&sysWarning.getSysWarningUserList().size()>0){
			for(SysWarningUser sysWarningUser:sysWarning.getSysWarningUserList()){
				sysWarningUserDao.delete(sysWarningUser);
			}
		}
	}
	@Transactional(readOnly = false)
	public void removeFlat(SysWarning sysWarning) {
		sysWarningDao.removeFlat(sysWarning);
	}

	public  Page<WorkStaffBasicInfo> sysWarningUser(Page<WorkStaffBasicInfo> page, WorkStaffBasicInfo workStaffBasicInfo) {
		workStaffBasicInfo.setPage(page);
		page.setList(workStaffAchivesDao.sysWarningUser(workStaffBasicInfo));
		return page;
	}

	/**
	 * 系统预警
	 */

	@Transactional(readOnly = false)
	public  void startTask(){
		List<SysWarning> list =sysWarningDao.find();
		if(list!=null&&list.size()>0){
			for(SysWarning sysWarning:list){
				String title="预警类型:"+DictUtils.getDictLabel(sysWarning.getWarningType(),"warning_type","");
				String content="预警类型:"+DictUtils.getDictLabel(sysWarning.getWarningType(),"warning_type","");
				if(isSend(sysWarning)){
				//if(true){
					//String str=getSqlString(sysWarning.getRules())
					String str=sysWarning.getSqlString();
					String sql=str.replaceAll("[?]","'"+sysWarning.getScope()+"'");
					int count= sysWarningDao.getSqlString(sql);
					if(count>0){
						//通知用户
						List<User> userList=userDao.findUserByRoles(sysWarning.getId());
						userList.addAll(userDao.findUserByUser(sysWarning.getId()));
						HashSet set = new HashSet(userList);
						userList.clear();
						userList.addAll(set);
						String reminding=sysWarning.getReminding();//预警类型
						//系统通知
							if (userList!=null && userList.size()!=0) {
								for (User u : userList) {
									WorkProjectNotify notify = new WorkProjectNotify();
									notify.setNotifyId(sysWarning.getId());
									//workProjectNotifyService.readByNotifyId(notify);
									workProjectNotifyService
											.save(UtilNotify
													.saveNotifyTask(sysWarning.getId(),
															u,
															u.getCompany().getId(),
															title,
															content,
															"74",
															"0",
															"待通知",
															"系统预警通知"));
									//增加日志
									SysWarningLog sysWarningLog=new SysWarningLog();
									sysWarningLog.preInsert();
									sysWarningLog.setCompanyId(sysWarning.getCompanyId());
									sysWarningLog.setOfficeId(sysWarning.getOfficeId());
									sysWarningLog.setUserId(u.getId());
									sysWarningLog.setWarningId(sysWarning.getId());
									sysWarningLog.setWarningDate(new Date());
									sysWarningLogDao.insert(sysWarningLog);
								}
							}
							if (userList!=null && userList.size()!=0) {
								for (User u : userList) {
									UserUtils.pushIm(u.getId(),title);
								}
							}
						 if(reminding.contains("3")){//短信提醒
							this.sendWarning(userList,sysWarning);
						}
						 if(reminding.contains("2")){//邮件提醒
							if (userList!=null && userList.size()!=0) {
								for (User u : userList) {
									SendMailUtil.sendCommonMail(u.getEmail(),"【匞匞】系统预警",sysWarning.getComment());
								}
							}
						}
					}
				}
			}
		}
	}
	public static void sendWarning(List<User> userList,SysWarning sysWarning){
		HashMap<String,Object> result = null;
		if (userList!=null && userList.size()!=0) {
			for (User u : userList) {
				try{
						result = UserUtils.sendRandomCodes(u.getMobile(), sysWarning.getComment());
					    String statusCode = (String) result.get("statusCode");
						if (("000000").equals(statusCode)) {
							System.out.println("短信发送成功!");
						}else{
							System.out.println("短信发送失败!");
						}

				}catch (Exception e){
					e.printStackTrace();
					System.out.println("短信发送失败!");
				}
			}
		}

	}
	/**
	 * 判断是系统时间是否等于发送时间
	 * @param sysWarning
	 * @return
	 */
	public static Boolean isSend(SysWarning sysWarning){
		String frequency=sysWarning.getFrequency();
		Date warningDate=sysWarning.getWarningDate();
		SimpleDateFormat min = new SimpleDateFormat("hh:mm");
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Date nowDate=new Date();
		if(warningDate.getTime()>nowDate.getTime()){
             return false;
		}
		if("1".equals(frequency)){//每天发送判断每天分钟是否相等
			String warningDateString = min.format(warningDate);
			String currentTime=min.format(nowDate);
			if(warningDateString.equals(currentTime)){
				return true;
			}
		}else if("2".equals(frequency)){//每周发送
			String warningDateString = formatter.format(warningDate);
			String currentTime=formatter.format(nowDate);
			int days=differentDaysByMillisecond(warningDate,nowDate);
			if(days%7==0){
				String warningDateMin = min.format(warningDate);
				String currentMin=min.format(nowDate);
				if(warningDateMin.equals(currentMin)){
					return true;
				}else{
					return false;
				}
			}else{
				return false;
			}
		}else if("3".equals(frequency)){//每月
			String warningDateString = formatter.format(warningDate);
			String currentTime=formatter.format(nowDate);
			int days=differentDaysByMillisecond(warningDate,nowDate);
			if(days%30==0){
				String warningDateMin = min.format(warningDate);
				String currentMin=min.format(nowDate);
				if(warningDateMin.equals(currentMin)){
					return true;
				}else{
					return false;
				}
			}else{
				return false;
			}
		}
		return false;
	}
	public static int differentDaysByMillisecond(Date date1,Date date2) {
		int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
		return days;
	}
	@Transactional(readOnly = false)
	public int getSqlString(String sqlString){
		String sql=sqlString
				.replaceAll("&ensp;"," ")
				.replaceAll("&emsp;"," ")
				.replaceAll("&nbsp;"," ")
				.replaceAll("&amp;"," ")
				.replaceAll("&lt;","<")
				.replaceAll("&gt;",">")
				.replaceAll("\'","'");
	int count=dao.getSqlString(sql);
		return count;
	}
	public static void main(String args[]) {
		SendMailUtil.sendCommonMail("370326586@qq.com","【匞匞】系统预警","逗你玩？");
		/*String dateStr = "15:48";
		String dateStr2 = "2008-1-8 23:56";
		Date d=new Date();
		SimpleDateFormat format = new SimpleDateFormat("HH:mm");
		String currentTime=format.format(d);
		System.out.println(currentTime.equals(dateStr));

		SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");*/
		/*try
		{
			Date date2 = format.parse(dateStr2);
			Date date = format.parse(dateStr);
			System.out.println("两个日期的差距：" + differentDaysByMillisecond(date,date2));
			int i=differentDaysByMillisecond(date,date2);
			if(i%7==0){
				System.out.println("2222222");
			}else{
				System.out.println(i%7);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}*/
	}
	public List<SysModularField> findModularField(SysModularField modularField) {
		List<SysModularField> list=sysModularFieldDao.findList(modularField);
		return list;
	}

}