package com.goafanti.common.task;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.mail.SendFailedException;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.goafanti.admin.service.AdminService;
import com.goafanti.common.bo.EmailBo;
import com.goafanti.common.dao.NoticeMapper;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.enums.PatentCategoryStatus;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.Notice;
import com.goafanti.common.model.PatentNew;
import com.goafanti.common.model.PatentNewLog;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.common.utils.SendEmailUtil;
import com.goafanti.patent.service.PatentNewService;




@Component
@RestController
public class PatentTask {
	@Resource
	private PatentNewService patentNewService;
	@Resource
	private AdminService adminService;
	@Autowired
	private NoticeMapper	noticeMapper;
	
	
	
	
	

	int pointsDataLimit=50;
    
    private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
    private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
    private static final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
    private static final String regEx_space = "\\s*|\t|\r|\n";//定义空格回车换行符
	

	
	
	
	@Scheduled(cron = "0 0 0  * * ?") 
	@RequestMapping(value = "/open/patentRemind", method = RequestMethod.GET)
	public void patentRemind() {
		LoggerUtils.debug(getClass(), "====================开始检查专利提醒==================");
		try {
		List<PatentNew> l=patentNewService.AllselectStartPatentNew();
		List<Notice> nlist=new  ArrayList<>();
		for (PatentNew p : l) {
			 Calendar cst =Calendar.getInstance();
			 Calendar ced =Calendar.getInstance();
			 Calendar ted =Calendar.getInstance();
			 cst.setTime(p.getApplyDate());
			 ced.setTime(new Date());
			 //获得累计年限   
			 int d = (int) ((ced.getTimeInMillis()-cst.getTimeInMillis()) / (1000*3600*24));
			 int y=d/365;
			 if(d%365>0)y++;
			 ted.setTime(cst.getTime());
			 ted.add(Calendar.YEAR,y);
			 //计算相差日期
			 int count = (int) ((ted.getTimeInMillis()-ced.getTimeInMillis()) / (1000*3600*24));
			 Notice n =new Notice();
			 n.setId(UUID.randomUUID().toString());
			 n.setCreateTime(new Date());
			 n.setReaded(0);//未读
			 n.setAid("1");
			 n.setNoticeType(NoticeStatus.TASK_PATENT_ERROR.getCode());
			 if (count>=0&&count<=90) {
					 Admin a=adminService.selectByPrimaryKey(p.getAid());
					 //设置如果找不到用户则提醒管理员
					 String str2="专利编号="+p.getPatentNo()+"名称="+p.getName()+",email="+p.getEmail();;
					 n.setContent(str2);
					 if(a==null) {
						n.setContent(str2+",aid="+p.getAid());
						nlist.add(n);
							continue;
					 }else if (!SendEmailUtil.isEmail(p.getEmail().trim())) {
						n.setContent(str2+",管理员="+a.getName());
						nlist.add(n);
						//再发一条给管理员
						Notice n2 =new Notice();
						n2.setId(UUID.randomUUID().toString());
						n2.setCreateTime(new Date());
						n2.setReaded(0);//未读
						n2.setContent(str2);
						n2.setNoticeType(NoticeStatus.TASK_PATENT_ERROR.getCode());
						n2.setAid(a.getId());
						nlist.add(n2);
							continue;
					}else {
						 //计算出年费金额，然后存入数据库
						 BigDecimal money=countMoney(y,p.getType());
						ted.setTime(cst.getTime());
						ted.add(Calendar.YEAR, y);
						EmailBo emailBo = new EmailBo("专利提醒",p.getEmail().trim(), p.getApplicant(), "科德集团", a.getName(),p.getName(), p.getPatentNo(), money.toString(), DateFormatUtils.format(ted, "yyyy-MM-dd"));
						 n.setNoticeType(NoticeStatus.TASK_PATENT_REMIND.getCode());
						 String title="专利提醒";
						 p.setStatus(1);//提醒中
						try {
							SendEmailUtil.getInstance().patentSend(emailBo);
						} catch (SendFailedException e) {
							//如果邮件发送失败提醒
							 n.setNoticeType(NoticeStatus.TASK_PATENT_ERROR.getCode());
							 title="专利提醒失败！对方邮箱不存在或者拒收";
							 p.setStatus(0);
						}
						 p.setPatentAmount(money);
						 p.setYears(y);
						 patentNewService.updatePatenNew(p);
						 PatentNewLog pl=new PatentNewLog();
						 String str=StrToString(title,p.getEmail().trim(), p.getApplicant(), a.getName(),p.getName(), p.getPatentNo(),
								 money.toString(), DateFormatUtils.format(ted, "yyyy-MM-dd"));
						 pl.setContent(str);
						 pl.setCreateTime(new Date());
						 pl.setPid(p.getId());
						 patentNewService.addPatenNewLog(pl);
						 n.setAid(p.getAid());
						 n.setContent(str);
						 nlist.add(n);
					}
					
					 Thread.sleep(2000);
				}
		}
		if (!nlist.isEmpty()) {
			List<Notice> newList=new  ArrayList<>();
				  for(int i=0;i<nlist.size();i++){
					  newList.add(nlist.get(i));
					  if(pointsDataLimit == newList.size()||i == nlist.size()-1){
						  if(newList.size()>0) noticeMapper.insertBatch(newList);	
						  newList.clear();
						  Thread.sleep(2000);
					  }  
			}
		}
		List<PatentNew> ls=patentNewService.AllselectEndPatentNew();
		for (PatentNew p : ls) {
			Calendar cst =Calendar.getInstance();
			Calendar ced =Calendar.getInstance();
			Calendar ted =Calendar.getInstance();
			cst.setTime(p.getApplyDate());
			ced.setTime(new Date());
			int d = (int) ((ced.getTimeInMillis()-cst.getTimeInMillis()) / (1000*3600*24));
			int y=(d/365);
			if(d%365>0)y++;
			ted.setTime(cst.getTime());
			ted.add(Calendar.YEAR,y);
			//计算相差日期
			int count = (int) ((ted.getTimeInMillis()-ced.getTimeInMillis()) / (1000*3600*24));
			if (count>200) {
			p.setStatus(0);//恢复待提醒
			patentNewService.updatePatenNew(p);
			 }
		}
		} catch (Exception e) {
			LoggerUtils.debug(getClass(), "=====================专利提醒失败======================");
			 Notice n =new Notice(UUID.randomUUID().toString(),new Date(),0,"1",NoticeStatus.TASK_PATENT_ERROR.getCode(),"==============专利提醒失败================");
			 noticeMapper.insert(n);
			e.printStackTrace();
		}
					 
		LoggerUtils.debug(getClass(), "=====================专利提醒结束======================");
	}
	

	private String StrToString(String name, String email, String applicant,  String adminName, String pantentName,
		String pantentNo, String money, String format) {
		StringBuilder str =new StringBuilder("");
		str.append(name).append(":").append("邮箱:").append(email).append(",授权公司:").append(applicant).append(",录入人:").append(adminName)
		.append(",专利名称:").append(pantentName).append (",专利编号:").append(pantentNo).append(",金额:").append(money).append(",时间:").append(format);
		return str.toString();
	
}


	/**
	 * 
	 * @param 年份
	 * @param 分类
	 * @return 金额
	 */
	
	private static BigDecimal countMoney(Integer y, Integer type) {
		int money=0;
		if (type==PatentCategoryStatus.INVENTION.getCode()) {
			if (y>0&&y<4) {
				money=900;
			}else if (y>3&&y<7) {
				money=1200;
			}else if (y>6&&y<10) {
				money=2000;
			}else if (y>9&&y<13) {
				money=4000;
			}else if (y>12&&y<16) {
				money=6000;
			}else if (y>15&&y<21) {
				money=8000;
			}
		} else {
			if (y>0&&y<4) {
				money=600;
			}else if (y>3&&y<6) {
				money=900;
			}else if (y>5&&y<9) {
				money=1200;
			}else if (y>8&&y<11) {
				money=2000;
			}
		}
		
		return new BigDecimal(money);
	}
	
	
	
	
	/**
         * @param htmlStr
         * @return
         *  删除Html标签
         */
        public static String delHTMLTag(String htmlStr) {
            Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            Matcher m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); // 过滤script标签
       
            Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            Matcher m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); // 过滤style标签
       
            Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            Matcher m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); // 过滤html标签
       
            Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);
            Matcher m_space = p_space.matcher(htmlStr);
            htmlStr = m_space.replaceAll(""); // 过滤空格回车标签
            return htmlStr.trim(); // 返回文本字符串
        }
           
        public static String getTextFromHtml(String htmlStr){
            htmlStr = delHTMLTag(htmlStr);
            htmlStr = htmlStr.replaceAll("&nbsp;", "");
            return htmlStr;
        }
}