package com.goafanti.common.utils;

import com.goafanti.admin.bo.AdminListBo;
import com.goafanti.common.bo.EmailBo;
import com.goafanti.common.bo.OrderExamineBo;
import com.goafanti.common.bo.OrderOperator;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.enums.NoticeTypes;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.weChat.WeChatUtils;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.order.bo.NewOrderChangeBo;
import com.goafanti.order.bo.TOrderNewBo;
import com.goafanti.order.bo.TOrderTaskBo;
import com.goafanti.order.enums.NewProjectStatus;
import com.goafanti.order.enums.OrderChangeProcess;
import com.goafanti.order.enums.OrderChangeType;
import com.goafanti.order.enums.ProcessStatus;
import com.goafanti.organization.bo.OrganizationListOut;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
@Async
public class AsyncUtils {
	@Resource
	private NoticeMapper noticeMapper;
	@Resource
	private AdminMapper adminMapper;
	@Resource
	private TOrderNewMapper tOrderNewMapper;
	@Resource
	private TOrderTaskMapper tOrderTaskMapper;
	@Resource
	private NewOrderChangeMapper newOrderChangeMapper;
	@Resource
	private OrderExamineMapper orderExamineMapper;
	@Resource
	private TaskAttributionLogMapper taskAttributionLogMapper;
	@Resource
	private TTaskLogMapper tTaskLogMapper;
	@Resource
	private DepartmentMapper departmentMapper;
	@Resource
	private OrderChangeLogMapper orderChangeLogMapper;
	@Resource
	private TOrderMidMapper tOrderMidMapper;
	@Resource
	private RoleMapper roleMapper;
	@Resource
	private ExpenseAccountMapper expenseAccountMapper;
	@Resource
	private TOrderInvoiceMapper tOrderInvoiceMapper;
	@Resource
	private TTaskMemberMapper tTaskMemberMapper;
	@Resource
	private TOrderPaymentMapper tOrderPaymentMapper;
	@Resource
	private FinanceCountMapper financeCountMapper;
	@Resource
	private WeChatUtils weChatUtils;
	@Resource
	private AdminProjectStatisticsMapper adminProjectStatisticsMapper;






    public void patentSend(EmailBo bo) throws UnsupportedEncodingException, MessagingException {
		SendEmailUtil.getInstance().patentSend(bo);
	}

	public void patentSend(List<EmailBo> list) {
		try {
			for (EmailBo emailBo : list) {
					SendEmailUtil.getInstance().patentSend(emailBo);
			}
		} catch (MessagingException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}
    }

	public void sendList(List<EmailBo> list) {
		try {
			for (EmailBo emailBo : list) {
				SendEmailUtil.getInstance().send(emailBo);
				LoggerUtils.debug(getClass(),String.format("=============发送邮件==>%s===>%s",emailBo.getSubject(),emailBo.getAddress()));
			}
		} catch (MessagingException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}


	/**
	 * 发送邮件
	 * @param bo 邮件信息
	 */
	public void send(EmailBo bo){
		try {
			if (bo.getAddress()==null){
				LoggerUtils.debug(getClass(),"邮件发送失败，发送地址不纯在");
			}else {
				SendEmailUtil.getInstance().send(bo);
				LoggerUtils.debug(getClass(),String.format("====================" +
						"邮件发送成功，地址={%s}，类型={%s}",bo.getAddress(),bo.getSubject()));
			}
		} catch (UnsupportedEncodingException | MessagingException e) {
			LoggerUtils.error(getClass(),"邮件发送错误");
			e.printStackTrace();
		}
	}

	public void addNotice(Notice n ) {
		n.setType(NoticeTypes.getType(n.getNoticeType()));
		noticeMapper.insertSelective(n);
	}

	public void addNotic(Integer type, String  aid,String str) {
		Notice n =new Notice();
		n.setId(UUID.randomUUID().toString());
		n.setAid(aid);
		n.setNoticeType(type);
		n.setContent(str);
		n.setReaded(0);//未读
		addNotice(n);
	}

	/**
	 *
	 * @param type NoticeStatus的类型
	 * @param aid 接受者编号
	 * @param str 推送信息
	 */
	public void addNoticAndEmail(Integer type, String  aid,String str) {
		Notice n =new Notice();
		n.setId(UUID.randomUUID().toString());
		n.setAid(aid);
		n.setNoticeType(type);
		n.setContent(str);
		n.setReaded(0);//未读
		addNoticAndEmail(n);
	}





	public void addNoticAndEmail(Notice n) {
		n.setType(NoticeTypes.getType(n.getNoticeType()));
		AdminListBo a = adminMapper.getDeptNameByAid(n.getAid());
		EmailBo bo=new EmailBo(NoticeStatus.getStatus(n.getNoticeType()).getDesc(),a.getEmail(),n.getContent()) ;
		noticeMapper.insertSelective(n);
		if (StringUtils.isNotBlank(bo.getAddress())){
			send(bo);
		}
	}

	/**
	 *
	 * @param aid 通知对象
	 * @param noticeType  通知类型
	 * @param content 通知内容
	 */
	public void addNoticAndEmail(String aid,Integer noticeType,String content) {
		Notice n=new Notice();
		n.setId(UUID.randomUUID().toString());
		n.setAid(aid);
		n.setNoticeType(noticeType);
		n.setContent(content);
		n.setReaded(0);
		n.setType(NoticeTypes.getType(n.getNoticeType()));
		addNoticAndEmail(n);
	}


	public void addNoticeBatch(List<Notice> ln) {
		List<Notice> newList=new ArrayList<Notice>();
		if (ln != null && ln.size() > 0) {
			for (int i = 0; i < ln.size(); i++) {
				ln.get(i).setType(NoticeTypes.getType(ln.get(i).getNoticeType()));
				newList.add(ln.get(i));
				if (50 == newList.size() || i == ln.size() - 1) {
					if (newList.size() > 0) noticeMapper.insertBatch(newList);
					for (Notice e : newList) {
						LoggerUtils.debug(getClass(),String.format("=============发送站内信==>%s===>%s",NoticeStatus.getValueByCode(e.getNoticeType()),e.getContent()));
					}
					newList.clear();
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}


	}


    public void batchUpdateUnreaded(List<String> dl) {
		noticeMapper.batchUpdateUnreaded(dl);
    }








	/**
	 *
	 * @param type  发送对象 0发起营销管理员 1 完成通知所有人 2拒绝发送给营销员
	 *  @param sotpType  发送对象 类型 0=项目暂停，1=项目重启
	 *
	 */
	public void addProjectSotpNotic(Integer type,  Integer sotpType, String ids, TOrderTask task) {
		Integer noticeType=0;
		if (task==null)task = tOrderTaskMapper.queryById(Integer.valueOf(ids.split(",")[0]));
		TOrderNewBo tOrderNew = tOrderNewMapper.getOrderNewDetail(task.getOrderNo());
		List<Notice> notes=new ArrayList<>();
		StringBuffer emails=new StringBuffer();
		if (type==0){
			noticeType=sotpType==0?NoticeStatus.PROJECT_SOPT_START.getCode() :NoticeStatus.PROJECT_RENEW_START.getCode();
			String str=String.format("客户名称[%s]订单编号[%s]项目编号[%s],请及时审核。",tOrderNew.getUserName(),task.getOrderNo(),ids);
			List<Admin> admins = adminMapper.listAdminBydepIdAndRoleType(tOrderNew.getOrderDep(),AFTConstants.SALESMAN_ADMIN);
			for (Admin admin : admins) {
				addNotic( noticeType,admin.getId(), str);
				send(new EmailBo(NoticeStatus.getValueByCode(noticeType),admin.getEmail(),str));
			}
		}else if(type==1){
			String str=String.format("客户名称[%s]订单编号[%s]项目编号[%s],已%s请悉知。",tOrderNew.getUserName(),task.getOrderNo(),task.getId(),sotpType==1?"重启":"暂停");
			noticeType=sotpType==0?NoticeStatus.PROJECT_SOPT_YES.getCode() :NoticeStatus.PROJECT_RENEW_YES.getCode();
			OrderOperator orderOperator = tOrderTaskMapper.selectAidByParam(task.getId());
			List<String >aids=new ArrayList<>();
			if (orderOperator.getSalesmanId()!=null&&!aids.contains(orderOperator.getFinanceId())){
				aids.add(orderOperator.getSalesmanId());
			}
			if (task.getConsultantId()!=null&&!aids.contains(task.getConsultantId())){
				 aids.add(task.getConsultantId());
			}
			if (task.getManagerId()!=null&&!aids.contains(task.getManagerId())){
				aids.add(task.getManagerId());
			}
			if (orderOperator.getFinanceId()!=null&&!aids.contains(orderOperator.getFinanceId())){
				aids.add(orderOperator.getFinanceId());
			}
			List<Admin> cwgly = adminMapper.selectAdminByRoleType(AFTConstants.FINANCE_ADMIN);
			for (Admin admin : cwgly) {
				if (!aids.contains(admin.getId())){
					aids.add(admin.getId());
				}
			}
			List<Admin> zxsgly = adminMapper.selectAdminByRoleType(AFTConstants.TECH_ADMIN);
			for (Admin admin : zxsgly) {
				if (!aids.contains(admin.getId())){
					aids.add(admin.getId());
				}
			}
			List<Admin> zc = adminMapper.selectAdminByRoleType(AFTConstants.CED);
			for (Admin admin : zc) {
				if (!aids.contains(admin.getId())){
					aids.add(admin.getId());
				}
			}
			List<Admin> dsz = adminMapper.selectAdminByRoleType(AFTConstants.APPROVAL_DECISION);
			for (Admin admin : dsz) {
				if (!aids.contains(admin.getId())){
					aids.add(admin.getId());
				}
			}
			if (!aids.isEmpty()){
				for (String aid : aids) {
					pushParam( aid,  noticeType, str,  notes,  emails);
				}
			}
			noticeMapper.insertBatch(notes);
			send(new EmailBo(NoticeStatus.getValueByCode(noticeType),emails.substring(0,emails.length()-1),str));
			}else if (type==2){
				noticeType=sotpType==0?NoticeStatus.PROJECT_SOPT_NO.getCode() :NoticeStatus.PROJECT_RENEW_NO.getCode();
				String str=String.format("客户名称[%s]订单编号[%s]项目编号[%s],已经被驳回。",tOrderNew.getUserName(),task.getOrderNo(),task.getId());
				if (tOrderNew.getSalesmanId()!=null){
					Admin admin = adminMapper.selectById(tOrderNew.getSalesmanId());
					addNotic( noticeType,admin.getId(), str);
					send(new EmailBo(NoticeStatus.getValueByCode(noticeType),admin.getEmail(),str));
				}
			}
		}

	private void pushParam(String id, Integer noticeType, String str, List<Notice> notes, StringBuffer emails) {
		Admin admin = adminMapper.selectById(id);
		pushParam(admin,noticeType,str,notes,emails);

	}



	private void pushParam(Admin admin, Integer noticeType, String str, List<Notice> notes, StringBuffer emails) {
		notes.add(new Notice(UUID.randomUUID().toString(), new Date(), 0, admin.getId(),
				noticeType, str));
		if (admin!=null &&StringUtils.isNotBlank(admin.getEmail())) {
			if (!emails.toString().contains(admin.getEmail())){
				emails = emails.append(admin.getEmail()).append(",");
			}
		}
	}


	/**
	 * @param date 日期
	 * @param admin 原本管理员
	 * @param tadmin 转交管理员
	 */
	public  void pushTechTransfer(Admin admin,Admin tadmin,Date date) {
		//获取旧人员与新人员的角色
		List<String>  useType=adminMapper.getAdminRoleListByAid(admin.getId());
		List<String>  newType=adminMapper.getAdminRoleListByAid(tadmin.getId());
		List<String>  useOrderNo=tOrderTaskMapper.selectOrderNoAllByaid(admin.getId());
		String aid=admin.getId();
		String transferId=tadmin.getId();
		if (useType.contains(AFTConstants.TECH)&&newType.contains(AFTConstants.TECH)){
			//System.out.println("同咨询师");
			List<Integer> list = newOrderChangeMapper.selectProcess(3, aid);
			tOrderTaskMapper.updateDimissionTransfer(aid, transferId, 0);
			orderExamineMapper.updateDimissionTransfer(aid, transferId,0,null);
			pushChangeProcessZXS(list);
		}else if (useType.contains(AFTConstants.TECH)&&newType.contains(AFTConstants.TECH_MANAGER)){
//			System.out.println("不同职业");
			List<Integer> list = newOrderChangeMapper.selectProcess(3, aid);
			tOrderTaskMapper.updateDimissionTransfer(aid, transferId, 3);
			orderExamineMapper.updateDimissionTransfer(aid, transferId,3,null);
			List<Integer> list2 = newOrderChangeMapper.selectProcess(4, transferId);
			//如果转交后订单全通过了，则变更+1
			pushChangeProcessZXS(list);
			pushChangeProcessZXSJL(list2);
		}
		if (useType.contains(AFTConstants.TECH_MANAGER)&&newType.contains(AFTConstants.TECH_MANAGER)){
//			System.out.println("同咨询师经理");
			List<Integer> list = newOrderChangeMapper.selectProcess(4, aid);
			tOrderTaskMapper.updateDimissionTransfer(aid, transferId, 1);
			tOrderTaskMapper.updateDimissionTransferManager(aid, transferId);
			orderExamineMapper.updateDimissionTransfer(aid, transferId,1,null);
			pushChangeProcessZXSJL(list);
		}else if (useType.contains(AFTConstants.TECH_MANAGER)&&newType.contains(AFTConstants.TECH)){
//			System.out.println("不同职业");
			//获取转交前的
			List<Integer> list = newOrderChangeMapper.selectProcess(4, aid);
			tOrderTaskMapper.updateDimissionTransfer(aid, transferId, 4);
			tOrderTaskMapper.updateDimissionTransferManager(aid, null);
			orderExamineMapper.updateDimissionTransfer(aid, transferId,4,null);
			List<Integer> list2 = newOrderChangeMapper.selectProcess(3, transferId);
			pushChangeProcessZXSJL(list);
			pushChangeProcessZXS(list2);
		}else {
			throw  new BusinessException("无法将项目转给非咨询角色");
		}
		taskAttributionLogMapper.insertList(aid, transferId, date);
		tTaskLogMapper.updateDimissionTransfer(aid, transferId);
		updateOrderMidServiceProject(useOrderNo);
	}

	private void updateOrderMidServiceProject(List<String> useOrderNo) {
		for (String orderNo : useOrderNo) {
			updateOrderMidServiceProject(orderNo);
		}
	}

	private void updateOrderMidServiceProject(String orderNo) {
		{
			List<TOrderTaskBo> taskBos = tOrderTaskMapper.selectOrderTaskAll(orderNo, null);
			if (!taskBos.isEmpty()){
				List<String > cp=new ArrayList<>();
				List<String > cc=new ArrayList<>();
				StringBuffer ps=new StringBuffer();
				StringBuffer cs=new StringBuffer();
				for (TOrderTaskBo taskBo : taskBos) {
					if (!cp.contains(taskBo.getCommodityName())){
						cp.add(taskBo.getCommodityName());
						ps=ps.append(taskBo.getCommodityName());
						String str= NewProjectStatus.getValueByCode(taskBo.getProjectStatus());
						ps=ps.append("-").append(str).append("-").append(taskBo.getContacts()).append(",");
					}
					if (!cc.contains(taskBo.getCname())){
						cc.add(taskBo.getCname());
						cs=cs.append(taskBo.getCname()).append(",");
					}
				}
				TOrderMid tOrderMid = new TOrderMid();
				tOrderMid.setOrderNo(orderNo);
				if (ps.length()>1)tOrderMid.setServiceProject(ps.substring(0,ps.length()-1));
				if (ps.length()>1)tOrderMid.setServiceType(cs.substring(0,cs.length()-1));
				tOrderMidMapper.updateByOrderNo(tOrderMid);
			}
		}
	}


	private void pushChangeProcessZXSJL(List<Integer> list) {
		if(!list.isEmpty()){
			Date date =new Date();
			for (Integer i : list) {
				NewOrderChangeBo changeBo = newOrderChangeMapper.selectById(i);
				pushZXSJL(changeBo,date,1);
				pushOrderCangeProcess(changeBo);
				newOrderChangeMapper.updateByPrimaryKeySelective(changeBo);
			}
		}
	}
	public void pushZXS(NewOrderChangeBo nb,  Date date,Integer type) {
		int zxs=orderExamineMapper.checkCountStatus(nb.getOrderNo(),0,null);
		if (zxs>0){
			nb.setProcessState(OrderChangeProcess.JSY.getCode());
		}else {
			if(type==1){
				date.setTime(date.getTime()+100);
				addOrderChangeLog("无咨询师自动通过", 2, nb.getOrderNo(), nb.getId(), date);
			}
			pushZXSJL(nb,date,1);
		}
	}
	public void pushZXSJL(NewOrderChangeBo nb,Date date,Integer type) {
		int zxsjl=orderExamineMapper.checkCountStatus(nb.getOrderNo(),1,0);
		if (nb.getType()== OrderChangeType.XMJJEBG.getCode()||
				nb.getType()==OrderChangeType.TDTK.getCode()||
				nb.getType()==OrderChangeType.TDBTK.getCode()||
				nb.getType()==OrderChangeType.CB.getCode()||
				nb.getType()==OrderChangeType.JXMBG.getCode()){
			if (zxsjl>0){
				nb.setProcessState(OrderChangeProcess.JSJL.getCode());
			}else {
				if (type==1){
					date.setTime(date.getTime()+100);
					addOrderChangeLog("无咨询师经理自动通过", 2, nb.getOrderNo(), nb.getId(),date);
				}
				//重报 没有技术员跳入财务
				if (nb.getType()==OrderChangeType.CB.getCode()){
					nb.setProcessState(OrderChangeProcess.CWZY.getCode());
					//项目变更没有跳入技术总监
				}else{
					nb.setProcessState(OrderChangeProcess.JSZJ.getCode());
				}
			}
		}
	}

	private void addOrderChangeLog(String remarks, Integer status, String orderNo, Integer id,Date date) {
		if (date ==null)date=new Date();
		OrderChangeLog ocl = new OrderChangeLog();
		ocl.setAuditor(TokenManager.getAdminId());
		ocl.setOrderNo(orderNo);
		ocl.setRemarks(remarks);
		ocl.setChangeId(id);
		ocl.setStatus(status);
		ocl.setCreateTime(date);
		orderChangeLogMapper.insertSelective(ocl);
	}


	private void pushChangeProcessZXS(List<Integer> list) {
		if(!list.isEmpty()){
			Date date =new Date();
			for (Integer i : list) {
				NewOrderChangeBo changeBo = newOrderChangeMapper.selectById(i);
				pushZXS(changeBo,date,1);
				pushOrderCangeProcess(changeBo);
				newOrderChangeMapper.updateByPrimaryKeySelective(changeBo);
			}
		}
	}


	public  void pushOrderCangeProcess(NewOrderChange noc) {
		if (noc.getProcessState()== OrderChangeProcess.YXY.getCode()){
			TOrderNewBo ton = tOrderNewMapper.getSaleIdByOno(noc.getOrderNo());
			noc.setExamineName(ton.getSalesmanName());
		}else if (noc.getProcessState()== OrderChangeProcess.YXJL.getCode()){
			TOrderNewBo ton = tOrderNewMapper.getSaleIdByOno(noc.getOrderNo());
			Admin saleman = adminMapper.selectById(ton.getSalesmanId());
			Admin manager = adminMapper.selectById(saleman.getManagerId());
			noc.setExamineName(manager.getName());
		}else if (noc.getProcessState()== OrderChangeProcess.YXGLY.getCode()){
			TOrderNewBo ton = tOrderNewMapper.getSaleIdByOno(noc.getOrderNo());
			StringBuffer str=new StringBuffer();
			List<Admin> admins = adminMapper.listAdminBydepIdAndRoleType(ton.getOrderDep(),AFTConstants.SALESMAN_ADMIN);
			if (admins.isEmpty()){
				OrganizationListOut dep = departmentMapper.selectAllById(ton.getOrderDep());
				admins = adminMapper.listAdminBydepIdAndRoleType(dep.getSuperId(),AFTConstants.SALESMAN_ADMIN);
			}
			for (Admin admin : admins) {
				if (!str.toString().contains(admin.getName()))str.append(admin.getName()).append(",");
			}
			if (str.length()>0)noc.setExamineName(str.substring(0,str.length()-1));
		}else if (noc.getProcessState()== OrderChangeProcess.JSY.getCode()){
			List<OrderExamineBo> os = orderExamineMapper.selectByOrderNo(noc.getOrderNo(), 0);
			StringBuffer str=new StringBuffer();
			for (OrderExamineBo o : os) {
				if (o.getStatus()==0){
					if (!str.toString().contains(o.getName()))str.append(o.getName()).append(",");
				}
			}
			if (str.length()>0)noc.setExamineName(str.substring(0,str.length()-1));


		}else if (noc.getProcessState()== OrderChangeProcess.JSJL.getCode()){
			List<OrderExamineBo> os = orderExamineMapper.selectByOrderNo(noc.getOrderNo(), 1);
			StringBuffer str=new StringBuffer();
			for (OrderExamineBo o : os) {
				if (o.getStatus()==0){
					if (!str.toString().contains(o.getName()))str.append(o.getName()).append(",");
				}
			}
			if (str.length()>0)noc.setExamineName(str.substring(0,str.length()-1));
		}else if (noc.getProcessState()== OrderChangeProcess.JSZJ.getCode()){
			StringBuffer str=new StringBuffer();
			List<Admin> admins = adminMapper.getAdminRoleTypeList(AFTConstants.TECH_ADMIN);
			for (Admin a : admins) {
				str=str.append(a.getName()).append(",");
			}
			if (str.length()>0)noc.setExamineName(str.substring(0,str.length()-1));

		}else if (noc.getProcessState()== OrderChangeProcess.CWZY.getCode()){
			TOrderNewBo ton = tOrderNewMapper.getSaleIdByOno(noc.getOrderNo());
			OrganizationListOut dep = departmentMapper.selectAllById(ton.getOrderDep());
			noc.setExamineName(dep.getFinanceName());
		}else if (noc.getProcessState()== OrderChangeProcess.CWZJ.getCode()){
			StringBuffer str=new StringBuffer();
			List<Admin> admins = adminMapper.getAdminRoleTypeList(AFTConstants.FINANCE_ADMIN);
			for (Admin a : admins) {
				str=str.append(a.getName()).append(",");
			}
			if (str.length()>0)noc.setExamineName(str.substring(0,str.length()-1));

		}else if (noc.getProcessState()== OrderChangeProcess.TPSH.getCode()||noc.getProcessState()== OrderChangeProcess.DSZ.getCode()){
			if(noc.getStatus()==2){
				TOrderNewBo ton = tOrderNewMapper.getSaleIdByOno(noc.getOrderNo());
				OrganizationListOut dep = departmentMapper.selectAllById(ton.getOrderDep());
				noc.setExamineName(dep.getFinanceName());
			}else {
				noc.setExamineName("");
			}
		}
	}

	/**
	 * 处理修改角色对于订单、变更审核人员的修改
	 * @param ad
	 * @param usead
	 * @param roleIds
	 */
	public  void pushRoleUpdateExamine(Admin ad, Admin usead, List<String> roleIds, List<Role>  useRole) {
		List<Role> roles = roleMapper.selectByIdList(roleIds);
		updateExamineByRole(ad, usead, useRole, roles,AFTConstants.SALESMAN);
		updateExamineByRole(ad, usead, useRole, roles,AFTConstants.SALESMAN_MANAGER);
		updateExamineByRole(ad, usead, useRole, roles,AFTConstants.SALESMAN_ADMIN);
		updateExamineByRole(ad, usead, useRole, roles,AFTConstants.TECH);
		updateExamineByRole(ad, usead, useRole, roles,AFTConstants.TECH_MANAGER);
		updateExamineByRole(ad, usead, useRole, roles,AFTConstants.TECH_ADMIN);
		updateExamineByRole(ad, usead, useRole, roles,AFTConstants.FINANCE);
		updateExamineByRole(ad, usead, useRole, roles,AFTConstants.FINANCE_ADMIN);
	}

	private void updateExamineByRole(Admin ad, Admin usead, List<Role> useRole, List<Role> roles, String roleType) {
		boolean updateParam=false;
		int updatedep =0;
		if (!ad.getName().equals(usead.getName())){
			updateParam=true;
		}
		boolean newDEP=Rolescontains(roles,roleType);
		boolean useDep=Rolescontains(useRole,roleType);
		if (newDEP||useDep){
			if (roleType.equals(AFTConstants.SALESMAN_ADMIN)){
				if (ad.getDepartmentId().equals(usead.getDepartmentId())){
					updatedep=1;
				}else{
					updatedep=2;
				}
				if (newDEP&&useDep){
					//新旧为同一个，修改当前就可以了
					if (updatedep ==1&& updateParam){
						updateOrderAndChangeExamine(ad, roleType);
						//新旧不是同一个，俩个都要修改
					}else if (updatedep ==2){
						updateOrderAndChangeExamine(ad, roleType);
						updateOrderAndChangeExamine(usead, roleType);
					}
				}else if (!newDEP&&useDep){
					updateOrderAndChangeExamine(usead, roleType);
				}
			}else if (roleType.equals(AFTConstants.SALESMAN)){
				if (ad.getManagerId()!=null&&usead.getManagerId()!=null&&!ad.getManagerId().equals(usead.getManagerId())){
					updateOrderAndChangeExamine(ad, roleType);
				}
			}else {
				if (updateParam){
					updateOrderAndChangeExamine(ad, roleType);
				}
			}

		}


	}


	private boolean Rolescontains(List<Role> roles, String roleType) {
		for (Role role : roles) {
			if (role.getRoleType().equals(Integer.valueOf(roleType))){
				return true;
			}
		}
		return false;
	}
	/**
	 *
	 * @param ad
	 * @param roleType
	 */
	public void updateOrderAndChangeExamine(Admin ad, String roleType) {
		if (roleType.equals(AFTConstants.SALESMAN_ADMIN)){
			updateSalesmanAdminExamine(ad.getId());
		}else if (roleType.equals(AFTConstants.SALESMAN)){
			updateSalesmanExamine(ad.getManagerId());
		}else if (roleType.equals(AFTConstants.SALESMAN_MANAGER)){
//			订单 0=营销员，1=经理，2=营销管理员，3=财务专员，4=总裁，5=技术总监，6部分分配，7全部分配
//			变更 流程状态 0=营销员，1=营销经理，2=营销管理员，3=技术员，4=技术经理，5=技术总监，6=财务专员，7=财务总监，8=总裁，9=董事长
			updateSalesmanManagerExamine(ad);
		}else if (roleType.equals(AFTConstants.FINANCE)){
			updateFinanceExamine(ad.getId());
		}else if (roleType.equals(AFTConstants.TECH)) {
			newOrderChangeMapper.updateExamineById(ad.getId(), OrderChangeProcess.JSY.getCode());
		}else if (roleType.equals(AFTConstants.TECH_MANAGER)) {
			newOrderChangeMapper.updateExamineById(ad.getId(), OrderChangeProcess.JSJL.getCode());
		}else if (roleType.equals(AFTConstants.TECH_ADMIN)) {
			tOrderNewMapper.updateExamineById(null, ProcessStatus.YPZXSGLY.getCode());
			newOrderChangeMapper.updateExamineById(null, OrderChangeProcess.JSZJ.getCode());
		}else if (roleType.equals(AFTConstants.FINANCE_ADMIN)) {
			newOrderChangeMapper.updateExamineById(null, OrderChangeProcess.CWZJ.getCode());
		}
	}

	private void updateSalesmanExamine(String id) {
		tOrderNewMapper.updateExamineById(id,ProcessStatus.YPYXY.getCode());
		newOrderChangeMapper.updateExamineById(id,OrderChangeProcess.YXY.getCode());
	}

	private void updateSalesmanAdminExamine(String id) {
		tOrderNewMapper.updateExamineById(id,ProcessStatus.YPYXGLY.getCode());
		newOrderChangeMapper.updateExamineById(id,OrderChangeProcess.YXGLY.getCode());
	}

	private void updateSalesmanManagerExamine(Admin ad) {
		updateSalesmanManagerExamine(ad.getId());
	}

	private void updateSalesmanManagerExamine(String id) {
		tOrderNewMapper.updateExamineById(id, ProcessStatus.YPYXJL.getCode());
		newOrderChangeMapper.updateExamineById(id, OrderChangeProcess.YXJL.getCode());
	}

	public void updateFinanceExamine(String id) {
		tOrderNewMapper.updateExamineById(id,ProcessStatus.YPCW_JSZJ.getCode());
		newOrderChangeMapper.updateExamineById(id,OrderChangeProcess.CWZY.getCode());
	}





	public void financeCoutSwitch(List<String> aids) {
		for (String aid : aids) {
			List<FinanceCount> list=new ArrayList<>();
			financeCountRestart(aid,list);
			financeCountMapper.deleteByAid(aid);
			listBatches(list);
		}
	}

	public void financeCoutSwitch(String aid) {
		List<FinanceCount> list=new ArrayList<>();
		financeCountRestart(aid,list);
		financeCountMapper.deleteByAid(aid);
		listBatches(list);
	}

	private void listBatches(List<FinanceCount> list) {
		List<FinanceCount> addList=new ArrayList<>();
		for (int i = 0; i <list.size(); i++) {
			FinanceCount financeCount = list.get(i);
			FinanceCount newFc=FinanceCount.initialization(financeCount);
			addList.add(newFc);
			if (addList.size()==50||i==list.size()-1){
				financeCountMapper.insetBatch(addList);
				addList.clear();
				try {
					Thread.sleep(500);
				} catch (InterruptedException exception) {
					exception.printStackTrace();
				}
			}
		}
	}

	private void financeCountRestart(String financeId, List<FinanceCount> list) {
		List<FinanceCount> aList=new ArrayList<>();
		List<FinanceCount> orderList = tOrderNewMapper.selectCountByFinance(financeId);
		if (!orderList.isEmpty()){
			aList.addAll(orderList);
		}
		List<FinanceCount> expenseList = expenseAccountMapper.selectCountByFinance(financeId);
		pushFinanceList(aList, expenseList,0);
		List<FinanceCount> invoiceList =tOrderInvoiceMapper.selectCountByFinance(financeId);
		pushFinanceList(aList, invoiceList,1);
		List<FinanceCount> memberList =tTaskMemberMapper.selectCountByFinance(financeId);
		pushFinanceList(aList, memberList,2);
		List<FinanceCount> paymentList =tOrderPaymentMapper.selectCountByFinance(financeId);
		pushFinanceList(aList, paymentList,3);
		if (!aList.isEmpty()){
			list.addAll(aList);
		}
	}


	/**
	 *
	 * @param list
	 * @param minList
	 * @param type
	 */
	private void pushFinanceList(List<FinanceCount> list, List<FinanceCount> minList,Integer type) {
		if (!minList.isEmpty()){
			for (FinanceCount expense : minList) {
				boolean flag=true;
				for (FinanceCount e : list) {
					if (e.getDateTime().getTime()==expense.getDateTime().getTime()){
						if (type==0){
							e.setExpenseCount(expense.getExpenseCount());
							e.setExpenseUnauditedCount(expense.getExpenseUnauditedCount());
						}else if (type==1){
							e.setInvoiceCount(expense.getInvoiceCount());
							e.setInvoiceUnauditedCount(expense.getInvoiceUnauditedCount());
						}else if (type==2){
							e.setMemberCount(expense.getMemberCount());
							e.setMemberUnauditedCount(expense.getMemberUnauditedCount());
						}else if (type==3){
							e.setPaymentCount(expense.getPaymentCount());
							e.setPaymentUnauditedCount(expense.getPaymentUnauditedCount());
						}
						flag=false;
					}
				}
				if (flag){
					list.add(expense);
				}
			}
		}
	}




	public void sendCarbonCopyWeChat( String publicCarbonCopy,Integer id, String name, String startTime, String endTime, String typeName, String plan) {
		Admin admin = adminMapper.selectById(publicCarbonCopy);
		weChatUtils.addSendCopyNotice(admin.getOpenId(), id, name, startTime, endTime, typeName, plan);
	}
	public void updateAdminByAid(String aid,String aid2) {
		updateAdminByAid(aid);
		updateAdminByAid(aid2);
	}

	public void updateAdminByAid(String aid) {
		List<TOrderTaskBo> tOrderTaskBos = tOrderTaskMapper.selectAdminTaskByAid(aid);

		int htSatCount = 0,htSatScoreCount = 0,htSatNotScoreCount = 0,
				memberCount=0,memberScoreCount = 0,memberNotScoreCount = 0;
		BigDecimal ht_satSum=new BigDecimal(0);
		BigDecimal hySum=new BigDecimal(0);
		for (TOrderTaskBo tOrderTaskBo : tOrderTaskBos) {
			if (aid ==null) aid =tOrderTaskBo.getTaskReceiver();
			if (tOrderTaskBo.getcSort()==3||tOrderTaskBo.getcSort()==9){
				htSatCount++;
				if (tOrderTaskBo.getScoreStatus()==1){
					htSatNotScoreCount++;
				}else if (tOrderTaskBo.getScoreStatus()==2){
					htSatScoreCount++;
					ht_satSum=ht_satSum.add(new BigDecimal(tOrderTaskBo.getScoreNumber()));
				}

			}else  if (tOrderTaskBo.getcSort()==6) {
				memberCount++;
				if (tOrderTaskBo.getScoreStatus()==1){
					memberNotScoreCount++;
				}else if (tOrderTaskBo.getScoreStatus()==2){
					memberScoreCount++;
					hySum=hySum.add(new BigDecimal(tOrderTaskBo.getScoreNumber()));
				}

			}
		}
		BigDecimal htSatScoreAverage = BigDecimal.ZERO;
		BigDecimal memberScoreAverage = BigDecimal.ZERO;
		if (htSatScoreCount>0)htSatScoreAverage=ht_satSum.divide(new BigDecimal(htSatScoreCount),2, RoundingMode.HALF_UP);
		if (memberScoreCount>0)memberScoreAverage=hySum.divide(new BigDecimal(memberScoreCount),2, RoundingMode.HALF_UP);
		AdminProjectStatistics adminProjectStatistics = adminProjectStatisticsMapper.queryByAid(aid);
		AdminProjectStatistics aps=new AdminProjectStatistics();
		aps.setAid(aid);
		aps.setHtSatCount(htSatCount);
		aps.setHtSatScoreAverage(htSatScoreAverage.doubleValue());
		aps.setHtSatNotScoreCount(htSatNotScoreCount);
		aps.setHtSatScoreCount(htSatScoreCount);
		aps.setMemberScoreAverage(memberScoreAverage.doubleValue());
		aps.setMemberScoreCount(memberScoreCount);
		aps.setMemberNotScoreCount(memberNotScoreCount);
		aps.setMemberCount(memberCount);
		if (adminProjectStatistics==null){
			adminProjectStatisticsMapper.insert(aps);
		}else {
			aps.setId(adminProjectStatistics.getId());
			adminProjectStatisticsMapper.update(aps);
		}
	}


}
