package com.goafanti.patent.service.impl;


import cn.jiguang.common.utils.StringUtils;
import com.goafanti.admin.service.DepartmentService;
import com.goafanti.common.bo.EmailBo;
import com.goafanti.common.bo.Error;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.AsyncUtils;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.ExcelUtils;
import com.goafanti.common.utils.SendEmailUtil;
import com.goafanti.common.utils.excel.NewExcelUtil;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.patent.bo.PatentNewBo;
import com.goafanti.patent.enums.PatentType;
import com.goafanti.patent.service.PatentNewService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;

@Service
public class PatentNewServiceImpl  extends BaseMybatisDao<PatentNewMapper> implements PatentNewService {
	@Autowired
	private PatentNewMapper patentNewMapper;
	@Autowired
	private PatentNewLogMapper patentNewLogMapper;
	@Autowired
	private TOrderTaskMapper	tOrderTaskMapper;
	@Autowired
	private PatentPaymentDetailsMapper	patentPaymentDetailsMapper;
	@Autowired
	private PatentYearPaymentMapper	patentYearPaymentMapper;
	@Autowired
	private AsyncUtils asyncUtils;
	@Autowired
	private AdminMapper	adminMapper;
	@Autowired
	private DepartmentService departmentService;

	private List<PatentYearPayment> patentYear=new ArrayList<PatentYearPayment>();




	@Value(value = "${upload.path}")
	private String uploadPath=null;

	@Override
	public int addPatenNew(PatentNew p) {
		p.setStatus(0);//
		p.setAid(TokenManager.getAdminId());
		return patentNewMapper.insertSelective(p);
	}

	@Override
	public int updatePatenNew(PatentNewBo p) {
		Admin a = adminMapper.selectById(TokenManager.getAdminId());
		PatentNew pn=patentNewMapper.selectByPrimaryKey(p.getId());
		StringBuffer str=new StringBuffer(a.getName());
		if (!p.getApplyDate().equals(pn.getApplyDate())
				|| !Objects.equals(p.getType(), pn.getType())) {
			p.setYears(getyear(p));
			p.setPatentAmount(sumAmout(p.getType(),p.getTid(),p.getYears()));
			 if(p.getPatentAmount()==null) {
		        	throw new BusinessException(new Error("年份超过最大可提醒日期。"));
		        }
			p.setStatus(getSatus(p.getEndDate()));
			sumYears(p);
		}
		addPatentNewLog(p,pn,str);
		return patentNewMapper.updateByPrimaryKeySelective(p);
	}

	private void addPatentNewLog(PatentNewBo p, PatentNew pn, StringBuffer str) {
		PatentNewLog pl = new PatentNewLog();
		pl.setPid(p.getId());
		boolean flag=false;
		StringBuilder s=new StringBuilder();
		if (p.getPatentNo()!=null&&!p.getPatentNo().equals(pn.getPatentNo())) {
			s.append("[专利号：").append(pn.getPatentNo()).append(" => ").append(p.getPatentNo()).append("],");
			flag=true;
		}
		if (p.getName()!=null&&!p.getName().equals(pn.getName())) {
			s.append("[专利名称：").append(pn.getName()).append(" => ").append(p.getName()).append("],");
			flag=true;
		}
		if (p.getType()!=null&&!p.getType().equals(pn.getType())) {
			// 0=发明专利，1=使用新型，2=外观设计
			String type = getPatentType(p.getType());
			String type1 = getPatentType(pn.getType());
			s.append("[专利类型：").append(type1).append(" => ").append(type).append("],");
			flag=true;
		}
		if (p.getTid()!=null&&!p.getTid().equals(pn.getTid())) {
			s.append("[项目编号：").append(pn.getTid()).append(" => ").append(p.getTid()).append("],");
			flag=true;
		}
		if (p.getApplyDate()!=null&&!p.getApplyDate().equals(pn.getApplyDate())) {
			String date = DateUtils.formatDate(p.getApplyDate(), AFTConstants.YYYYMMDD);
			String date1="";
			if(pn.getApplyDate()!=null) {
				date1 = DateUtils.formatDate(pn.getApplyDate(), AFTConstants.YYYYMMDD);
			}
			s.append("[申请日期：").append(date1).append(" => ").append(date).append("],");
			flag=true;
		}
		if (p.getAuthorizationDate()!=null&&!p.getAuthorizationDate().equals(pn.getAuthorizationDate())) {
			String date = DateUtils.formatDate(p.getAuthorizationDate(), AFTConstants.YYYYMMDD);
			String date1="";
			if(pn.getAuthorizationDate()!=null) {
				date1 = DateUtils.formatDate(pn.getAuthorizationDate(), AFTConstants.YYYYMMDD);
			}
			s.append("[授权日期：").append(date1).append(" => ").append(date).append("],");
			flag=true;
		}
		if (p.getEmail()!=null&&!p.getEmail().equals(pn.getEmail())) {
			s.append("[Email：").append(pn.getEmail()).append(" => ").append(p.getEmail()).append("],");
			flag=true;
		}
		if (p.getDelayingAmount()!=null&&p.getDelayingAmount().compareTo(pn.getDelayingAmount()) != 0) {
			s.append("[滞纳金：").append(pn.getDelayingAmount().stripTrailingZeros().toPlainString()).append(" => ")
					.append(p.getDelayingAmount().stripTrailingZeros().toPlainString()).append("],");
			flag=true;
		}
		if (p.getRecoveryAmount()!=null&&p.getRecoveryAmount().compareTo(pn.getRecoveryAmount()) != 0) {
			s.append("[权利恢复费：").append(pn.getRecoveryAmount().stripTrailingZeros().toPlainString()).append(" => ")
					.append(p.getRecoveryAmount().stripTrailingZeros().toPlainString()).append("],");
			flag=true;
		}
		if (p.getAnnualFeeStatus()!=null&&!p.getAnnualFeeStatus().equals(pn.getAnnualFeeStatus())) {
			s.append("[年费状态：").append(pn.getAnnualFeeStatus() == 1 ? "已缴费" : "未缴费").append(" => ")
					.append(p.getAnnualFeeStatus() == 1 ? "已缴费" : "未缴费").append("],");
			flag=true;
		}
		if (p.getHolders()!=null&&!p.getHolders().equals(pn.getHolders())) {
			s.append("[权利人：").append(pn.getHolders()).append(" => ").append(p.getHolders()).append("],");
			flag=true;
		}
		if (p.getInventor()!=null&&!p.getInventor().equals(pn.getInventor())) {
			s.append("[发明人：").append(pn.getInventor()).append(" => ").append(p.getInventor()).append("],");
			flag=true;
		}
		if (flag) {
			str.append("修改了：").append(s);
			pl.setContent(str.substring(0, str.toString().length()-1));
			patentNewLogMapper.insertSelective(pl);
		}
	}

	private String getPatentType(Integer type) {
		if (type==0) return "发明专利";
		else if (type==1) return "实用新型";
		else if (type==2) return "外观设计";
		return null;
	}

	@Override
	public Pagination<PatentNewBo> selectPatentNew(PatentNewBo p,Integer pageSize, Integer pageNo) {
		Map<String, Object> params = new HashMap<>();
		if (pageNo == null || pageNo < 0) pageNo = 1;
		if (pageSize == null || pageSize < 0)	pageSize = 10;
		pushParams(p, params);
		Pagination<PatentNewBo> pa=(Pagination<PatentNewBo>) findPage("selectPatentNewList", "selectPatentNewCount", params, pageNo,
				pageSize);
		List<PatentNewBo> list=(List<PatentNewBo>) pa.getList();
		 String aid=TokenManager.getAdminId();
		for (PatentNewBo pn : list) {
            if (aid != null && aid.equals(pn.getAid())) {
                pn.setIsFollow(1);
            }
        }
		return pa;
	}

	private void pushParams(PatentNewBo p, Map<String, Object> params) {
		if(p.getStatus()!=null)params.put("status", p.getStatus());
		if(p.getName()!=null)params.put("name", p.getName());
		if(p.getAname()!=null)params.put("aname", p.getAname());
		if(p.getPatentNo()!=null)params.put("patentNo", p.getPatentNo());
		if(p.getDepartmentId()!=null)params.put("departmentId", p.getDepartmentId());
		if(p.getStartDates()!=null)params.put("startDates", p.getStartDates());
		if(p.getEndDates()!=null)params.put("endDates", p.getEndDates()+" 23:59:59");
		if(p.getCreateStarts()!=null)params.put("createStarts", p.getCreateStarts());
		if(p.getCreateEnds()!=null)params.put("createEnds", p.getCreateEnds()+" 23:59:59");
		if(p.getType()!=null)params.put("type", p.getType());
		if(p.getDepName()!=null){
			params.put("depName",  departmentService.parseArray(p.getDepName()));
		}
		if(p.getAnnualFeeStatus()!=null)params.put("annualFeeStatus", p.getAnnualFeeStatus());
		if(p.getUserName()!=null)params.put("userName", p.getUserName());
		if(p.getSalesmanRemind()!=null)params.put("salesmanRemind", p.getSalesmanRemind());
		if(p.getInputDep()!=null){
			params.put("inputDep", departmentService.parseArray(p.getInputDep()));
		}
		if(p.getFollowDep()!=null){
			params.put("followDep", departmentService.parseArray(p.getFollowDep()));
		}

		if(p.getIsFollow()!=null) {
			params.put("isFollow", p.getIsFollow());
		}else {
			params.put("isFollow", 0);
		}
		params.put("aid", TokenManager.getAdminId());
		if (TokenManager.hasRole(AFTConstants.SUPERADMIN) || TokenManager.hasRole(AFTConstants.PATENT_AUDITOR)) {
			params.put("shiro", 2);
		} else  if (TokenManager.hasRole(AFTConstants.SALESMAN_ADMIN)) {
			params.put("shiro", 1);
		} else   {
			params.put("shiro", 0);
		}
	}

	@Override
	public List<PatentNewBo> AllselectStartPatentNew() {
		return patentNewMapper.AllselectStartPatentNew();
	}

	@Override
	public int addPatenNewLog(PatentNewLog pl) {
		return patentNewLogMapper.insertSelective(pl);
	}

	@Override
	public List<PatentNew> AllselectEndPatentNew() {
		return patentNewMapper.AllselectEndPatentNew();
	}

	@Override
	public void insertLogBatch(List<PatentNewLog> list) {
		patentNewLogMapper.insertLogBatch(list);
	}

	@Override
	public List<PatentNewLog> selectPatentNewLog(Integer id) {
		return patentNewLogMapper.selectPatentNewLog(id);
	}

	@Override
	public void pushImportTemplate(MultipartFile file) {
		 //获得Workbook工作薄对象
        Workbook workbook = ExcelUtils.getWorkBook(file);
        //创建一个对象，用来存储数据
        if(workbook != null){
        	//获得当前sheet工作表
    		Sheet sheet = workbook.getSheetAt(0);
    		if(sheet == null){
    			return;
    		}
    		//获得当前sheet的开始行
    		int firstRowNum = sheet.getFirstRowNum();
    		//获得当前sheet的结束行
    		int lastRowNum = sheet.getLastRowNum();
    		//处理空白行
    		for (int i = firstRowNum; i <= sheet.getLastRowNum();i++) {
    			Row r = sheet.getRow(i);
    			if(r == null){
    				// 如果是空行（即没有任何数据、格式），直接把它以下的数据往上移动
    				sheet.shiftRows(i+1, sheet.getLastRowNum(),-1);
    				continue;
    			}
    			boolean flag = false;
    			for(Cell c:r){
    				if(c.getCellTypeEnum() != CellType._NONE){
    					flag = true;
    					break;
    				}
    			}
    			if(flag){
    				i++;
    				continue;
    			} else{//如果是空白行（即可能没有数据，但是有一定格式）
    				if(i == sheet.getLastRowNum())//如果到了最后一行，直接将那一行remove掉
    					sheet.removeRow(r);
    				else//如果还没到最后一行，则数据往上移一行
    				    sheet.shiftRows(i+1, sheet.getLastRowNum(),-1);
    			}
    		}
    		lastRowNum=sheet.getLastRowNum();
    		if (lastRowNum<2) {
    			throw new BusinessException(new Error("未找到正确的参数。"));
			}
    		List<PatentNew> list=new ArrayList<>();
    		List<Notice> nl= new ArrayList<>();
    		String str= "";
    		//循环除了第2行的所有行
    		for(int rowNum = firstRowNum+2;rowNum <= lastRowNum;rowNum++){
        		//获得当前行
				Row row = sheet.getRow(rowNum);
				if(row == null){
					continue;
				}
	        	//获得当前行的开始列
	        	int firstCellNum = row.getFirstCellNum();
	        	//获得当前行的列数
	        	int lastCellNum = row.getLastCellNum();
		        //循环当前行 cellNum = (firstCellNum+1) 则是除开第一例
	        	PatentNew trb=new PatentNew();
		        for(int cellNum = (firstCellNum); cellNum < lastCellNum;cellNum++){
			        Cell cell = row.getCell(cellNum);
			    	try {
			        switch (cellNum) {
					case 0:
						trb.setPatentNo(ExcelUtils.getCellValue(cell));
						break;
					case 1:
						trb.setName(ExcelUtils.getCellValue(cell).trim());
						break;
					case 2:
						trb.setType(PatentType.getCodeByDesc(ExcelUtils.getCellValue(cell)));
						break;
					case 3:
						trb.setApplyDate(ExcelUtils.getCellDate(cell));
						break;
					case 4:
						trb.setHolders(ExcelUtils.getCellValue(cell));
						break;
					case 5:
							trb.setAuthorizationDate(ExcelUtils.getCellDate(cell));
						break;
					case 6:
						trb.setInventor(ExcelUtils.getCellValue(cell));
						break;
					case 7:
						trb.setEmail(ExcelUtils.getCellValue(cell));
						break;
					case 8:
						str=ExcelUtils.getCellValue(cell);
						if (StringUtils.isNotEmpty(str)) {
							trb.setTid(Integer.parseInt(str));
						}
						break;

			        }
			    	} catch (Exception e) {
			    		e.printStackTrace();
			    		throw new BusinessException(new Error("表格第"+(rowNum+1)+"行"+(cellNum+1)+"列输入内容不正确。"));
					}
			    	if (cellNum==0&&trb.getPatentNo()!=null) {
						Integer i=patentNewMapper.selectByPatenNo(trb.getPatentNo());
						if (i>0) {
							throw new BusinessException(new Error("表格第"+(rowNum+1)+"行[专利编号]系统已存在。"));
						}
					}
		        }
		        for (PatentNew pt : list) {
		        	if (pt.getPatentNo().equals(trb.getPatentNo())) {
		        		throw new BusinessException(new Error("表格第"+(rowNum+1)+"行[专利编号]重复导入。"));
		        	}
		        }
		        if (trb.getType()==10) {
		        	throw new BusinessException(new Error("表格第"+(rowNum+1)+"专利类型错误。"));
				}
		        Date date=new Date();
		        trb.setAid(TokenManager.getAdminId());
		        trb.setInputId(trb.getAid());
		        trb.setCreateTime(date);
		        trb.setNewType(1);
		        trb.setYears(getyear(trb));
		        trb.setStatus(getSatus(trb.getEndDate()));
		        trb.setPatentAmount(sumAmout(trb.getType(),trb.getTid(),trb.getYears()));
		        if(trb.getPatentAmount()==null) {
		        	throw new BusinessException(new Error("表格第"+(rowNum+1)+"行年份超过最大可提醒日期。"));
		        }
		        list.add(trb);
		        if (trb.getStatus()!=0) {
		        	Notice n = addNotice(trb);
		        	n.setId(UUID.randomUUID().toString());
		        	n.setCreateTime(date);
		        	n.setReaded(0);// 未读
		        	n.setNoticeType(NoticeStatus.TASK_PATENT_REMIND.getCode());
					nl.add(n);
				}
		    }

    		List<PatentNew> list2=new ArrayList<>();
    		for (int i = 0; i < list.size(); i++) {
    			list2.add(list.get(i));
    			if (50 == list2.size() || i == list.size() - 1) {
                    patentNewMapper.insertBatch(list2);
                    list2.clear();

    			}
    		}
    		asyncUtils.addNoticeBatch(nl);
        }

    }

	private Notice addNotice(PatentNew p) {
		Notice n = new Notice();
		Date date=new Date();
		n.setId(UUID.randomUUID().toString());
		n.setCreateTime(date);
		n.setReaded(0);// 未读
		n.setNoticeType(NoticeStatus.TASK_PATENT_ERROR.getCode());
		Admin a = adminMapper.selectById(p.getAid());
		StringBuffer str2 = new StringBuffer();
		str2.append("专利编号[").append(p.getPatentNo()).append("],名称[").append(p.getName()).append("],email[")
				.append(p.getEmail().trim()).append("]");
		if (a == null) {
			str2.append(",aid=").append(p.getAid()).append(",找不到管理员。");
			n.setAid("1");
			n.setContent(str2.toString());
		} else if (!SendEmailUtil.isEmail(p.getEmail().trim())) {
			str2.append(",管理员=").append(a.getName()).append(",邮箱不正确。");
			n.setAid("1");
			n.setContent(str2.toString());
		} else {
			PatentNewLog pl = new PatentNewLog();
			String str = StrToString(str2,p.getEndDate(),p.getStatus());
			pl.setContent(str);
			pl.setCreateTime(new Date());
			pl.setPid(p.getId());
			patentNewLogMapper.insertSelective(pl);
			n.setAid(p.getAid());
			n.setNoticeType(NoticeStatus.TASK_PATENT_REMIND.getCode());
			n.setContent(str);
		}
		return n;
	}

	private String StrToString(StringBuffer str, Date date, Integer status) {
		//状态 0 未提醒 1 剩余90天 2剩余30天 3剩余20天 4剩余10天 5剩余3天 6剩余2天 7剩余1天
		Integer days=0;
		if (status==1) days=90;
		else if (status==2) days=60;
		else if (status==3) days=30;
		else if (status==4) days=15;
		else if (status==5) days=7;
		if(days>0) {
			str.append(",续费时间还剩").append(days).append("天");
		}
		str.append(",截止时间[").append(DateUtils.formatDate(date, AFTConstants.YYYYMMDD)).append("]请在截止时间前通知客户!");
		return str.toString();
	}

	public Integer getSatus(Date endDate) {
		int count=countDays(endDate);
		int status=0;
		if (count > 60 && count <= 90) {
			status=1;
		} else if (count > 30 && count <= 60) {
			status=2;
		}else if (count > 15 && count <= 30) {
			status=3;
		}else if (count > 7 && count <= 15) {
			status=4;
		}else if (count>0&&count <= 7) {
			status=5;
		}
		return status;
	}

	private Integer getyear(PatentNew p) {
		Calendar c=Calendar.getInstance();
		c.setTime(p.getApplyDate());
		int x=c.get(Calendar.YEAR);
		Calendar now=Calendar.getInstance();
		int y=now.get(Calendar.YEAR);
		int z=y-x;
		if (z==0) z=1;
		Calendar end=Calendar.getInstance();
		end.setTime(p.getApplyDate());
		end.add(Calendar.YEAR, z);
		p.setEndDate(end.getTime());
		return z;
	}

	private List<PatentPaymentDetails> sumYears(PatentNew trb) {
		if (trb.getApplyDate()!=null) {
			Calendar apply =Calendar.getInstance();
			apply.setTime(trb.getApplyDate());
			List<PatentPaymentDetails> list =new ArrayList<PatentPaymentDetails>();
			for (int i = 1; i < 21; i++) {
				PatentPaymentDetails pd=new PatentPaymentDetails();
				if ((trb.getType()==0||trb.getType()==2)&&i<11) {
						addParam(trb, apply, i, pd);
						list.add(pd);
				}else if (trb.getType()==1) {
					addParam(trb, apply, i, pd);
					list.add(pd);
				}
			}
			patentPaymentDetailsMapper.deleteByPid(trb.getId());
			patentPaymentDetailsMapper.insertBatch(list);
			return list;
		}
		return null;
	}

	private void addParam(PatentNew trb, Calendar apply, int i, PatentPaymentDetails pd) {
		Calendar end=Calendar.getInstance();
		end.setTime(apply.getTime());
		end.add(Calendar.YEAR, i);
		pd.setPid(trb.getId());
		pd.setEndDate(end.getTime());
		pd.setPatentAmount(sumAmout(trb.getType(),trb.getTid(),i));
		pd.setStatus(0);
		pd.setYears(i);
	}





	private BigDecimal sumAmout(Integer type,Integer tid,Integer year) {
		if (patentYear.isEmpty()) {
			patentYear=patentYearPaymentMapper.selectAll();
		}
		for (PatentYearPayment p : patentYear) {
			if (Objects.equals(type, p.getType()) && Objects.equals(year, p.getYear())) {
				if (tid==null){
					return p.getPatentAmount();
				}else{
					TOrderTask t=tOrderTaskMapper.queryById(tid);
					if (t!=null&&t.getCostReduction()!=null&& t.getCostReduction()==1) {
						return p.getReductionAmount();
					}else {
						return p.getPatentAmount();
					}
				}
			}
		}
		return null;
	}

	@Override
	public Object export(PatentNewBo p, Integer pageSize, Integer pageNo) {
		NewExcelUtil<PatentNewBo> excel=new NewExcelUtil<PatentNewBo>(PatentNewBo.class);
		Map<String, Object> params = new HashMap<>();
		if (pageNo == null || pageNo < 0) pageNo = 1;
		if (pageSize == null || pageSize < 0)	pageSize = 99999;
		pushParams(p, params);
		List<PatentNewBo> list= (List<PatentNewBo>) findList("selectPatentNewList", params, pageNo,
				pageSize);
		return excel.exportExcel(list, "专利列表",uploadPath);
	}

	@Override
	public Object pushPatentPaymentDetails(Integer id) {
		List<PatentPaymentDetails> list =patentPaymentDetailsMapper.selectByPid(id);
		if (list==null||list.isEmpty()) {
			PatentNew pt=patentNewMapper.selectByPrimaryKey(id);
			return sumYears(pt);
		}
		return list;
	}

	/** @param type 0 标记已通知 1批量发邮件 2转给营销员
	   */
	@Override
	public Object updateBatch(String ids, Integer type, String aid) {
		String[] s = ids.split(",");
		List<String> ls = Arrays.asList(s);
		addPatentNewLog(type, ls, aid);
		if (type == 1) {
			List<PatentNew> lp = patentNewMapper.selectByids(ls);
			List<EmailBo> list = new ArrayList<EmailBo>();
			for (PatentNew patentNew : lp) {
				if (patentNew.getStatus() == 0) {
					throw new BusinessException("专利号[" + patentNew.getPatentNo() + "]未达到距离截止时间90天，不允许发送邮件");
				}
				if (!SendEmailUtil.isEmail(patentNew.getEmail())) {
					throw new BusinessException("专利号[" + patentNew.getPatentNo() + "]的邮箱不正确。");
				}
			}
			for (PatentNew patentNew : lp) {
				Admin a = adminMapper.selectById(patentNew.getAid());
				String userName = patentNewMapper.selectUserNameByTid(patentNew.getTid());
				if (StringUtils.isEmpty(userName)){
					userName=patentNew.getHolders();
				}
				BigDecimal amout = patentNew.getPatentAmount().multiply(new BigDecimal(10000));
				String emailList = patentNew.getEmail();
				if (StringUtils.isNotEmpty(emailList)){
					String[] split = emailList.split(",");
					for (String email : split) {
						EmailBo emailBo = new EmailBo("专利提醒", email, userName, "科德集团", a.getName(),
								patentNew.getName(), patentNew.getPatentNo(), amout.stripTrailingZeros().toPlainString(),
								patentNew.getEndDate());
						list.add(emailBo);
					}
				}
			}
				asyncUtils.patentSend(list);
		}
		if (type == 0 || type == 1) {
			patentNewMapper.updateBatch(ls);
		} else if (type == 2) {
			patentNewMapper.updateBatchByid(ls, null, aid);
		}
		return 1;
	}

	/**
	 * 批量添加专利日志
	 */
	private void addPatentNewLog(Integer type, List<String> ls,String aid) {
		List<PatentNewLog> log=new ArrayList<PatentNewLog>();
		Date date=new Date();
		Admin a=adminMapper.selectById(TokenManager.getAdminId());
		Admin s=adminMapper.selectById(aid);
		for (String str : ls) {
			PatentNewLog pl=new PatentNewLog();
			pl.setPid(Integer.valueOf(str));
			pl.setCreateTime(date);
			String content="[%s]批量将专利%s";
			if(type==0)str=String.format(content,a.getName(),"标记已通知。");
			else if(type==1)str=String.format(content,a.getName(),"发送邮件。");
			else if(type==2)str=String.format(content,a.getName(),"转交给["+s.getName()+"]。");
			pl.setContent(str);
			log.add(pl);
		}
		patentNewLogMapper.insertLogBatch(log);
	}

	@Override
	public void updateBatchStatusByid(List<String> l2, Integer status) {
		patentNewMapper.updateBatchByid(l2,status,null);

	}

	/**
	 * 超过时间重置到第二年
	 */
	@Override
	public void pushResetPatentNew(List<String> list) throws InterruptedException {
		List<PatentNewLog> logs = new ArrayList<>();
		for (String ids : list) {
			PatentNew pn=patentNewMapper.selectByPrimaryKey(Integer.valueOf(ids));
			int year=pn.getYears()+1;
			PatentPaymentDetails ppd=patentPaymentDetailsMapper.selectByPidAndYear(pn.getId(),year);
			//未找到下一年则计算看是否存在
			if (ppd==null) {
				sumYears(pn);
				ppd=patentPaymentDetailsMapper.selectByPidAndYear(pn.getId(),year);
			}
			PatentNew n=new PatentNew();
			n.setId(pn.getId());
			n.setStatus(0);
			n.setSalesmanRemind(0);
			//还是未找到，判断为不存在一下年，判断提醒已完成
			if(ppd==null){
				n.setStatus(6);
			}else{
				n.setYears(ppd.getYears());
				n.setEndDate(ppd.getEndDate());
				n.setPatentAmount(sumAmout(pn.getType(),pn.getTid(),pn.getYears()));
				PatentNewLog log=new PatentNewLog();
				log.setContent("超过时间重置状态并计算下一年");
				log.setCreateTime(new Date());
				log.setPid(Integer.valueOf(ids));
				logs.add(log);
			}
			patentNewMapper.updateByPrimaryKeySelective(n);
		}
		pushPatentLog(logs);
	}

	private void pushPatentLog(List<PatentNewLog> logList) throws InterruptedException {
		if (!logList.isEmpty()) {
			List<PatentNewLog> logList2 = new ArrayList<>();
			for (int i = 0; i < logList.size(); i++) {
				logList2.add(logList.get(i));
				if (50 == logList2.size() || i == logList.size() - 1) {
                    insertLogBatch(logList2);
					Thread.sleep(2000);
					logList2.clear();
				}
			}

		}
	}

	@Override
	public boolean checkTid(Integer tid) {
		TOrderTask task=tOrderTaskMapper.queryById(tid);
        return task == null;
    }

	@Override
	public int countDays(Date endDate) {
		// 申请时间
		Calendar end = Calendar.getInstance();
		end.setTime(endDate);
		// 当前时间
		Calendar now = Calendar.getInstance();
		now.setTime(new Date());
		now.set(Calendar.MILLISECOND, 0);
		now.set(Calendar.HOUR_OF_DAY, 0);
		now.clear(Calendar.MINUTE);
		now.clear(Calendar.SECOND);
        return (int) ((end.getTimeInMillis() - now.getTimeInMillis()) / (1000 * 3600 * 24));
	}

	@Override
	public void updateCostReduction(Integer id) {
		List<PatentNew> list =patentNewMapper.selectByTid(id);
		Admin	a=	adminMapper.selectById(TokenManager.getAdminId());
		for (PatentNew p : list) {
			PatentNew pn=new PatentNew();
			pn.setId(p.getId());
			pn.setPatentAmount(sumAmout(p.getType(), id, p.getYears()));
			sumYears(p);
			PatentNewLog pl = new PatentNewLog();
			pl.setPid(p.getId());
            pl.setContent(a.getName() + "修改了有无费减");
			patentNewLogMapper.insertSelective(pl);
			patentNewMapper.updateByPrimaryKeySelective(pn);
		}

	}
}
