package com.yccrc.kede.service.impl;

import com.yccrc.common.core.domain.entity.SysUser;
import com.yccrc.kede.domain.Enterprise;
import com.yccrc.kede.domain.Project;
import com.yccrc.kede.enums.UserTypeEnum;
import com.yccrc.kede.service.IEnterpriseService;
import com.yccrc.kede.service.INotifyService;
import com.yccrc.kede.service.IProjectService;
import com.yccrc.kede.vo.EnterpriseAuthVO;
import com.yccrc.kede.vo.ProjectAddVO;
import com.yccrc.system.domain.SysNotice;
import com.yccrc.system.service.ISysNoticeService;
import com.yccrc.system.service.ISysUserService;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ReUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
@Slf4j
public class NotifyServiceImpl implements INotifyService {
	
	@Autowired
	ISysNoticeService sysNoticeService;
	
	@Autowired
	IEnterpriseService enterpriseService;
	
	@Autowired
	ISysUserService userService;
	
	@Autowired
	IProjectService projectService;
	
	@Value("${notify.emailHost}")
	private String emailHost;
	
	@Value("${notify.emailPort}")
	private Integer emailPort;
	
	@Value("${notify.sendEmail}")
	private String sendEmail;
	
	@Value("${notify.sendPwd}")
	private String sendPwd;

	@Override
	public void sendMsg(Long userId, String title, String content) {
		SysUser user = userService.getById(userId);
		
		if(user!=null) {
			log.info("给用户{},对应邮箱[{}]发送信息提醒。",user.getUserName(),user.getEmail());
			SysNotice notice = new SysNotice();
			notice.setNoticeType("1");
			notice.setNoticeTitle(title);
			notice.setNoticeContent(content);
			notice.setStatus("0");
			notice.setUserId(userId);
			sysNoticeService.save(notice);
			
			if(ReUtil.isMatch("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$"  , user.getEmail())) {
				 
				//异步执行
				  new Thread(() -> {
					  // 发送器
					  JavaMailSenderImpl sender = new JavaMailSenderImpl();
					  sender.setHost(emailHost);
					  sender.setPort(emailPort); // 默认就是25
					  sender.setUsername(sendEmail); 
					  sender.setPassword(sendPwd);
					   
					  SimpleMailMessage mail = new SimpleMailMessage();
					  mail.setTo(user.getEmail()); // 发送给谁
					  mail.setSubject(title); // 标题
					  mail.setFrom(sendEmail); // 来自
					  mail.setText(content); // 邮件内容
					  sender.send(mail); // 发送
				    }).start();
			}
		}
		
	}

	@Override
	public void authEnterpriseMsg(EnterpriseAuthVO authEnt) {
		SysUser user = userService.lambdaQuery().eq(SysUser::getScopeId, authEnt.getId()+"").eq(SysUser::getUserType, UserTypeEnum.ENT_ADMIN).one();
		if(user!=null) {
			String title = "入驻审核通知";
			String content = "您好，您注册的科德科研系统已审核通过，您可登录系统办理业务.";
			if(authEnt.getAuthState()==3) {
				content = "您好，您注册的科德科研系统已被驳回，请修改资料后重新提交.";
			}
			this.sendMsg(user.getUserId(), title, content);
		}
	}

	@Override
	public void asignProjectMsg(ProjectAddVO project) {
		String title = "项目分配通知";
		String content = "您好，您有负责的项目需要进行处理，请登录系统办理业务。";
		this.sendMsg(project.getFinUserId(), title, content);
		this.sendMsg(project.getTechUserId(), title, content);
	}

	@Override
	public void authProjectMsg(Integer projectId) {
		Project project = projectService.getById(projectId);
		if(project!=null) {
			List<SysUser> userList = null;
			//技术
			if(project.getProjectOwner()==2) {
				userList = userService.lambdaQuery().eq(SysUser::getUserType, UserTypeEnum.ENT_ADMIN_TECH).eq(SysUser::getScopeId, project.getEntId()).list();
			}else if(project.getProjectOwner()==3) {	//财务
				userList = userService.lambdaQuery().eq(SysUser::getUserType, UserTypeEnum.ENT_ADMIN_FIN).eq(SysUser::getScopeId, project.getEntId()).list();
			}
			if(!CollectionUtil.isEmpty(userList)) {
				String title = "项目审核";
				String content = "您好，您有项目需要审核，请登录系统办理业务。";
				for(SysUser user:userList) {
					this.sendMsg(user.getUserId(), title, content);
				}
			}
		}
	}

	@Override
	public void authProjectFinishMsg(Integer projectId) {
		Project project = projectService.getById(projectId);
		if(project!=null) {
			String title = "审核完成";
			String content = "您好，您提项目已审核完成，请登录系统查看。";
			this.sendMsg(project.getUserId(), title, content);
		}
	}

	@Override
	public void reportProjectMsg(Integer projectId) {
		Project project = projectService.getById(projectId);
		if(project!=null) {
			String title = "提交申报";
			String content = "您好，您负责的项目已提交申报，请登录系统查看。";
			
			this.sendMsg(project.getUserId(), title, content);
			List<SysUser> userList = userService.lambdaQuery().eq(SysUser::getUserType,UserTypeEnum.ADMIN).eq(SysUser::getScopeId, project.getEntId()).list();
			for(SysUser user:userList) {
				this.sendMsg(user.getUserId(), title, content);
			}
		}
	}

	@Override
	public void expireingEnterpriseMsg(Enterprise enteprise) {
		String title = "企业即将到期";
		String content = "您好,"+enteprise.getEntName()+"企业即将到期，请进行处理。";
		List<SysUser> userList = userService.lambdaQuery().eq(SysUser::getUserType, UserTypeEnum.ADMIN).list();
		for(SysUser user:userList) {
			this.sendMsg(user.getUserId(), title, content);
		}
		
		content = "您好，您注册的科德科研系统即将到期，如有需要请联系科德处理。";
		SysUser entUser =  userService.lambdaQuery().eq(SysUser::getScopeId, enteprise.getId()+"").eq(SysUser::getUserType, UserTypeEnum.ENT_ADMIN).one();
		this.sendMsg(entUser.getUserId(), title, content);
	}

	@Override
	public void expiredEnterpriseMsg(Enterprise enterprise,boolean sendToAdmin) {
		String title = "企业即将到期";
		String content = "您好，您注册的科德科研系统已到期，如有需要请联系科德处理。";
		SysUser entUser =  userService.lambdaQuery().eq(SysUser::getScopeId, enterprise.getId()+"").eq(SysUser::getUserType, UserTypeEnum.ENT_ADMIN).one();
		this.sendMsg(entUser.getUserId(), title, content);
		if(sendToAdmin) {
			content = "您好,"+enterprise.getEntName()+"企业已到期，请进行处理。";
			List<SysUser> userList = userService.lambdaQuery().eq(SysUser::getUserType, UserTypeEnum.ADMIN).list();
			for(SysUser user:userList) {
				this.sendMsg(user.getUserId(), title, content);
			}
		}
	}
	
}
