package com.goafanti.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.goafanti.admin.service.DepartmentService;
import com.goafanti.business.bo.InputRestrictProject;
import com.goafanti.common.bo.Error;
import com.goafanti.common.bo.*;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.ChannelStatus;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.enums.NoticeTypes;
import com.goafanti.common.enums.OrderLogProcess;
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.LoggerUtils;
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.order.bo.*;
import com.goafanti.order.controller.InputTaskStopLog;
import com.goafanti.order.enums.*;
import com.goafanti.order.service.OrderNewService;
import com.goafanti.order.service.OrderProjectService;
import com.goafanti.order.service.TaskScoreService;
import com.goafanti.organization.bo.OrganizationListOut;
import com.goafanti.organization.bo.OutPaymentNode;
import com.goafanti.techproject.enums.TaskState;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderProjectServiceImpl extends BaseMybatisDao<TOrderTaskMapper> implements OrderProjectService {
	@Autowired
	private TOrderTaskMapper tOrderTaskMapper;
	@Autowired
	private TOrderNewMapper	tOrderNewMapper;
	@Autowired
	private TTaskHoursMapper	tTaskHoursMapper;
	@Autowired
	private TOrderBonusMapper 	tOrderBonusMapper;
	@Autowired
	private TTaskLogMapper	tTaskLogMapper;
	@Autowired
	private TOrderLogMapper	tOrderLogMapper;
	@Autowired
	private TaskProgressMapper	taskProgressMapper;
	@Autowired
	private TaskProgressLogMapper	taskProgressLogMapper;
	@Autowired
	private OrganizationContactBookMapper	organizationContactBookMapper;
	@Autowired
	private OrganizationIdentityMapper	 organizationIdentityMapper;
	@Autowired
	private TaskLogMapper	taskLogMapper;
	@Autowired
	private OrderNewService	orderNewService;
	@Autowired
	private TaskHoursCountMapper	taskHoursCountMapper;
	@Autowired
	private AdminMapper	adminMapper;
	@Autowired
	private BusinessProjectMapper	businessProjectMapper;
	@Autowired
	private NewOrderDunMapper	newOrderDunMapper;
	@Autowired
	private DepartmentService	departmentService;
	@Autowired
	private TArrearsDunMapper	tArrearsDunMapper;
	@Autowired
	private PaymentNodeMapper	paymentNodeMapper;
	@Autowired
	private TTaskMidMapper	tTaskMidMapper;
	@Autowired
	private UserMapper	userMapper;
	@Autowired
	private UserLockReleaseMapper	userLockReleaseMapper;
	@Autowired
	private UserBusinessMapper	userBusinessMapper;
	@Autowired
	private UserChannelMapper	userChannelMapper;
	@Autowired
	private TaskAttributionLogMapper	taskAttributionLogMapper;
	@Autowired
	private ProjcetCheckLogMapper	projcetCheckLogMapper;
	@Autowired
	private TOrderPaymentMapper	tOrderPaymentMapper;
	@Autowired
	private PublicReleaseMapper	publicReleaseMapper;
	@Autowired
	private MemberLogMapper memberLogMapper;
	@Autowired
	private UserMidMapper userMidMapper;
	@Autowired
	private AsyncUtils	asyncUtils;
	@Autowired
	private TTaskMemberMapper tTaskMemberMapper;
	@Autowired
	private TOrderMidMapper	tOrderMidMapper;
	@Autowired
	private OrderExamineMapper orderExamineMapper;
	@Autowired
	private NewOrderChangeMapper newOrderChangeMapper;
	@Autowired
	private TaskStopMapper taskStopMapper;
	@Autowired
	private TaskStopLogMapper taskStopLogMapper;
	@Autowired
	private TaskTimeMapper taskTimeMapper;
	@Autowired
	private FinanceCountMapper financeCountMapper;
	@Autowired
	private TOrderExamineMapper tOrderExamineMapper;
	@Autowired
	private RestrictProjectMapper restrictProjectMapper;
	@Autowired
	private UserTransferLogMapper userTransferLogMapper;
	@Autowired
	private TaskScoreService taskScoreService;
	@Autowired
	private ProjectDistributionAsyncService projectDistributionAsyncService;




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

	Logger							logger	= LoggerFactory.getLogger(OrderProjectServiceImpl.class);

	@Override
	@Transactional
	public int updateProjectDistribution(Integer taskId, String taskReceiverId,String remarks,Integer type) {
		TOrderTask t=tOrderTaskMapper.queryById(taskId);
		TOrderNew tn=checkDeleteSign(t.getOrderNo());
		Date date=new Date();
		t.setTaskStatus(TaskState.DISTRIBUTION.getCode());
		t.setTaskAllocator(TokenManager.getAdminId());
		t.setTaskReceiver(taskReceiverId);
		t.setTaskDistributionTime(date);
		Admin a=adminMapper.selectById(taskReceiverId);
		insetLog(taskId, taskReceiverId);
		addtaskAttributionLog(taskId,taskReceiverId,remarks,type,date);
		if (a==null||a.getId()==null) {
			throw  new BusinessException(new Error("分配人员不存在！","分配人员不存在！"));
		}
		if (type ==0) {
			addOrderLog(t.getOrderNo(), OrderLogProcess.XMZJPD.getCode(), remarks);
			t.setManagerId(taskReceiverId);
			t.setConsultantId(null);
		}else if(type ==1) {
			t.setManagerId(taskReceiverId);
			t.setConsultantId(null);
		}else if(type ==2) {
			addOrderLog(t.getOrderNo(), OrderLogProcess.XMJLPD.getCode(), remarks);
			t.setConsultantId(taskReceiverId);
		}else if(type ==3) {
			t.setConsultantId(taskReceiverId);
		}else if(type ==4) {
			t.setConsultantId(null);
			t.setManagerId(taskReceiverId);
		}
		t.setReceiverName(a.getName());
		tOrderTaskMapper.update(t);
		projectDistributionAsyncService.pushProjectDistribution(taskId, taskReceiverId, type, t, tn, date, a);
		return 1;
	}

	private void pushProjectDistribution(Integer taskId, String taskReceiverId, String remarks, Integer type, TOrderTask t, TOrderNew tn, Date date, Admin a) {
		if (type ==0) {
			addOrderLog(t.getOrderNo(), OrderLogProcess.XMZJPD.getCode(), remarks);
			t.setManagerId(taskReceiverId);
			t.setConsultantId(null);
			//设置催款触发
			orderNewService.pushOrderDun(tn);
			//未锁定客户就锁定客户
			pushUser(t, tn, date);
			//处理客户已派项目
			projectDistributionPushUserMid(tn);
			//处理限定项目状态
			BusinessProject businessProject = businessProjectMapper.selectById(t.getCommodityId());
			if (businessProject.getRestrictStatus()==1){
				RestrictProject use = restrictProjectMapper.selectByParam(new InputRestrictProject(tn.getBuyerId(), null, t.getCommodityId()));
				if (use!=null){
					RestrictProject newRP=new RestrictProject();
					newRP.setId(use.getId());
					newRP.setLockTime(date);
					newRP.setType(2);
					if (!use.getAid().equals(tn.getSalesmanId())){
						newRP.setAid(tn.getSalesmanId());
					}
					restrictProjectMapper.updateByPrimaryKeySelective(newRP);
					UserTransferLog log=new UserTransferLog();
					log.setAid(use.getAid());
					log.setUid(use.getUid());
					log.setPid(use.getPid());
					log.setType(20);
					log.setRemarks("签单触发锁定限时项目");
					userTransferLogMapper.insertSelective(log);
				} else {
					RestrictProject newRP=new RestrictProject();
					newRP.setUid(tn.getBuyerId());
					newRP.setAid(tn.getSalesmanId());
					newRP.setPid(t.getCommodityId());
					newRP.setLockTime(date);
					newRP.setType(2);
					restrictProjectMapper.insertSelective(newRP);
				}
			}
		}else if(type ==1) {
			t.setManagerId(taskReceiverId);
			t.setConsultantId(null);
		}else if(type ==2) {
			addOrderLog(t.getOrderNo(), OrderLogProcess.XMJLPD.getCode(), remarks);
			t.setConsultantId(taskReceiverId);
		}else if(type ==3) {
			t.setConsultantId(taskReceiverId);
		}else if(type ==4) {
			t.setConsultantId(null);
			t.setManagerId(taskReceiverId);
		}
		t.setReceiverName(a.getName());
		tOrderTaskMapper.update(t);
		List<String> aids = new ArrayList<>();
		aids.add(taskReceiverId);
		TOrderNewBo order = tOrderNewMapper.getSaleIdByOno(t.getOrderNo());
		orderNewService.pushGeneralSendNoticeAndEmail(aids, NoticeStatus.ORDER_TASK_TO.getCode(),order, TokenManager.getAdminId(),0, taskId);
		//处理项目统计表
		TTaskMid dtails = tTaskMidMapper.getDtails(taskId);
		if (type ==0){
			dtails.setDispatchCount(t.getCommodityQuantity());
			dtails.setStockCount(t.getCommodityQuantity());
		}
		//如果不相等就切换
		if (!dtails.getDutyDep().equals(a.getDepartmentId())){
			dtails.setDutyDep(a.getDepartmentId());
		}
		tTaskMidMapper.updateByTid(dtails);
		//处理订单信息
		checkProjiectAllocation(t.getOrderNo());
		pushTaskChange(TokenManager.getAdminId(), taskReceiverId, type, t.getOrderNo());
		//派单后设置用户客户统计
		if (type ==0){
			asyncUtils.updateAdminByAid(taskReceiverId);
		}else {
			asyncUtils.updateAdminByAid(TokenManager.getAdminId(), taskReceiverId);
		}
	}

	/**
	 *
	 * @param aid 操作者
	 * @param taskReceiverId 接收方
	 * @param type type – 0管理员派单 1经理转交 2经理派单 3咨询师转交 4回退
	 */
	private void pushTaskChange(String aid, String taskReceiverId,Integer type,String orderNo) {
		if (type==1||type==3){
			orderExamineMapper.updateDimissionTransfer(aid,taskReceiverId,null,orderNo);
		}else if (type==2){
			OrderExamine o=new OrderExamine();
			o.setAid(taskReceiverId);
			o.setOrderNo(orderNo);
			o.setCreateTime(new Date());
			o.setType(0);//咨询师经理
			o.setStatus(0);//正常
			orderExamineMapper.insertSelective(o);
		}else if (type==4){
			orderExamineMapper.updateBack(aid,taskReceiverId,orderNo);
		}
		newOrderChangeMapper.updateTaskExamineName(aid,taskReceiverId,OrderChangeProcess.JSY.getCode());
		newOrderChangeMapper.updateTaskExamineName(aid,taskReceiverId,OrderChangeProcess.JSJL.getCode());
	}

	private void projectDistributionPushUserMid(TOrderNew tn) {
		if (Objects.equals(tn.getProcessStatus(), ProcessStatus.YPZXSGLY.getCode())){
			UserMid um=new UserMid();
			String taskNames=userMidMapper.getUserTaskNames(tn.getBuyerId());
			UserMid use=userMidMapper.getUserDtails(tn.getBuyerId());
			um.setUid(tn.getBuyerId());
			um.setTaskNames(taskNames);
			um.setLastSigningTime(tn.getCreateTime());
			if(tn.getSalesType()!=null){
				um.setLastSalesType(tn.getSalesType());
			}
			BigDecimal signAmount;
			int signNumber;
			if (use!=null){
				if (use.getFirstSigningTime() != null) {
					um.setFirstSigningTime(use.getFirstSigningTime()); }
				if (use.getSignAmount() != null) {
					signAmount=use.getSignAmount().add(tn.getTotalAmount());
				}else{
					signAmount=new BigDecimal(0).add(tn.getTotalAmount());

				}
				if (use.getSignNumber()!=null){
					signNumber=use.getSignNumber()+1;
				}else {
					signNumber=1;
				}
			}else {
				signAmount=new BigDecimal(0).add(tn.getTotalAmount());
				signNumber=1;
			}
			um.setSignAmount(signAmount);
			um.setSignNumber(signNumber);
			userMidMapper.updateByUid(um);
		}
	}


	/**
	 * 	推动客户、业务渠道的锁定
	 */
	private void pushUser(TOrderTask t, TOrderNew tn, Date date) {
		if (userMapper.checkLock(tn.getBuyerId())<1) {
			User user = userMapper.queryById(tn.getBuyerId());
			//新增如果不是渠道才转换时间和改成签单
			if (user!=null&&user.getNewChannel()!=1){
				//签单改成刷新客户跟进时间
				userLockReleaseMapper.updateByAidAndUid(tn.getBuyerId());
				userMapper.updateShareType(tn.getBuyerId(),tn.getSalesmanId());
			}
		}
		//判定用户最后签单时间
		pushSignTime(tn);
		//未锁定业务就锁定业务
		if (userLockReleaseMapper.checkLock(tn.getSalesmanId(),tn.getBuyerId(),t.getCommodityId())<1) {
			UserLockRelease ulr=new UserLockRelease();
			ulr.setId(UUID.randomUUID().toString());
			ulr.setBusinessProjectId(t.getCommodityId());
			ulr.setType(1);
			ulr.setUid(tn.getBuyerId());
			ulr.setAid(tn.getSalesmanId());
			ulr.setStatus(0);
			ulr.setLockTime(date);
			userLockReleaseMapper.insertSelective(ulr);
		}
		int i = userBusinessMapper.judgeBusiness(tn.getBuyerId(), t.getCommodityId(), tn.getSalesmanId());
		UserBusiness ub=new UserBusiness();
		ub.setId(UUID.randomUUID().toString());
		ub.setUid(tn.getBuyerId());
		ub.setAid(tn.getSalesmanId());
		ub.setFollowSituation(5);
		ub.setCustomerStatus(4);
		ub.setUpdateTime(date);
		ub.setRemarks("派单自动锁定客户");
		ub.setBusinessProjectId(t.getCommodityId());
		if (i>0){
			userBusinessMapper.updateByPrimaryKeySelective(ub);
		}else {
			ub.setCreateTime(date);
			userBusinessMapper.insertSelective(ub);
		}
			//如果是渠道客户更新渠道表
			UserChannel uc=new UserChannel();
			uc.setUid(tn.getBuyerId());
			uc.setStatus(ChannelStatus.YQD.getCode());
			uc.setSignTime(date);
			userChannelMapper.updateByUid(uc);
			//标记最新的打卡
			publicReleaseMapper.updateSignByAidAndUid(tn.getBuyerId(),tn.getSalesmanId());
	}

	private void pushSignTime(TOrderNew tn) {
		List<TOrderNewBo> tOrderNewBos = tOrderNewMapper.selectByuidandAid(tn.getBuyerId(), tn.getSalesmanId());
		Date lastSigningTime= tn.getSignTime();
		if (!tOrderNewBos.isEmpty()){
			for (TOrderNewBo e : tOrderNewBos) {
				if(e.getSignTime()!=null){
					if (e.getSignTime().getTime()>lastSigningTime.getTime()){
						lastSigningTime = e.getSignTime();
					}
				}
			}
		}
		User u=new User();
		u.setId(tn.getBuyerId());
		u.setSignTime(lastSigningTime);
		userMapper.update(u);
	}


	private void addtaskAttributionLog(Integer taskId, String taskReceiverId, String remarks, Integer type, Date date) {
		TaskAttributionLog log=new TaskAttributionLog(taskId,TokenManager.getAdminId(),taskReceiverId,remarks,type,date);
		taskAttributionLogMapper.insertSelective(log);

	}



	public TOrderNew checkDeleteSign(String orderNo) {
		TOrderNew t=tOrderNewMapper.queryById(orderNo);
		if(t.getDeleteSign()==2||t.getDeleteSign()==3) throw new BusinessException(new Error(ErrorConstants.ORDER_ALREADY_REVOKE, t.getOrderNo(),""));
		return t;
	}
	public void addOrderLog(String orderNo, Integer code,String remarks) {
		TOrderLog tl=new TOrderLog();
		tl.setOrderNo(orderNo);
		tl.setProcess(code);
		tl.setAid(TokenManager.getAdminId());
		if(null!=remarks)tl.setRemarks(remarks);
		tOrderLogMapper.insertSelective(tl);

	}
	public void checkProjiectAllocation(String  orderNo) {
		TOrderNew tNew=new TOrderNew();
		tNew.setOrderNo(orderNo);
		tNew.setProcessStatus(getOrderProcessStatus(orderNo));
		tNew.setExamineName("");
		tOrderNewMapper.update(tNew);
		updateMidServiceProject(orderNo);
	}

	@Override
	public Integer getOrderProcessStatus(String  orderNo) {
		Integer processStatus=ProcessStatus.YPZXSGLY.getCode();
		List<TOrderTaskBo> taskBos=tOrderTaskMapper.selectOrderTaskAll(orderNo,4);
		int i=0;
		for (TOrderTaskBo to : taskBos) {
			if (to.getTaskStatus()>TaskState.UN_DISTRIBUTION.getCode()&&to.getTaskStatus()<TaskState.INVALID.getCode()) {
				i++;
			}
		}
		if (i==taskBos.size()) {
			processStatus=ProcessStatus.YQBFPZXSGLY.getCode();
		}else if(i>0&&i<taskBos.size()){
			processStatus=ProcessStatus.YBFPZXSGLY.getCode();
		}else if(i==0){
			processStatus=ProcessStatus.YPZXSGLY.getCode();
		}
		return processStatus;
	}




	private void insetLog(Integer taskId, String taskReceiverId) {
		TTaskLog tl=new TTaskLog();
		tl.setCreateTime(new Date());
		tl.setTaskId(taskId);
		tl.setTaskAllocator(TokenManager.getAdminId());
		tl.setTaskReceiver(taskReceiverId);
		tTaskLogMapper.insertSelective(tl);
	}

	@Override
	public Pagination<TOrderTaskListBo> orderTaskList(inuptTaskListBo ib) {
		Map<String, Object> params = new HashMap<>();
		if(ib.getPageSize()==null||ib.getPageSize()<0)ib.setPageSize(10);
		if(ib.getPageNo()==null||ib.getPageNo()<0)ib.setPageNo(1);
		params.put("outsource", ib.getOutsource()==null?0:ib.getOutsource());
		if (null!=ib.getSpecially()) params.put("specially", ib.getSpecially());
		if (StringUtils.isNotBlank(ib.getName())) params.put("name", ib.getName());
		if (StringUtils.isNotBlank(ib.getProjectName())) params.put("projectName", ib.getProjectName());
		if (StringUtils.isNotBlank(ib.getDeps())) params.put("deps", departmentService.parseArray(ib.getDeps()));
		if (StringUtils.isNotBlank(ib.getOrderNo())) params.put("orderNo", ib.getOrderNo());
		if (StringUtils.isNotBlank(ib.getContractNo())) params.put("contractNo", ib.getContractNo());
		if (ib.getProjectStatus() !=null ) params.put("projectStatus", ib.getProjectStatus());
		if (StringUtils.isNotBlank(ib.getTaskId())) params.put("taskId", ib.getTaskId());
		if (ib.getApproval() !=null) params.put("approval", ib.getApproval());
		if (StringUtils.isNotBlank(ib.getAdminName())) params.put("adminName", ib.getAdminName());
		if (StringUtils.isNotBlank(ib.getStartTime())) params.put("startTime", ib.getStartTime());
		if (StringUtils.isNotBlank(ib.getEndTime())) params.put("endTime", ib.getEndTime());
		if (null != ib.getTaskStatus()) params.put("taskStatus", ib.getTaskStatus());
		if (ib.getOutsourceStatus() !=null) params.put("outsourceStatus", ib.getOutsourceStatus());
		if (ib.getMemberProjectType()!=null) params.put("memberProjectType", ib.getMemberProjectType());
		if (ib.getCid() !=null) params.put("cid", ib.getCid());
		if (StringUtils.isNotBlank(ib.getType())){
			String[] split = ib.getType().split(",");
			params.put("type", split);
		}
		List<String> fids=new ArrayList<>();
		 if (TokenManager.hasRole(AFTConstants.TECH)||TokenManager.hasRole(AFTConstants.TECH_MANAGER)){
			params.put("role", 0);
			params.put("aid", TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
		}else if (TokenManager.hasRole(AFTConstants.FINANCE_ADMIN) ||TokenManager.hasRole(AFTConstants.SUPERADMIN)||
				TokenManager.hasRole(AFTConstants.CED)||TokenManager.hasRole(AFTConstants.APPROVAL_DECISION)||
				TokenManager.hasRole(AFTConstants.VICE_CEO)) {
			params.put("role", 2);
		}else if (TokenManager.hasRole(AFTConstants.FINANCE_MANAGER)) {
			params.put("role", 1);
			fids =adminMapper.selectBySuperId(TokenManager.getAdminId());
			params.put("fids",fids);
		}else if (TokenManager.hasRole(AFTConstants.FINANCE)) {
			params.put("role", 1);
			 fids.add(TokenManager.getAdminId());
			 params.put("fids",fids);
		}
		Pagination<TOrderTaskListBo> p = (Pagination<TOrderTaskListBo>)findPagePlus("selectOrderTaskListByPage", "selectOrderTaskListCount",
				"selectOrderTaskListSum",
				params, ib.getPageNo(), ib.getPageSize());
		List<TOrderTaskListBo> list=(List<TOrderTaskListBo>) p.getList();
		for (TOrderTaskListBo t : list) {
			if(t.getSplitStatus()==1) {
				List<TOrderTaskListBo> l=splitProjectList(t.getId(),1);
				t.setSplitList(l);
			}
		}
		return p;
	}

	@Override
	public TOrderTaskDetailBo orderTaskDetail(Integer id) {
		TOrderTaskDetailBo t=tOrderTaskMapper.getOrderTaskDetail(id);
		TaskTime tt=new TaskTime();
		tt.setTid(t.getId());
		tt.setProjectStatus(t.getProjectStatus());
		List<TaskTime> taskTimes = taskTimeMapper.selectByTidAndProject(tt);
		Map<String,Object> map=new HashMap<>();
		for (TaskTime e : taskTimes) {
			Map<String,Object> param=new HashMap<>();
			if (e.getDateTime()!=null){
				param.put("date",DateUtils.formatDate(e.getDateTime(),AFTConstants.YYYYMMDD));
			}
			param.put("title",NewProjectStatus.getValueByCode(e.getProjectStatus()));
			map.put(e.getProjectStatus().toString(),param);
		}
		t.setTimeRecord(JSON.toJSONString(map));
		if (TokenManager.hasRole(AFTConstants.SUPERADMIN)||TokenManager.hasRole(AFTConstants.APPROVAL_DECISION)
				||TokenManager.hasRole(AFTConstants.CUSTOMER_SERVICE)
					|| Objects.equals(TokenManager.getAdminId(), t.getTaskReceiver())) {
			return t;
		}else {
			t.setContacts("***");
			t.setContactMobile("***");
			t.setLegalPerson("***");
			t.setLegalPersonTel("***");
			t.setOutsourceName("****");
			t.setOutsourcePrice("****");
			t.setDeclareUser("****");
			t.setDeclarePwd("****");
			t.setCertificateNumber("****");
			return t;
		}


	}

	@Override
	@Transactional
	public int updateOrderTask(TOrderTaskDetailBo t) {
		TOrderTask task=new TOrderTask();
		TOrderNew tn=checkDeleteSign(t.getOrderNo());
		task.setAttachmentUrl(t.getAttachmentUrl());
		task.setId(Integer.valueOf(t.getId()));
		task.setTaskComment(t.getTaskComment());
		task.setCertificateNumber(t.getCertificateNumber());
		task.setStatus(t.getStatus());
		task.setFormRetrieve(t.getFormRetrieve());
		task.setTaskRefund(t.getTaskRefund());
		task.setRefundContent(t.getRefundContent());
		task.setRetrieveContent(t.getRetrieveContent());
		task.setDeclareUser(t.getDeclareUser());
		task.setDeclarePwd(t.getDeclarePwd());
		task.setArrivalMoney(t.getArrivalMoney());
		task.setSetUpAmount(t.getSetUpAmount());
		task.setOutsourceName(t.getOutsourceName());
		task.setDeclarationBatch(t.getDeclarationBatch());
		task.setSetUpStatus(t.getSetUpStatus());
		if(t.getSetUpTime()!=null)task.setSetUpTime(DateUtils.StringToDate(t.getSetUpTime(), AFTConstants.YYYYMMDD));
		task.setSpotCheckStatus(t.getSpotCheckStatus());
		task.setHighTechStatus(t.getHighTechStatus());
		task.setSpecialComment(t.getSpecialComment());
		if(StringUtils.isNotBlank(t.getOutsourcePrice()))task.setOutsourcePrice(new BigDecimal(t.getOutsourcePrice()));
		if (t.getIfCertificationFee()!=null&&t.getIfCertificationFee()==1) {
			task.setCertificationCorporate(t.getCertificationCorporate());
			task.setCertificationFee(t.getCertificationFee());
		}

		//根据修改的修改订单法人与联系人
		if(StringUtils.isNotEmpty(t.getContacts()))tn.setContacts(t.getContacts());
		if(StringUtils.isNotEmpty(t.getContactMobile()))	tn.setContactMobile(t.getContactMobile());
		if(StringUtils.isNotEmpty(t.getLegalPerson()))tn.setLegalPerson(t.getLegalPerson());
		if(StringUtils.isNotEmpty(t.getLegalPersonTel()))tn.setLegalPersonTel(t.getLegalPersonTel());
		tOrderNewMapper.update(tn);
		//修改公司地址信息
		if (null!=t.getLocationProvince()||null!=t.getLocationArea()||null!=t.getLocationCity()||null!=t.getPostalAddress()) {
			OrganizationIdentity org=new OrganizationIdentity();
			org.setUid(tn.getBuyerId());
			org.setLocationProvince(t.getLocationProvince());
			org.setLocationArea(t.getLocationArea());
			org.setLocationCity(t.getLocationCity());
			org.setPostalAddress(t.getPostalAddress());
			organizationIdentityMapper.updateServiceByUid(org);
		}

		//修改公司联系人
		int adcount=organizationContactBookMapper.checkContacts(tn.getBuyerId(), t.getContactMobile(),tn.getSalesmanId());
		if (StringUtils.isNotBlank(t.getContacts())&&StringUtils.isNotBlank(t.getContactMobile())&&adcount<1) {
			OrganizationContactBook contactBook=new OrganizationContactBook();
			contactBook.setId(UUID.randomUUID().toString());
			contactBook.setAid(tn.getSalesmanId());
			contactBook.setUid(tn.getBuyerId());
			contactBook.setName(t.getContacts());
			contactBook.setMobile(t.getContactMobile());
			organizationContactBookMapper.insertSelective(contactBook);
		}
		//新增结算奖金信息
		checkSettlementAward(tn,task);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if(StringUtils.isNotBlank(t.getStartDate()))task.setTaskStartTime(sdf.parse(t.getStartDate()));
			if(StringUtils.isNotBlank(t.getEndDate()))task.setTaskEndTime(sdf.parse(t.getEndDate()));
			if(StringUtils.isNotBlank(t.getAcceptDate()))task.setAcceptTime(sdf.parse(t.getAcceptDate()));
			if(StringUtils.isNotBlank(t.getReviewDate()))task.setReviewTime(sdf.parse(t.getReviewDate()));
			if(StringUtils.isNotBlank(t.getPublicityDate()))task.setPublicityTime(sdf.parse(t.getPublicityDate()));
			if(StringUtils.isNotBlank(t.getLicenceDate()))task.setLicenceTime(sdf.parse(t.getLicenceDate()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		tOrderTaskMapper.update(task);
		//项目中间表修改
		if (t.getUrgentDay()!=null||t.getIfMaterial()!=null||t.getRejectCount()!=null||
				t.getAcceptCount()!=null||t.getAuthorizeCount()!=null||t.getSpotCheckStatus()!=null) {
			TTaskMid tm=new TTaskMid();
			tm.setTid(task.getId());
			if (t.getUrgentDay()!=null)tm.setUrgentDay(t.getUrgentDay());
			if (t.getIfMaterial()!=null)tm.setIfMaterial(t.getIfMaterial());
			if (t.getRejectCount()!=null)tm.setRejectCount(t.getRejectCount());
			if (t.getAcceptCount()!=null)tm.setAcceptCount(t.getAcceptCount());
			if (t.getAuthorizeCount()!=null)tm.setAuthorizeCount(t.getAuthorizeCount());
			if (t.getSpotCheckStatus()==1||t.getSpotCheckStatus()==2){
				tm.setSpotCheckCount(t.getCommodityQuantity());
				if (t.getSpotCheckStatus()==2){
					tm.setFailCount(t.getCommodityQuantity());
				}
			}
			tTaskMidMapper.updateByTid(tm);
		}
		TaskLog tl=new TaskLog();
		tl.setCreateTime(new Date());
		tl.setTaskId(t.getId());
		tl.setAid(TokenManager.getAdminId());
		//项目触发发催款

		return 1;
	}


	public int updateProjectStatus(UpdateProjectStatusBo b) {
		TOrderTask t=new TOrderTask();
		t.setId(b.getTid());
		t.setProjectStatus(b.getProjectStatus());
		t.setTimeRecord(b.getTimeRecord());
		t.setCertificateNumber(b.getCertificateNumber());
		if(b.getSetUpAmount()!=null)t.setSetUpAmount(new BigDecimal(b.getSetUpAmount()));
		if (b.getPubicityUrl()!=null)t.setPubicityUrl(b.getPubicityUrl());
		TOrderTask task2=tOrderTaskMapper.queryById(b.getTid());//查询出项目信息
		t.setTaskDistributionTime(task2.getTaskDistributionTime());
		if(!Objects.equals(b.getProjectStatus(), task2.getProjectStatus())
				||!b.getTimeRecord().equals(task2.getTimeRecord())){
				TTaskMid taskMid = new TTaskMid();
				taskMid.setTid(b.getTid());
			if(Objects.equals(b.getProjectStatus(), NewProjectStatus.YLX.getCode())
					|| Objects.equals(b.getProjectStatus(), NewProjectStatus.YNGS.getCode())){
				t.setSetUpStatus(1);
				taskMid.setSetUpCount(task2.getCommodityQuantity());
				if (Objects.equals(b.getProjectStatus(), NewProjectStatus.YNGS.getCode())){
					t.setIfPublicity(1);
					taskMid.setPromulgateCount(task2.getCommodityQuantity());
				}
			}else if (b.getProjectStatus().equals(NewProjectStatus.YWCXZ.getCode())||b.getProjectStatus().equals(NewProjectStatus.YXZ.getCode())||
					b.getProjectStatus().equals(NewProjectStatus.D1NWC.getCode())||b.getProjectStatus().equals(NewProjectStatus.D2NWC.getCode())||
					b.getProjectStatus().equals(NewProjectStatus.D3NWC.getCode())||b.getProjectStatus().equals(NewProjectStatus.QBWC.getCode())
			){
				//完成时通知客服
				completeSendCustomerService(b.getTid());
			}
			//大于3计做已完成 不计做库存
			if (b.getProjectStatus()>3){
				taskMid.setCompleteCount(task2.getCommodityQuantity());
				taskMid.setStockCount(0);
			}
			if (taskMid.getPromulgateCount()!=null||taskMid.getSetUpCount()!=null||
					taskMid.getCompleteCount()!=null ||taskMid.getStockCount()!=null){
				tTaskMidMapper.updateByTid(taskMid);
			}
			//做计时处理
			pushTaskTimes(t);
			tOrderTaskMapper.update(t);
			projectSplitPush(b.getTid(), b.getProjectStatus(),task2);
			pushTaskLog(b.getTid(), b.getProjectStatus());
			updateMidServiceProject(task2.getOrderNo());
			if (task2.getScoreStatus()==0){
				updateProjectCompleteDate(t);
			}
			asyncUtils.updateAdminByAid(task2.getTaskReceiver());
		}
		return 1;
	}

	private void pushTaskTimes(TOrderTask t) {
		Map<String,Object> map = JSON.parseObject(t.getTimeRecord(), Map.class);
		for (String key : map.keySet()) {
			Map map1 = JSON.parseObject(map.get(key).toString(), Map.class);
				TaskTime tt=new TaskTime();
				tt.setTid(t.getId());
				tt.setProjectStatus(Integer.valueOf(key));
			String date = map1.get("date").toString();
			tt.setDateTime(DateUtils.StringToDate(date,AFTConstants.YYYYMMDD));
			int i = taskTimeMapper.updateByTidAndProjectSelective(tt);
			if (i==0){
				taskTimeMapper.insertSelective(tt);
			}
		}
	}

	private void completeSendCustomerService(Integer id) {
		OrderOperator orderOperator = tOrderTaskMapper.selectAidByParam(id);
		String content=String.format("[%s]企业[%s]项目已完成，订单编号[%s]。",orderOperator.getBuyerName(),orderOperator.getProjectName(),orderOperator.getOrderNo());
		List<Admin> list =adminMapper.getAdminRoleTypeList(AFTConstants.CUSTOMER_SERVICE);
		List<Notice> notices=new ArrayList<>();
		for (Admin admin : list) {
			Notice notice=new Notice();
			notice.setId(UUID.randomUUID().toString());
			notice.setNoticeType(NoticeStatus.COMPLETES_PROJECT.getCode());
			notice.setType(NoticeTypes.getType(NoticeStatus.COMPLETES_PROJECT.getCode()));
			notice.setAid(admin.getId());
			notice.setCreateTime(new Date());
			notice.setContent(content);
			notice.setReaded(0);
			notices.add(notice);
		}
		asyncUtils.addNoticeBatch(notices);
	}


	/**
	 * 推动项目日志
	 * @param tid
	 * @param projectStatus
	 */
	private void pushTaskLog(Integer tid,Integer projectStatus) {
		TaskLog tl = new TaskLog();
		tl.setCreateTime(new Date());
		tl.setTaskId(tid);
		tl.setAid(TokenManager.getAdminId());
		StringBuffer s = new StringBuffer("项目状态修改为:");
		s.append(NewProjectStatus.getValueByCode(projectStatus));
		tl.setContent(s.toString());
		taskLogMapper.insertSelective(tl);
	}


	//推动项目计算及催款
	private void projectSplitPush(Integer tid, Integer projectStatus,TOrderTask task2) {
		//0否 1父拆分 2子拆分 如果没有拆分
		if (task2.getSplitStatus()==0) {
			pushOrderDunAndPaymentNode(tid,projectStatus,task2);
			//如果是子项目
		}else if (task2.getSplitStatus()==2){
			//查出父项目
			List<TOrderTaskListBo> list=tOrderTaskMapper.splitProjectList(task2.getSplitSuper(),null);
			//设置一个比较大的流程数字，然后取最小的
			Integer i=28;
			for (TOrderTaskListBo tt : list) {
				if (tt.getProjectStatus()<i) i=tt.getProjectStatus();
			}
			TOrderTask fatherTask=new TOrderTask();
			fatherTask.setId(task2.getSplitSuper());
			fatherTask.setProjectStatus(i);
			tOrderTaskMapper.update(fatherTask);
			TOrderTask task3=tOrderTaskMapper.queryById(task2.getSplitSuper());
			//设置父任务
			TOrderTaskDetailBo t2=new TOrderTaskDetailBo();
			t2.setOrderNo(task2.getOrderNo());
			t2.setId(task2.getSplitSuper());
			t2.setProjectStatus(task3.getProjectStatus());
			pushOrderDunAndPaymentNode(t2.getId(),t2.getProjectStatus(),task3);
		}

		if (task2.getSuperId()!=null) {//有父项目
			TOrderTask task3 =tOrderTaskMapper.selectBySuperId(task2.getSuperId());
			task3.setId(Integer.valueOf(task2.getSuperId()));
			task3.setSuperId(null);
			tOrderTaskMapper.update(task3);
			TOrderTask task4 = tOrderTaskMapper.queryById(Integer.valueOf(task2.getSuperId()));
			meanwhileUpdateOrder(task4);
		}else {
			meanwhileUpdateOrder(task2);
		}
	}

	/**
	 * 项目状态达到触发催款
	 * @param tid
	 * @param projectStatus
	 * @param task2
	 */
	private void pushOrderDunAndPaymentNode(Integer tid,Integer projectStatus,TOrderTask task2) {
		List<OutNewOrderDunBo> list=newOrderDunMapper.selectByTid(tid);
		for (OutNewOrderDunBo ob : list) {
			if (ob!=null) {
				boolean flag=false;
				if((ob.getProjectType()==OrderDunProjectType.CGZH.getCode()&&ob.getDunType()==2&&//成果转化 验收
						projectStatus==NewProjectStatus.YWCXZ.getCode()))flag=true;
				else if((ob.getProjectType()==OrderDunProjectType.COMMON.getCode()&&ob.getDunType()==2&&//通用 公示
						projectStatus==NewProjectStatus.YTJ.getCode()))flag=true;
				else if((ob.getProjectType()==OrderDunProjectType.COMMON.getCode()&&ob.getDunType()==3&&//通用 下证
						projectStatus==NewProjectStatus.YWCXZ.getCode()))flag=true;
				else if((ob.getProjectType()==OrderDunProjectType.KJXM.getCode()&&ob.getDunType()==2&&//科技项目 立项或者公示
						projectStatus==NewProjectStatus.YLX.getCode()))flag=true;
				else if((ob.getProjectType()==OrderDunProjectType.KJXM.getCode()&&ob.getDunType()==3&&//科技项目 拨款
						projectStatus==NewProjectStatus.LXYBK.getCode()))flag=true;
				else if((ob.getProjectType()==OrderDunProjectType.KJJR.getCode()&&ob.getDunType()==2&&//科技金融 拨款
						projectStatus==NewProjectStatus.YWCXZ.getCode()))flag=true;
				else if((ob.getProjectType()==OrderDunProjectType.RJKF.getCode()&&ob.getDunType()==2&&//软件开发 立项
						projectStatus==NewProjectStatus.YTJ.getCode()))flag=true;
				else if((ob.getProjectType()==OrderDunProjectType.RJKF.getCode()&&ob.getDunType()==3&&//软件开发 验收
						projectStatus==NewProjectStatus.YWCXZ.getCode()))flag=true;
				else if(ob.getProjectType()==OrderDunProjectType.ZSCQ.getCode()){//知识产权 公示 专利受理、转让（项目已提交），软著下证
					if(ob.getDunType()==3&&projectStatus==NewProjectStatus.YWCXZ.getCode()) {
						flag=true;
					}else if (ob.getDunType()==2) {
						BusinessProject bp=businessProjectMapper.selectById(task2.getCommodityId());
						if (bp.getType()==0&&projectStatus==NewProjectStatus.YWCXZ.getCode()) {
							flag=true;
						}
						if (bp.getType()==1&&projectStatus==NewProjectStatus.YTJ.getCode()) {
							flag=true;
						}
						if (bp.getType()==2&&projectStatus==NewProjectStatus.YWCXZ.getCode()) {
							flag=true;
						}

					}
				}else if(ob.getProjectType()==OrderDunProjectType.GX.getCode()) {
					if (ob.getDunType()==2&&projectStatus>=NewProjectStatus.YNGS.getCode()
							&&projectStatus<=NewProjectStatus.YXZ.getCode()) {
						flag=true;
					} else if (ob.getDunType()==3&&projectStatus==NewProjectStatus.YXZ.getCode()){
						flag=true;
					}
				}
					if(flag) {
					//如果启动催款，则新增欠款与应收款
						TOrderNew tn=tOrderNewMapper.queryById(task2.getOrderNo());
						ob.setStatus(1);
						ob.setStartTime(new Date());
						newOrderDunMapper.updateByPrimaryKeySelective(ob);
						TOrderMid tm=orderNewService.pushOrderMidDun(task2.getOrderNo(),tn.getSettlementAmount(),new Date());
						TArrearsDun td=new TArrearsDun();
						td.setOrderArrears(tm.getOrderArrears());
						td.setOrderReceivables(tm.getOrderReceivables());
						if (tArrearsDunMapper.checkOrderNo(task2.getOrderNo(),null)<1) {
							td.setOrderNo(task2.getOrderNo());
							tArrearsDunMapper.insertSelective(td);
						}else if(tArrearsDunMapper.checkOrderNo(task2.getOrderNo(),0)>0){
							Integer i=tArrearsDunMapper.selectByStatus(task2.getOrderNo(), 0);
							td.setId(i);
							tArrearsDunMapper.updateByPrimaryKeySelective(td);
						}
					orderNewService.addNewDunNoticAndSendEmail(task2.getOrderNo(),ob);

				}
			}
		}
		List<OutPaymentNode> list2=paymentNodeMapper.selectByTid(tid,0);
		for (OutPaymentNode op : list2) {
			if (op!=null) {
				boolean flag=false;
				if((op.getProjectType()==OrderDunProjectType.CGZH.getCode()&&op.getDunType()==2&&//成果转化 验收
						projectStatus==NewProjectStatus.YWCXZ.getCode()))flag=true;
				if((op.getProjectType()==OrderDunProjectType.COMMON.getCode()&&op.getDunType()==2&&//通用 公示
						projectStatus==NewProjectStatus.YTJ.getCode()))flag=true;
				if((op.getProjectType()==OrderDunProjectType.COMMON.getCode()&&op.getDunType()==3&&//通用 下证
						projectStatus==NewProjectStatus.YWCXZ.getCode()))flag=true;
				if((op.getProjectType()==OrderDunProjectType.KJXM.getCode()&&op.getDunType()==2&&//科技项目 立项或者公示
						projectStatus==NewProjectStatus.YLX.getCode()))flag=true;
				if((op.getProjectType()==OrderDunProjectType.KJXM.getCode()&&op.getDunType()==3&&//科技项目 拨款
						projectStatus==NewProjectStatus.LXYBK.getCode()))flag=true;
				if((op.getProjectType()==OrderDunProjectType.KJJR.getCode()&&op.getDunType()==2&&//科技金融 拨款
						projectStatus==NewProjectStatus.YWCXZ.getCode()))flag=true;
				if((op.getProjectType()==OrderDunProjectType.RJKF.getCode()&&op.getDunType()==2&&//软件开发 立项
						projectStatus==NewProjectStatus.YTJ.getCode()))flag=true;
				if((op.getProjectType()==OrderDunProjectType.RJKF.getCode()&&op.getDunType()==3&&//软件开发 验收
						projectStatus==NewProjectStatus.YWCXZ.getCode()))flag=true;
				if(op.getProjectType()==OrderDunProjectType.ZSCQ.getCode()){//知识产权 公示 专利受理、转让（项目已提交），软著下证
					if(op.getDunType()==3&&projectStatus==NewProjectStatus.YWCXZ.getCode()) {
						flag=true;
					}else if (op.getDunType()==2) {
						BusinessProject bp=businessProjectMapper.selectById(task2.getCommodityId());
						if (bp.getType()==0&&projectStatus==NewProjectStatus.YWCXZ.getCode()) {
							flag=true;
						}
						if (bp.getType()==1&&projectStatus==NewProjectStatus.YTJ.getCode()) {
							flag=true;
						}
						if (bp.getType()==2&&projectStatus==NewProjectStatus.YWCXZ.getCode()) {
							flag=true;
						}

					}
				}
					if(flag)addNoticAndEmail( op,NoticeStatus.PAYMENT_DUN.getCode());
			}
		}
	}


	public void addNoticAndEmail(OutPaymentNode pn,Integer type) {
		paymentNodeEmailBo pnb=paymentNodeMapper.selectBytidGetEmail(pn.getTid());
		TOrderNewBo b  = tOrderNewMapper.getSaleIdByOno(pnb.getOrderNo());
		orderNewService.addNotic(type,b,null);
		pn.setDunStatus(1);
		paymentNodeMapper.updateByPrimaryKeySelective(pn);
		//营销员名称、邮箱、订单编号、客户名称
		String dunTypeName=NewOrderDunType.getValueByCode(Integer.valueOf(""+pn.getProjectType()+pn.getDunType()));
			//发送驳回邮件
		if(SendEmailUtil.isEmail(pnb.getEmail())) {
	    	 EmailBo bo = new EmailBo("付款通知", pnb.getEmail(), "平台超管中心", "管理员",
						"", pnb.getOrderNo(),pnb.getContractNo(),pn.getPartyTimes(),
						dunTypeName,pnb.getSalesmanName(),pnb.getUserName(),2,0);
				if(StringUtils.isNotBlank(pnb.getEmail())) {
					try {
						asyncUtils.patentSend(bo);
					} catch (UnsupportedEncodingException | MessagingException e) {
						LoggerUtils.debug(logger, "=========================================发送邮件异常");
						e.printStackTrace();
					}
				}
	     }
	}

	private void checkSettlementAward(TOrderNew tn,TOrderTask task) {
		if(task.getTaskStatus()==TaskState.COMPLETE.getCode()&&tn.getTotalAmount().compareTo(tn.getSettlementAmount())==0) {
			List<TOrderTaskBo> l = tOrderTaskMapper.getReceiverByOid(tn.getOrderNo());
			for (TOrderTaskBo tOrderTask : l) {
				if(null != tOrderTask &&null != tOrderTask.getTaskReceiver()){
					TOrderBonus bonus = new TOrderBonus();
					bonus.setId(UUID.randomUUID().toString());
					bonus.setOrderNo(tn.getOrderNo());
					bonus.setGrantBy(tn.getFinanceId());
					bonus.setBonusSubject(BonusSubject.WK.getCode());//12
					bonus.setTaskId(tOrderTask.getId());//任务id
					bonus.setGrantTarget(tOrderTask.getTaskReceiver());
					bonus.setGrantType(1);
					int c = tOrderBonusMapper.checkByOnoAndSub(bonus);
					//不存在就设置
					if(c==0){
						bonus.setId(UUID.randomUUID().toString());
						tOrderBonusMapper.insertSelective(bonus);
					}

				}

			}
		}
	}

	private void meanwhileUpdateOrder(TOrderTask task) {
		//是否是主要项目
		if (task.getMain()==1) {
		//更改订单项目状态
		TOrderNew tNew = new TOrderNew();
		tNew.setProjectStatus(task.getProjectStatus());
		tNew.setOrderNo(task.getOrderNo());
		tOrderNewMapper.update(tNew);
		}
		if (task.getProjectStatus()==NewProjectStatus.YTJ.getCode()||task.getProjectStatus()==NewProjectStatus.YLX.getCode()||
				task.getProjectStatus()==NewProjectStatus.YNGS.getCode()) {
			TOrderBonus tb=new TOrderBonus();
			TOrderNew t=tOrderNewMapper.queryById(task.getOrderNo());
			tb.setId(UUID.randomUUID().toString());
			tb.setOrderNo(task.getOrderNo());
			if (task.getProjectStatus()==NewProjectStatus.YTJ.getCode()) {
				tb.setBonusSubject(21);//项目已提交
				addOrderLog(task.getOrderNo(),OrderLogProcess.XMWC.getCode(),null);
			}
			if (task.getProjectStatus()==NewProjectStatus.YLX.getCode())tb.setBonusSubject(23);//项目立项
			if (task.getProjectStatus()==NewProjectStatus.YNGS.getCode())tb.setBonusSubject(24);//项目公示
			tb.setGrantType(1);//技术员
			//新增奖金之前检查这个奖金数据是否存在
			tb.setGrantTarget(task.getTaskReceiver());
			int c = tOrderBonusMapper.checkByOnoAndSub(tb);
			if(c==0){
				tb.setGrantBy(t.getFinanceId());
				tb.setTaskId(task.getId());
				tOrderBonusMapper.insertSelective(tb);
			}
		}
	}

	@Override
	public int addTaskHours(TTaskHours t) {
		TOrderTask tt=tOrderTaskMapper.queryById(Integer.valueOf(t.getTaskId()));
		checkDeleteSign(tt.getOrderNo());
		t.setAid(TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
		t.setId(UUID.randomUUID().toString());
		t.setCreateTime(new Date());
		if(taskHoursCountMapper.selectByAidAndTid(TokenManager.getAdminId(),t.getTaskId())>0) {
			taskHoursCountMapper.updateByAidAndTid(TokenManager.getAdminId(),t.getTaskId(),t.getHours());
		}else {
			TaskHoursCount tc=new TaskHoursCount();
			tc.setAid(TokenManager.getAdminId());
			tc.setTid(Integer.valueOf(t.getTaskId()));
			tc.setHours(t.getHours());
			taskHoursCountMapper.insertSelective(tc);
		}
		return tTaskHoursMapper.insertSelective(t);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<TOrderTaskListBo> taskHoursList(inuptTaskHoursListBo ib, Integer pageNo,
			Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(pageSize==null||pageSize<0)pageSize=10;
		if(pageNo==null||pageNo<0)pageNo=1;
		if (StringUtils.isNotBlank(ib.getName())) params.put("name", ib.getName());
		if (StringUtils.isNotBlank(ib.getOrderNo())) params.put("orderNo", ib.getOrderNo());
		if (StringUtils.isNotBlank(ib.getTaskId())) params.put("taskId", ib.getTaskId());
		if (StringUtils.isNotBlank(ib.getStarTime())) params.put("starTime", ib.getStarTime());
		if (StringUtils.isNotBlank(ib.getEndTime())) params.put("endTime", ib.getEndTime()+" 23:59:59");
		if(StringUtils.isNotBlank(ib.getContractNo()))params.put("contractNo", ib.getContractNo());
		if(StringUtils.isNotBlank(ib.getDepId()))params.put("depId", ib.getDepId());
		if(StringUtils.isNotBlank(ib.getCid()))params.put("cid", ib.getCid());
		if (ib.getThchId()!=null)params.put("thchId", ib.getThchId());
		if(null!=ib.getOutsource())params.put("outsource", ib.getOutsource());
		Integer i=null;
	if (TokenManager.hasRole(AFTConstants.FINANCE))i=1;
		if (TokenManager.hasRole(AFTConstants.FINANCE_MANAGER))i=2;
		if (TokenManager.hasRole(AFTConstants.FINANCE_ADMIN)||TokenManager.hasRole(AFTConstants.VICE_CEO)||
				TokenManager.hasRole(AFTConstants.SUPERADMIN)||TokenManager.hasRole(AFTConstants.CED)||
				TokenManager.hasRole(AFTConstants.APPROVAL_DECISION))i=3;
		if(TokenManager.getAdminId()!=null)params.put("aid", TokenManager.getAdminId());
		if(i!=null)params.put("shiroType", i);
		Pagination<TOrderTaskListBo> p = (Pagination<TOrderTaskListBo>)findPage("selectTaskHoursListByPage", "selectTaskHoursListCount", params, pageNo, pageSize);

		return p;
	}







	@SuppressWarnings("unchecked")
	@Override
	public Pagination<TOrderTaskListBo> selectTaskList(String name, String orderNo, String taskId, Integer taskStatus,
			String adminName, Integer specially,String depId,String thchId  ,String type  , Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(pageSize==null||pageSize<0)pageSize=10;
		if(pageNo==null||pageNo<0)pageNo=1;
		params.put("aid", TokenManager.getAdminId()==null?"":TokenManager.getAdminId());
		if (StringUtils.isNotBlank(name)) params.put("name", name);
		if (StringUtils.isNotBlank(depId)) params.put("depId", depId);
		if (StringUtils.isNotBlank(orderNo)) params.put("orderNo", orderNo);
		if (StringUtils.isNotBlank(taskId)) params.put("taskId", taskId);
		if (StringUtils.isNotBlank(thchId)) params.put("thchId", thchId);
		if (StringUtils.isNotBlank(adminName)) params.put("adminName", adminName);
		if (null != taskStatus) params.put("taskStatus", taskStatus);
		if (StringUtils.isNotBlank(type)){
			params.put("type", type.split(","));
		}
		Pagination<TOrderTaskListBo> p = (Pagination<TOrderTaskListBo>)findPage("selectTaskListByPage", "selectTaskListCount", params, pageNo, pageSize);
		return p;
	}

	private void pushParams(Map<String,Object> map,String name,Object value) {
		if (value!=null){
			map.put(name, value);
		}
	}

	@Override
	public List<TaskLogBo> TaskLogList(Integer id) {
		return taskLogMapper.selectTaskLogList(id);
	}
	@Override
	public int createTaskProgress(TaskProgressBo t) {
		TaskProgress tp=new TaskProgress();
		TOrderTask tt=tOrderTaskMapper.queryById(t.getTaskId());
		int count =taskProgressMapper.AlreadyNuberCount(t.getTaskId());
		count +=t.getAlreadyNumber();
		if(tt.getCommodityQuantity()<count)throw new BusinessException(new Error( "数量不能大于总量！" ,"数量不能大于总量！"));
		tp.setAlreadyNumber(t.getAlreadyNumber());
		tp.setPatentName(t.getPatentName());
		tp.setPatentNo(t.getPatentNo());
		tp.setType(t.getType());
		if (t.getLicenceTimes()!=null) tp.setLicenceTime(DateUtils.StringToDate(t.getLicenceTimes(), AFTConstants.YYYYMMDD));
		if (t.getAcceptTimes()!=null) tp.setAcceptTime(DateUtils.StringToDate(t.getAcceptTimes(), AFTConstants.YYYYMMDD));
		if (t.getAuthorizeTimes()!=null) tp.setAuthorizeTime(DateUtils.StringToDate(t.getAuthorizeTimes(), AFTConstants.YYYYMMDD));
		tp.setStatus(t.getStatus());
		tp.setTaskId(t.getTaskId());
		tTaskMidMapper.updateCertificatesCountByTid(t.getTaskId(),count);
		TaskProgressLog tpl=new TaskProgressLog(t.getTaskId(),t.getPatentName(),0,new Date());
		taskProgressLogMapper.insertSelective(tpl);
		int i=taskProgressMapper.insertSelective(tp);
		countByTid(tp.getTaskId(),tp.getType());
		return i;
	}


	@Override
	public int updateTaskProgress(TaskProgressBo t) {
		TaskProgress tp=taskProgressMapper.selectByPrimaryKey(t.getId());
		TOrderTask tt=tOrderTaskMapper.queryById(t.getTaskId());
		int count =taskProgressMapper.AlreadyNuberCount(t.getTaskId());
		count = count-tp.getAlreadyNumber()+t.getAlreadyNumber();
		if(tt.getCommodityQuantity()<count)throw new BusinessException(new Error( "数量不能大于总量！" ,"数量不能大于总量！"));
		tp.setAlreadyNumber(t.getAlreadyNumber());
		tp.setPatentName(t.getPatentName());
		tp.setPatentNo(t.getPatentNo());
		tp.setType(t.getType());
		if (t.getLicenceTimes()!=null) tp.setLicenceTime(DateUtils.StringToDate(t.getLicenceTimes(), AFTConstants.YYYYMMDD));
		if (t.getAcceptTimes()!=null) tp.setAcceptTime(DateUtils.StringToDate(t.getAcceptTimes(), AFTConstants.YYYYMMDD));
		if (t.getAuthorizeTimes()!=null) tp.setAuthorizeTime(DateUtils.StringToDate(t.getAuthorizeTimes(), AFTConstants.YYYYMMDD));
		tp.setStatus(t.getStatus());
		tp.setTaskId(t.getTaskId());
		tTaskMidMapper.updateCertificatesCountByTid(t.getTaskId(),count);
		TaskProgressLog tpl=new TaskProgressLog(t.getTaskId(),t.getPatentName(),2,new Date());
		taskProgressLogMapper.insertSelective(tpl);
		int i=taskProgressMapper.updateByPrimaryKeySelective(tp);
		countByTid(tp.getTaskId(),tp.getType());
		return i;
	}

	@Override
	public int delectTaskProgress(Integer id) {
		TaskProgress tp=taskProgressMapper.selectByPrimaryKey(id);
		if (tp==null) {
			return 0;
		}
		int i=taskProgressMapper.deleteByPrimaryKey(id);
		TaskProgressLog tpl=new TaskProgressLog(tp.getTaskId(),tp.getPatentName(),1,new Date());
		taskProgressLogMapper.insertSelective(tpl);
		countByTid(tp.getTaskId(),tp.getType());
		return i;
	}
	private void countByTid(Integer taskId, Integer type) {
		//目前不做计算
//		TTaskMid ttm=tTaskMidMapper.selectCountBytid(taskId,type);
//		tTaskMidMapper.updateByPrimaryKeySelective(ttm);

	}



	@Override
	public List<TaskProgressBo> selectTaskProgress(Integer tid) {
		List<TaskProgressBo> l=taskProgressMapper.selectTaskProgress(tid);
		int notcount=0;
		for (TaskProgressBo t : l) {
			notcount+=t.getAlreadyNumber();
			t.setNotCount(t.getIngCount()-notcount);
		}
		return l;
	}

	@Override
	public List<TTaskHours> taskHoursDetailsList(String taskId) {
		String aid=TokenManager.getAdminId();
		return tTaskHoursMapper.taskHoursDetailsList(taskId,aid);
	}

	@Override
	public int pushSplitProject(Integer tid, String splitList) {
			String[] str=splitList.split(",");
			TOrderTask task=tOrderTaskMapper.queryById(tid);
			checkDeleteSign(task.getOrderNo());
			TOrderTask usedTask=new TOrderTask();
			usedTask.setId(tid);
			usedTask.setSplitStatus(1);
			//计算拆分数量
			Integer x=0;
			for (String string : str) {
				x+=Integer.parseInt(string);
			}
			if (!task.getCommodityQuantity().equals(x)||str.length==1) {
				return -1;
			}
			tOrderTaskMapper.update(usedTask);
			int i=1;
			TOrderTask newTask=task;
			newTask.setCommodityPrice(new BigDecimal(0));
			newTask.setSplitAid(TokenManager.getAdminId());
			newTask.setSplitStatus(2);
			newTask.setSplitSuper(tid);
			newTask.setSplitTime(new Date());
			for (String string : str) {
				newTask.setId(null);
				newTask.setCommodityQuantity(Integer.parseInt(string));
				newTask.setSplitId(i);
				i++;
				tOrderTaskMapper.insertSelective(newTask);
				TTaskMid dtails = tTaskMidMapper.getDtails(newTask.getId());
				TTaskMid tTaskMid = new TTaskMid(newTask.getId(), new BigDecimal(0));
				tTaskMid.setDispatchProvince(dtails.getDispatchProvince());
				tTaskMid.setDutyDep(dtails.getDutyDep());
				tTaskMidMapper.insertSelective(tTaskMid);
			}
		return 1;
	}

	@Override
	public List<TOrderTaskListBo> splitProjectList(Integer tid,Integer type) {
		return tOrderTaskMapper.splitProjectList(tid,type);
	}


	@Override
	public List<OutTaskProgressLog> selectTaskProgressLog(Integer tid) {
		return taskProgressLogMapper.selectTaskProgressLog(tid);
	}



	@Override
	public Pagination<managerListBo> managerSelect(String name, String orderNo, String contractNo, String cid,
			String projectType,String thchId, String depId, String techDepId, Integer declarationBatch, String commodityPrice,
			String startTime,String endTime ,String type,Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(pageSize==null||pageSize<0)pageSize=10;
		if(pageNo==null||pageNo<0)pageNo=1;
		params.put("aid", TokenManager.getAdminId()==null?"":TokenManager.getAdminId());
		if (StringUtils.isNotBlank(name))params.put("name", name);
		if (StringUtils.isNotBlank(depId)) params.put("depId", depId);
		if (StringUtils.isNotBlank(orderNo)) params.put("orderNo", orderNo);
		if (StringUtils.isNotBlank(contractNo)) params.put("contractNo", contractNo);
		if (StringUtils.isNotBlank(cid)) params.put("cid", cid);
		if (StringUtils.isNotBlank(projectType)) params.put("projectType", projectType);
		if (StringUtils.isNotBlank(depId)) params.put("depId", depId);
		if (StringUtils.isNotBlank(thchId))params.put("thchId", thchId);
		if (StringUtils.isNotBlank(techDepId)) params.put("techDepId", techDepId);
		if (StringUtils.isNotBlank(commodityPrice)) params.put("commodityPrice", commodityPrice);
		if (StringUtils.isNotBlank(startTime)) params.put("startTime", startTime);
		if (StringUtils.isNotBlank(endTime)) params.put("endTime", endTime+" 23:59:59");
		if (null != declarationBatch) params.put("declarationBatch", declarationBatch);
		@SuppressWarnings("unchecked")
		Pagination<managerListBo> p = (Pagination<managerListBo>)findPage("managerSelectByPage", "managerSelectCount", params, pageNo, pageSize);
		return p;
	}


	@Override
	public List<taskAttributionLogBo> taskAttributionLog(Integer tid) {

		return taskAttributionLogMapper.selectByTid(tid);
	}


	@Override
	public List<UserOrderTask> selectUidByproject(String uid) {

		return tOrderTaskMapper.selectUidByproject(uid);
	}


	@Override
	public int addProjectCheck(Integer tid) {
		TOrderTask t=new TOrderTask();
		t.setCheckStatus(1);
		t.setId(tid);
		ProjcetCheckLog log=new ProjcetCheckLog();
		log.setAid(TokenManager.getAdminId());
		log.setRemarks("发起核对");
		log.setTid(tid);
		log.setStatus(0);
		OrderOperator oo=tOrderTaskMapper.selectAidByParam(tid);
		if (oo!=null&&oo.getOrderNo()!=null&&oo.getSalesmanId()!=null) {
			Notice n =new Notice();
			String str=String.format("[%s]发起专利核对，客户名称[%s]订单编号[%s]项目编号[%s]。", oo.getTechName(),oo.getBuyerName(),oo.getOrderNo(),oo.getTid());
			n.setId(UUID.randomUUID().toString());
			n.setAid(oo.getSalesmanId());
			n.setNoticeType(NoticeStatus.ITEM_CHECK_START.getCode());
			n.setContent(str);
			n.setReaded(0);//未读
			asyncUtils.addNoticAndEmail(n);
		}
		projcetCheckLogMapper.insertSelective(log);
		tOrderPaymentMapper.deleteByParam(tid,2);
		return tOrderTaskMapper.update(t);
	}


	@Override
	public List<OutProjectCheckLog> projectCheckLog(Integer tid) {
		return projcetCheckLogMapper.projectCheckLog(tid);
	}


	@SuppressWarnings("unchecked")
	@Override
	public Object selectProjectCheck(InputProjectCheck in) {
		Map<String, Object> map=new HashedMap<String, Object>();
		if (in.getName()!=null) map.put("name", in.getName());
		if (in.getOrderNo()!=null) map.put("orderNo", in.getOrderNo());
		if (in.getContractNo()!=null) map.put("contartNo", in.getContractNo());
		if (in.getPname()!=null) map.put("pname", in.getPname());
		if (in.getDeps()!=null) {
			map.put("deps", departmentService.parseArray(in.getDeps()));
		}
		map.put("aid", TokenManager.getAdminId());
		return (Pagination<OutProjectCheck>)findPage("selectProjectCheck", "countProjectCheck", map, in.getPageNo(), in.getPageSize());
	}

	@Override
	public List<OutHighNewRetrialStatistics> highNewRetrialStatistics(String depId, String startDate, String endDate) {
		endDate=endDate+" 23:59:59";
		return tOrderTaskMapper.highNewRetrialStatistics(depId,startDate,endDate);
	}

	@Override
	public List<OutHighNewRetrialList> highNewRetrialList(String province, String depId, String aid, Integer sort, String startDate, String endDate) {
		endDate=endDate+" 23:59:59";
		if (sort==null)sort=0;
		return tOrderTaskMapper.highNewRetrialList( province,  depId,  aid,  sort,  startDate,  endDate);
	}


	@Override
	public Pagination<OutMemberList> memberList(InputMemberList in) {
		HashMap<String, Object> map = new HashMap<>();
		addParam(in, map);
		Pagination<OutMemberList> page = (Pagination<OutMemberList>) findPage("findMemberList", "findMemberCount", map, in.getPageNo(), in.getPageSize());
		List<OutMemberList> list = (List<OutMemberList>) page.getList();
		if (!list.isEmpty())pushMyExamine(list);
		return page;
	}

	private void pushMyExamine(List<OutMemberList> list) {
		List<Integer> ids =list.stream().map(e -> e.getId()).collect(Collectors.toList());
		List<TOrderExamine> examineList = tOrderExamineMapper.selectExamineBytidAndAid(ids, TokenManager.getAdminId());
		list=list.stream().map(e -> {
					examineList.forEach(ex -> {
						if(e.getId().equals(ex.getTid())) {
							if (ex.getStatus() == 1) {
								e.setMyExamine(1);
							}
						}
					});
			if (e.getMyExamine()==null){
				e.setMyExamine(0);
			}
			return e;
		}).collect(Collectors.toList());
	}

	private void addParam(InputMemberList in, HashMap<String, Object> map) {
		if(in.getOrderNo()!=null) map.put("orderNo", in.getOrderNo());
		if(in.getUserName()!=null) map.put("userName", in.getUserName());
		if(in.getDeps()!=null&&!in.getDeps().isEmpty()){
			List<String> ls=JSON.parseArray(in.getDeps(),String.class);
			map.put("deps", ls);
		}
		if(in.getContractNo()!=null) map.put("contractNo", in.getContractNo());
		if(in.getSalesmanId()!=null) map.put("salesmanId", in.getSalesmanId());
		if(in.getProjectName()!=null) map.put("projectName", in.getProjectName());
		if(in.getAmountStatus()!=null) map.put("amountStatus", in.getAmountStatus());
		if(in.getApproval()!=null) map.put("approval", in.getApproval());
		if(in.getStatus()!=null) map.put("status", in.getStatus());
		if(in.getShiroType()!=null) map.put("shiroType", in.getShiroType());
		if(in.getType()!=null){
			map.put("type", in.getType().split(","));
		}
		map.put("aid",TokenManager.getAdminId());
//		if (TokenManager.hasRole(AFTConstants.VICE_CED)){
//			map.put("approvalType",2);
//		}else if (TokenManager.hasRole(AFTConstants.CED)){
//			map.put("approvalType",1);
//		}
	}

	@Override
	public Result memberListExport(InputMemberList in) {
		HashMap<String, Object> map = new HashMap<>();
		addParam(in, map);
		List<OutMemberList>list= (List<OutMemberList>) findList("findMemberList",map,1,9999);
		for (OutMemberList out : list) {
			if (out.getSalesType()!=null){
				StringBuffer str=new StringBuffer();
				str.append(SalesTypes.getValueByCode(out.getSalesType()));
				if (out.getSalesType()==SalesTypes.qd.getCode()){
					str.append("-").append(out.getOther());
				}
				out.setSalesTypeName(str.toString());
			}
			if (out.getTotalAmount()!=null){
				StringBuffer str=new StringBuffer();
				str.append(out.getTotalAmount().compareTo(new BigDecimal(10))>=0?"大客户":"一般客户");
				out.setBigUser(str.toString());
			}
			if (out.getDeleteSign()!=null){
				StringBuffer str=new StringBuffer();
				str=str.append(out.getDeleteSign()==0?"正常": out.getDeleteSign()==1?"删除":
						out.getDeleteSign()==2?"锁定":"未知");
				out.setDeleteSignStr(str.toString());
			}
			if (out.getType()!=null){
				String[] split = out.getType().split(",");
				StringBuilder str=new StringBuilder();
				int index = 1;
				for (int i = 1; i < 9; i++) {
					for (String s : split) {
						if (index ==Integer.parseInt(s)){
							if (ApprovalTypeEnums.QT.getCode().equals(Integer.parseInt(s))){
								str.append(ApprovalTypeEnums.getDesc(s))
										.append("(").append(out.getTypeExplain()).append(")")
										.append(",");
							}else {
								str.append(ApprovalTypeEnums.getDesc(s)).append(",");
							}
						}
					}
					index++;
					if (index==8)index=0;
				}
				out.setType(str.substring(0,str.length()-1));
			}

		}
		NewExcelUtil<OutMemberList> excelUtil=new NewExcelUtil<>(OutMemberList.class);
		return excelUtil.exportExcel(list,"会员审核列表",uploadPath);
	}


	/**
	 * 财务通过走3个逻辑   还有复审 停留不发送邮件   复审也审核了 ，看是否特批，特批走
	 * @param in
	 * @return
	 */
	@Override
	public int pushExamineMemberProject(InputMenber in) {
		TOrderTask task=tOrderTaskMapper.queryById(in.getId());
		String aid=TokenManager.getAdminId();
		int status=1;
		boolean appFlag=false;
		//是否财务审核加复审
		boolean flag=false;
		TOrderTask nt=new TOrderTask();
		nt.setId(task.getId());
		int result=0;
		Integer notice=NoticeStatus.MENBER_YES.getCode();
		TOrderNewBo ono = tOrderNewMapper.getSaleIdByOno(task.getOrderNo());
		TTaskMember tTaskMember = tTaskMemberMapper.selectByTid(in.getId());
		// 1=通过 0=驳回
		if (in.getResult()==1){
			//0=财务 1=特批
			if (in.getType()==0){
				if(task.getProcessStatus()!=1)throw  new BusinessException("审核状态错误");
				List<TOrderExamine> list = tOrderExamineMapper.selectByTid(task.getId());
				list.forEach(e ->{
					if (e.getAid().equals(aid)){
						TOrderExamine te=new TOrderExamine();
						te.setId(e.getId());
						te.setStatus(1);
						tOrderExamineMapper.updateByPrimaryKeySelective(te);
					}
						});
				OrganizationListOut dep = tOrderNewMapper.selectOrderFinance(task.getOrderNo());
				int examineType =task.getExamineType();
				//判定谁审核的财务审核，
				if (aid.equals(dep.getFinanceId())){
					if (examineType==3){
						examineType=2;
					} else if (examineType==1) {
						examineType=4;
					}
				}else if (aid.equals(dep.getRetrialFinanceId())){
					if (examineType==3){
						examineType=1;
					}else if (examineType==2){
						examineType=4;
					}
				}
				nt.setExamineType(examineType);
				//全都已经审核的情况下
				if(examineType==4){
					flag=true;
				}

				//需要特批的情况下
				if (task.getMemberType()==1||task.getMemberType()==2){
					if (flag){
						Department department = tOrderNewMapper.selectDepByOrderNo(task.getOrderNo());
						//部门设置无需特批的情况下直接完成，否则走正常流程
						if (department.getApproval()==0){
							nt.setProcessStatus(3);
							//判定无特批直接完成新增日志
							appFlag=true;
						}else {
							nt.setProcessStatus(2);
						}
					}
					status=1;
				}else if (task.getMemberType()==0){
					if(flag){
						nt.setProcessStatus(3);
						status=3;
						result=1;
					}else {
						status=1;
					}

				}
				if(flag){
					subtractionFinanceCountMember(task.getOrderNo(),tTaskMember.getCreateTime(),1);
				}
			}else if(in.getType()==1){
				if(task.getProcessStatus()!=2)throw  new BusinessException("审核状态错误");
				nt.setProcessStatus(3);
				status=3;
				result=1;
				flag=true;
			}
		}else if (in.getResult()==0){
			status=2;
			nt.setProcessStatus(4);
			notice=NoticeStatus.MENBER_NO.getCode();
			if(in.getType()==0){
				subtractionFinanceCountMember(task.getOrderNo(),tTaskMember.getCreateTime(),0);
			}else {
				subtractionFinanceCountMember(task.getOrderNo(),tTaskMember.getCreateTime(),2);
			}
		}
		addMemberLog(in.getId(),status,in.getRemarks(),TokenManager.getAdminId());
		if (nt.getProcessStatus()!=null&&nt.getProcessStatus()==3){
			tTaskMemberMapper.updateServiceYearBySplitSuper(task.getSplitSuper());
		}
		tOrderTaskMapper.update(nt);
		if (flag){
			addNoticMember(notice, ono, in.getType(),result);
		}
		if(appFlag)addMemberLog(in.getId(),status,"部门特批审核人未设置，系统自动通过",AFTConstants.SUPERADMIN_ID);
		return 1;
	}

	/**
	 *
	 * @param orderNo
	 * @param date
	 * @param type 0双减  1未审核减 2 总数减
	 */
	private void subtractionFinanceCountMember(String orderNo, Date date,Integer type) {
		Admin admin = adminMapper.selectOrderByFinanace(orderNo);
		String startTime = DateUtils.formatDate(date, AFTConstants.YYYYMMDD);
		FinanceCount financeCount = financeCountMapper.selectByAidAndDates(admin.getId(), startTime);
		if (financeCount != null) {
			FinanceCount newFinanceCount =new FinanceCount();
			newFinanceCount.setId(financeCount.getId());
			if(type==0){
				newFinanceCount.setMemberCount(financeCount.getMemberCount()-1);
				newFinanceCount.setMemberUnauditedCount(financeCount.getMemberUnauditedCount()-1);
			}else if(type==1){
				newFinanceCount.setMemberUnauditedCount(financeCount.getMemberUnauditedCount()-1);
			}else if(type==2){
				newFinanceCount.setMemberCount(financeCount.getMemberCount()-1);
			}else {
				return;
			}
			financeCountMapper.updateByPrimaryKeySelective(newFinanceCount);
		}
	}


	@Override
	public int updateMemberProject(InputAddTask t) {
		TOrderTask task=tOrderTaskMapper.queryById(t.getId());
		if(task.getProcessStatus()!=4)throw  new BusinessException("审核状态错误，无法提交。");
		addMemberLog(t.getId(),0,"修改重新发起",TokenManager.getAdminId());
		t.setProcessStatus(1);
		TOrderNewBo ono = tOrderNewMapper.getSaleIdByOno(task.getOrderNo());
		addNoticMember(NoticeStatus.MENBER_START.getCode(), ono, null,0,task);
		TTaskMember tTaskMember = tTaskMemberMapper.selectByTid(t.getId());
		addFinanceCountMember(task.getOrderNo(), tTaskMember.getCreateTime());
		addMemberExamine(task);
		return orderNewService.updateOrderTask(t);
	}



	@Override
	public void addMemberLog(Integer id,Integer status ,String remarks,String aid){
		MemberLog log = new MemberLog();
		log.setPid(id);
		log.setStatus(status);
		log.setRemarks(remarks);
		log.setAid(aid);
		memberLogMapper.insertSelective(log);
	}

	@Override
	public List<MemberLogBo> memberLog(Integer id) {
		return memberLogMapper.memberLog(id);
	}

	@Override
	public TOrderTask addMemberSonProject(InputSonProject in ) {
		Date date =new Date();
		TOrderTask tOrderTask =  tOrderTaskMapper.queryById(in.getTid());
		tOrderTask.setSplitStatus(1);
		tOrderTask.setSplitAid(TokenManager.getAdminId());
		tOrderTask.setSplitTime(date);
		tOrderTask.setProjectStatus(1);

		TOrderTask newT=new TOrderTask();
		BeanUtils.copyProperties(tOrderTask,newT);
		newT.setId(null);
		newT.setSplitStatus(2);
		newT.setSplitSuper(in.getTid());
		newT.setProjectStatus(0);
		if (in.getMemberType()!=null){
			newT.setProcessStatus(1);
			newT.setMemberType(in.getMemberType());
			newT.setPictureUrl(in.getPictureUrl());

//			if(memberType==1||memberType==2){
//				//判定项目省内外
//				Department dep = tOrderNewMapper.selectDepByOrderNo(tOrderTask.getOrderNo());
//				if (dep!=null&&dep.getProvince()==AFTConstants.HN_PROVINCE){
//					tOrderTask.setApproval(2);
//				}else {
//					tOrderTask.setApproval(1);
//				}
//			}
		}
		Integer i=tOrderTaskMapper.getSplitCount(in.getTid());
		i++;
		newT.setSplitId(i);
		newT.setCommodityQuantity(1);
		newT.setTaskComment(in.getTaskComment());
		newT.setMain(0);
		if (in.getHtMember()!=null){
			newT.setHtMember(in.getHtMember());
		}else {
			newT.setHtMember(0);
		}
		if (in.getAdditionalDeduction()!=null){
			newT.setAdditionalDeduction(in.getAdditionalDeduction());
		}else {
			newT.setAdditionalDeduction(0);
		}
		if (in.getRdAwardsubsidy()!=null){
			newT.setRdAwardsubsidy(in.getRdAwardsubsidy());
		}else {
			newT.setRdAwardsubsidy(0);
		}
		newT.setCommodityPrice(new BigDecimal(0));
		tOrderTaskMapper.insertSelective(newT);
//		新增不在需要单独处理
//		pushFatherTask(tOrderTask);
		tOrderTaskMapper.update(tOrderTask);
		TTaskMember t = tTaskMemberMapper.selectByTid(in.getTid());
		TOrderTaskBo tb=new TOrderTaskBo();
		BeanUtils.copyProperties(newT,tb);
		if (t.getServiceLife()!=null||t.getYearSum()!=null||t.getContractTerm()!=null||in.getServiceYear()!=null){
			TTaskMember ttm=new TTaskMember();
			ttm.setId(null);
			ttm.setTid(newT.getId());
			if(t.getServiceLife()!=null)ttm.setServiceLife(t.getServiceLife());
			ttm.setServiceYear(in.getServiceYear());
			tb.setServiceYear(in.getServiceYear());
			if(t.getYearSum()!=null)ttm.setYearSum(t.getYearSum());
			if(t.getContractTerm()!=null)ttm.setContractTerm(t.getContractTerm());
			tTaskMemberMapper.insertSelective(ttm);
		}
		orderNewService.addTaskMid(newT.getId(),newT.getCommodityId(), newT.getOrderNo());

		addMemberLog(newT.getId(),0,"新增会员项目",TokenManager.getAdminId());
		if(in.getMemberType()!=null){
			addMemberExamine(newT);
			addNoticMember(NoticeStatus.MENBER_START.getCode(),newT,null,0);
			addFinanceCountMember(newT.getOrderNo(),date);
		}
		return tb;
	}

	private void pushFatherTask(TOrderTask tOrderTask) {
		List<TOrderTaskListBo> listBos = tOrderTaskMapper.splitProjectList(tOrderTask.getId(), 1);
		int htMember=0,additionalDeduction=0,rdAwardsubsidy=0;
		for (TOrderTaskListBo e : listBos) {
			if (e.getHtMember()!=null&&e.getHtMember()==1)htMember=1;
			if (e.getAdditionalDeduction()!=null&&e.getAdditionalDeduction()==1)additionalDeduction=1;
			if (e.getRdAwardsubsidy()!=null&&e.getRdAwardsubsidy()==1)rdAwardsubsidy=1;
		}
		tOrderTask.setHtMember(htMember);
		tOrderTask.setAdditionalDeduction(additionalDeduction);
		tOrderTask.setRdAwardsubsidy(rdAwardsubsidy);
	}


	private void addMemberExamine(TOrderTask t) {
		OrganizationListOut dep = tOrderNewMapper.selectOrderFinance(t.getOrderNo());
		tOrderExamineMapper.deleteByTid(t.getId());
		List<TOrderExamine> list=new ArrayList<>();
		TOrderTask tOrderTask= new TOrderTask();
		if(StringUtils.isNotBlank(dep.getFinanceId())){
			int examineType=0;
			if (!Objects.isNull(dep.getFinanceId())){
				list.add(new TOrderExamine(t.getOrderNo(),1,t.getId(),dep.getFinanceId(),dep.getFinanceName()));
				examineType=1;
			}
			if (StringUtils.isNotBlank(dep.getRetrialFinanceId())){
				list.add(new TOrderExamine(t.getOrderNo(),1,t.getId(),dep.getRetrialFinanceId(),dep.getRetrialFinanceName()));
				if(examineType==1){
					examineType=3;
				}else {
					examineType=2;
				}
			}

			tOrderTask.setExamineType(examineType);
		}else {
			throw new BusinessException("部门未设置财务专员。");
		}
		tOrderTask.setId(t.getId());

		tOrderTaskMapper.update(tOrderTask);
		tOrderExamineMapper.insertBatch(list);
	}



	private void addFinanceCountMember(String orderNo, Date date) {
		Admin admin = adminMapper.selectOrderByFinanace(orderNo);
		String startTime = DateUtils.formatDate(date, AFTConstants.YYYYMMDD);
		FinanceCount financeCount = financeCountMapper.selectByAidAndDates(admin.getId(), startTime);
		if (financeCount == null) {
			financeCount = FinanceCount.initialization(admin.getId(), startTime);
			financeCount.setMemberCount(1);
			financeCount.setMemberUnauditedCount(1);
			financeCountMapper.insertSelective(financeCount);
		}else {
			FinanceCount newFinanceCount =new FinanceCount();
			newFinanceCount.setId(financeCount.getId());
			newFinanceCount.setMemberCount(financeCount.getMemberCount()+1);
			newFinanceCount.setMemberUnauditedCount(financeCount.getMemberUnauditedCount()+1);
			financeCountMapper.updateByPrimaryKeySelective(newFinanceCount);
		}
	}


	public void addNoticMember(Integer type,  TOrderTask tOrderTask,Integer shiroType,Integer result) {
		TOrderNewBo tn = tOrderNewMapper.getSaleIdByOno(tOrderTask.getOrderNo());
		addNoticMember(type,tn,shiroType,result,tOrderTask);
	}

	@Override
	public void addNoticMember(Integer type, TOrderNewBo b, Integer shiroType, Integer result) {
		addNoticMember(type,b,shiroType,result,null);
	}

	public void addNoticMember(Integer type,  TOrderNewBo b,Integer shiroType,Integer result,TOrderTask tOrderTask) {
		StringBuffer sb=new StringBuffer();
		Date date = new Date();
		String aid=null;
		List<Admin>admins=new ArrayList<>();
		sb.append("客户名称【").append(b.getUserName()).append("】,订单编号【").append(b.getOrderNo()).append("】,");
		if (type.equals(NoticeStatus.MENBER_START.getCode())){
			sb=sb.append("发起会员项目，请及时审核");
			pushTOrderExamineAid(tOrderTask.getId(),admins);
		}else if (type.equals(NoticeStatus.MENBER_YES.getCode())){
			sb=sb.append("会员项目审核");
			if(shiroType==0){
				sb=sb.append("财务已通过。");
				if (result==1) {
					admins = MemberEnd(b);
				}else{
					//通知总裁改成特批审核人
					//admins=adminMapper.getAdminRoleTypeList(AFTConstants.CED);
					Department department = tOrderNewMapper.selectDepByOrderNo(b.getOrderNo());
					//部门设置无需特批的情况下直接完成，否则走正常流程
					if (department.getApproval()==1){
						admins.add(adminMapper.selectById(department.getApprovalAid()));
					}
				}
			} else if(shiroType==1){
				sb=sb.append("特批已通过。");
				admins = MemberEnd(b);
			}
		}else if (type.equals(NoticeStatus.MENBER_NO.getCode())){
			if(shiroType==0){
				sb=sb.append("财务已驳回。");
			} else if(shiroType==1){
				sb=sb.append("特批已驳回。");
			}
			aid=b.getSalesmanId();
		}
		if (admins!=null&&admins.size()>0){
			List<EmailBo> list =new ArrayList<>();
			List<Notice> notices=new ArrayList<>();
			for (Admin admin : admins) {
				list.add(sendMemberEmail(type,admin.getId(),sb.toString()));
				Notice n = new Notice();
				n.setId(UUID.randomUUID().toString());
				n.setAid(admin.getAid());
				n.setNoticeType(type);
				n.setContent(sb.toString());
				n.setCreateTime(date);
				n.setReaded(0);//未读
				notices.add(n);
			}
			asyncUtils.sendList(list);
			asyncUtils.addNoticeBatch(notices);
		}else {
			asyncUtils.addNotic(type,aid,sb.toString());
			sendMemberEmail(type,aid,sb.toString());
		}
	}

	private void pushTOrderExamineAid(Integer tid, List<Admin> admins) {
		List<TOrderExamine> list = tOrderExamineMapper.selectByTid(tid);
		for (TOrderExamine e : list) {
			Admin admin = new Admin();
			admin.setId(e.getAid());
			admins.add(admin);
		}
	}


	/**
	 * 会员项目完成审核调用
	 * @param b
	 * @return
	 */
	private List<Admin> MemberEnd(TOrderNewBo b) {
		List<Admin> admins;
		admins=adminMapper.getAdminRoleTypeList(AFTConstants.TECH_ADMIN);
		Admin admin = new Admin();
		admin.setId(b.getSalesmanId());
		admins.add(admin);
		pushTOrderNew(b);
		return admins;
	}
	/**
	 * 新建完成会员项目修改订单状态
	 * @param b
	 */
	private void pushTOrderNew(TOrderNewBo b) {
		List<TOrderTaskBo> l = tOrderTaskMapper.selectOrderTaskAll(b.getOrderNo(), 4);
		int counts =l.size();
		int x=0;
		for (TOrderTaskBo t : l) {
			if (t.getTaskStatus()>0) {
				x++;
			}
		}
		TOrderNew n = new TOrderNew();
		n.setOrderNo(b.getOrderNo());
		if (x==0) {
			n.setProcessStatus(ProcessStatus.YPZXSGLY.getCode());
		} else if(x<counts) {
			n.setProcessStatus(ProcessStatus.YBFPZXSGLY.getCode());
		} else if(x==counts) {
			n.setProcessStatus(ProcessStatus.YQBFPZXSGLY.getCode());
		}
		tOrderNewMapper.update(n);
	}

	/**
	 * 发送邮件使用
	 * @param type
	 * @param aid
	 * @param content
	 */
	private EmailBo sendMemberEmail(Integer type,String aid,String content) {
		Admin admin = adminMapper.selectById(aid);
		EmailBo bo = new EmailBo(NoticeStatus.getValueByCode(type), admin.getEmail(),content);
		return bo;
	}

	@Override
	public int deleteMemberSonProject(Integer id) {
		TOrderTask task = tOrderTaskMapper.queryById(id);
		tOrderTaskMapper.deleteById(id);
		List<TOrderTaskListBo> tOrderTaskListBos = tOrderTaskMapper.splitProjectList(task.getSplitSuper(),null);
		//如果没有子项目则修改上级
		if (tOrderTaskListBos==null||tOrderTaskListBos.isEmpty()){
			TOrderTask tOrderTask=new TOrderTask();
			tOrderTask.setId(task.getSplitSuper());
			tOrderTask.setSplitStatus(0);
			tOrderTaskMapper.update(tOrderTask);
		}
		tTaskMidMapper.deleteByPrimaryKey(id);
		tTaskMemberMapper.deleteByPrimaryKey(id);
		tTaskLogMapper.deleteByPrimaryKey(id);
		tTaskMemberMapper.updateServiceYearBySplitSuper(task.getSplitSuper());
		return 1;
	}

	@Override
	public boolean checkOrderProcessStatus(Integer tid, Integer processStatus) {
		TOrderNew tOrderNew = tOrderNewMapper.checkOrderProcessStatus(tid);
		if (tOrderNew.getProcessStatus()>processStatus){
			return true;
		}
		return false;
	}


	@Override
	public void updateMidServiceProject(String orderNo) {
		List<TOrderTaskBo> taskBos = tOrderTaskMapper.selectOrderTaskAll(orderNo, 4);
		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());
					String contacts=taskBo.getContacts()!=null?taskBo.getContacts():"暂无";
					ps=ps.append("-").append(str).append("-").append(contacts).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);
		}
	}

	@Override
	public Integer addProjectStop(InputProjectStop in) {
		String[] split = in.getIds().split(",");
		Date date = new Date();
		String adminId = TokenManager.getAdminId();
		for (String s : split) {
			Integer id=Integer.valueOf(s);
			TaskStop use = taskStopMapper.selectByTid(id);
			if (use!=null){
				throw new BusinessException(String.format("项目[%s]暂停流程已存在，请先走完流程",id));
			}
			TOrderTaskDetailBo orderOp = tOrderTaskMapper.getOrderTaskDetail(id);

			if (orderOp.getDeleteSign()==2){
				throw new BusinessException(String.format("订单[%s]存在变更审核，请先走完流程",orderOp.getOrderNo()));
			}
			TaskStop ts = new TaskStop();
			ts.setTid(id);
			ts.setType(in.getType());
			ts.setStatus(0);
			ts.setReason(in.getReason());
			ts.setAnnexUrl(in.getAnnexUrl());
			ts.setCreateBy(adminId);
			ts.setCreateTime(date);
			taskStopMapper.insertSelective(ts);
			TaskStopLog log = new TaskStopLog();
			log.setTaskStopId(ts.getId());
			log.setReason(in.getReason());
			log.setCreateBy(adminId);
			log.setCreateTime(date);
			taskStopLogMapper.insertSelective(log);
			TTaskMid tt=new TTaskMid();
			tt.setTid(id);
			tt.setStopStatus(0);
			tt.setStopType(in.getType());
			tTaskMidMapper.updateByTid(tt);
		}
		asyncUtils.addProjectSotpNotic(0, in.getType(),in.getIds(),null);
		return 1;
	}

	@Override
	public Integer updateProjectStop(InputProjectStop in) {
		TaskStop use = taskStopMapper.selectByPrimaryKey(in.getStopId());
		Date date = new Date();
		String adminId = TokenManager.getAdminId();
		TaskStop ts = new TaskStop();
		ts.setId(in.getStopId());
		ts.setType(in.getType());
		ts.setStatus(0);
		ts.setReason(in.getReason());
		ts.setAnnexUrl(in.getAnnexUrl());
		taskStopMapper.updateByPrimaryKeySelective(ts);
		TaskStopLog log = new TaskStopLog();
		log.setTaskStopId(ts.getId());
		log.setReason(in.getReason());
		log.setCreateBy(adminId);
		log.setCreateTime(date);
		taskStopLogMapper.insertSelective(log);
		TTaskMid tt=new TTaskMid();
		tt.setTid(use.getTid());
		tt.setStopStatus(0);
		tTaskMidMapper.updateByTid(tt);
		asyncUtils.addProjectSotpNotic(0, in.getType(),use.getTid().toString(),null);
		return 1;
	}

	@Override
	public Pagination<?> selectProjectStop(String orderNo, String userName, String deps, String contractNo, String projectName,
										   Integer status,String startTime,String endTime,String receiverId,
										   Integer shiroType,Integer pageNo, Integer pageSize) {
		Map<String,Object>params =new HashMap<>();
		if (orderNo!=null)params.put("orderNo",orderNo);
		if (userName!=null)params.put("userName",userName);

		if (contractNo!=null)params.put("contractNo",contractNo);
		if (projectName!=null)params.put("projectName",projectName);
		if (status!=null)params.put("status",status);
		if (startTime!=null)params.put("startTime",startTime);
		if (endTime!=null)params.put("endTime",endTime+" 23:59:59");
		if (receiverId!=null)params.put("receiverId",receiverId);
		if (deps!=null){
			if (TokenManager.hasRole(AFTConstants.SALESMAN_ADMIN)){
				List<String> list= JSON.parseArray(deps,String.class);
				params.put("deps",departmentService.selectSubDeps(list));
			}else {
				List<String> list= JSON.parseArray(deps,String.class);
				params.put("deps",list);
			}
		}
		if (shiroType==0){
			if (TokenManager.hasRole(AFTConstants.SALESMAN)||TokenManager.hasRole(AFTConstants.SALESMAN_MANAGER)){
				params.put("shiro",1);
				params.put("aid",TokenManager.getAdminId());
			}
		}else if (shiroType==1){
			if (TokenManager.hasRole(AFTConstants.SUPERADMIN)){
				params.put("shiro",0);

			}else  if (TokenManager.hasRole(AFTConstants.SALESMAN_ADMIN)){
				params.put("shiro",2);
				List<String> myDeps = departmentService.selectMyDeps();
				params.put("myDeps",myDeps);
			}
		}else {
			return new Pagination<>();
		}

		return findPage("selectProjectStopList","selectProjectStopCount",params,pageNo,pageSize);
	}

	@Override
	public List<TaskStopLogBo> projectStopList(Integer taskStopId) {
		List<TaskStopLogBo> list =taskStopLogMapper.selectListBySoptId(taskStopId);
		TaskStopLogBo taskStopLogBo = list.get(list.size() - 1);
		if (taskStopLogBo.getStatus()==0){
			TaskStopLogBo newBo=new TaskStopLogBo();
			TaskStop taskStop = taskStopMapper.selectByPrimaryKey(Long.valueOf(taskStopId));
			TOrderTask tOrderTask = tOrderTaskMapper.queryById(taskStop.getTid());
			TOrderNewBo tOrderNew = tOrderNewMapper.getOrderNewDetail(tOrderTask.getOrderNo());
			List<Admin> admins = adminMapper.listAdminBydepIdAndRoleType(tOrderNew.getOrderDep(),AFTConstants.SALESMAN_ADMIN);
			StringBuilder str=new StringBuilder();
			for (Admin admin : admins) {
				if (!str.toString().contains(admin.getName()))str.append(admin.getName()).append(",");
			}
			newBo.setCreateName(str.substring(0,str.length()-1));
			list.add(newBo);
		}
		return list;
	}

	@Override
	public Object pushExamineProjectStop(InputTaskStopLog in) {
		TaskStop use = taskStopMapper.selectByPrimaryKey(in.getTaskStopId());
		TaskStop t=new TaskStop();
		t.setId(use.getId());
		TOrderTask task = tOrderTaskMapper.queryById(use.getTid());
		if (in.getStatus()==1){
			t.setStatus(1);
			StringBuffer str =new StringBuffer();
			str.append("项目状态修改为：");
			if (use.getType()==0){
				task.setProjectStatus(NewProjectStatus.ZT.getCode());
				str=str.append("已暂停");
				//处理时间
				pushExamineTaskTimes(task);

			}else {
				task.setProjectStatus(NewProjectStatus.JXZ.getCode());
				str=str.append("进行中");
			}
			TaskLog taskLog = new TaskLog();
			taskLog.setStopId(in.getTaskStopId());
			taskLog.setTaskId(use.getTid());
			taskLog.setContent(str.toString());
			taskLog.setAid(use.getCreateBy());
			taskLogMapper.insertSelective(taskLog);
			TOrderTask task2 =new TOrderTask();
			task2.setId(task.getId());
			task2.setProjectStatus(task.getProjectStatus());

			tOrderTaskMapper.update(task2);
			tOrderMidMapper.updateStopProjectByOrderNo(task.getOrderNo());
			if (task.getSplitStatus()==1){
				TOrderTask tot=new TOrderTask();
				tot.setSplitSuper(task.getId());
				tot.setProjectStatus(NewProjectStatus.ZT.getCode());
				tOrderTaskMapper.updateBySuperId(tot);
			}
			updateMidServiceProject(task.getOrderNo());
			examineProjectSotpAddNotice(task,1,use.getType());
		}else if(in.getStatus()==2) {
			t.setStatus(2);
			examineProjectSotpAddNotice(task,2,use.getType());
		}
		TTaskMid tt=new TTaskMid();
		tt.setTid(use.getTid());
		tt.setStopStatus(in.getStatus());
		tTaskMidMapper.updateByTid(tt);
		TaskStopLog tsl=new TaskStopLog();
		tsl.setTaskStopId(in.getTaskStopId());
		tsl.setReason(in.getReason());
		tsl.setStatus(in.getStatus());
		tsl.setCreateTime(new Date());
		tsl.setCreateBy(TokenManager.getAdminId());
		taskStopLogMapper.insertSelective(tsl);
		return taskStopMapper.updateByPrimaryKeySelective(t);
	}

	private void pushExamineTaskTimes(TOrderTask task) {
		TaskTime tt=new TaskTime();
		tt.setTid(task.getId());
		tt.setProjectStatus(task.getProjectStatus());
		tt.setDateTime(new Date());
		int i = taskTimeMapper.updateByTidAndProjectSelective(tt);
		if (i==0){
			taskTimeMapper.insertSelective(tt);
		}
	}


	private void examineProjectSotpAddNotice(TOrderTask task,Integer status,Integer sotpType) {
		asyncUtils.addProjectSotpNotic(status,sotpType,null,task);
	}


	@Override
	public Object updateSatisfactionDegree(Integer id, Integer formRetrieve, Integer satisfactionDegree, String satisfactionDegreeUrl) {
		TOrderTask in=new TOrderTask();
		in.setId(id);
		in.setFormRetrieve(formRetrieve);
		if(formRetrieve==2){
			if(satisfactionDegree!=null)in.setSatisfactionDegree(satisfactionDegree);
			in.setSatisfactionDegreeUrl(satisfactionDegreeUrl);
		}else if (formRetrieve==4){
			in.setSatisfactionDegreeUrl(satisfactionDegreeUrl);
		}
		return tOrderTaskMapper.update(in);
	}

	@Override
	public Object dispatchTaskLog(Integer id) {
		return tTaskLogMapper.selectByTid(id);
	}

	@Override
	public void pushProjectCompleteDate() {
		List<TOrderTask> tOrderTasks = tOrderTaskMapper.selectAll();
//		List<TOrderTask> tOrderTasks = tOrderTaskMapper.selectTasksByTid(2960);
		for (TOrderTask e : tOrderTasks) {
		updateProjectCompleteDate(e);
		}
		List<String> collect = tOrderTasks.stream().map(TOrderTask::getTaskReceiver).collect(Collectors.toList());
		Set<String> aids=new HashSet<>(collect);
		for (String aid : aids) {
			asyncUtils.updateAdminByAid(aid);
		}
	}

    @Override
    public boolean checkMemberType(InputSonProject in) {
		BusinessProject businessProject = businessProjectMapper.selectByTid(in.getTid());
		if (businessProject.getProjectType()==1){
			if (in.getHtMember()==null&&in.getAdditionalDeduction()==null&&in.getRdAwardsubsidy()==null){
				return  true;
			}
			if (in.getHtMember()==0&&in.getAdditionalDeduction()==0&&in.getRdAwardsubsidy()==0){
				return  true;
			}
		}
		return false;
    }

	@Override
	public Object updateMemberSonProject(InputSonProject in) {
		TOrderTask newT =  tOrderTaskMapper.queryById(in.getTid());
		newT.setId(in.getTid());
		newT.setTaskComment(in.getTaskComment());
		if (in.getHtMember()!=null)newT.setHtMember(in.getHtMember());
		if (in.getAdditionalDeduction()!=null)newT.setAdditionalDeduction(in.getAdditionalDeduction());
		if (in.getRdAwardsubsidy()!=null)newT.setRdAwardsubsidy(in.getRdAwardsubsidy());
		tOrderTaskMapper.update(newT);
		TOrderTask tOrderTask = tOrderTaskMapper.queryById(newT.getSplitSuper());
		pushFatherTask(tOrderTask);
		tOrderTaskMapper.update(tOrderTask);
		return newT;
	}

	@Override
	public boolean checkMember(InputSonProject in) {
		BusinessProject businessProject = businessProjectMapper.selectByTid(in.getTid());
        return businessProject.getProjectType() == 1 && (in.getHtMember() == 0 && in.getAdditionalDeduction() == 0 && in.getRdAwardsubsidy() == 0);
    }

	@Override
	public void updateServiceYearBySplitSuper(InputSonProject in ) {
		tTaskMemberMapper.updateServiceYearBySplitSuper(in.getTid());
	}

	/**
	 *
	 * @param e
	 */
	private void  updateProjectCompleteDate(TOrderTask e ) {
			ObjectMapper mapper = new ObjectMapper();
			try {
				Map map =null;
				if(StringUtils.isNotBlank(e.getTimeRecord()))map = mapper.readValue(e.getTimeRecord(), Map.class);
				String[] str={"4","5","6","7","8","9","10","11","13","14","15","16","17","18","19","20","27"};
				String date = null;
				boolean flag = false;
				for (String s : str) {
					//判定时间是否为空
					if (StringUtils.isEmpty(date)){
                        String s1 = null;
                        if (map != null) {
                            s1 = pushStr(s, map);
							if (s1!=null)date=s1;
                        }
					}
					if (Integer.parseInt(s)==e.getProjectStatus()) {
						flag = true;
						break;
					}
				}
				//如果是完成则修改成完成
				if(flag){
					TOrderTaskDetailBo orderTaskDetail = tOrderTaskMapper.getOrderTaskDetail(e.getId());
					Integer sort = orderTaskDetail.getSort();
						TOrderTask t=new TOrderTask();
						t.setId(e.getId());
						t.setCompleteStatus(1);
						if (date !=null)e.setCompleteDate(DateUtils.parseDate(date));
						//只有带评分和无才需要修改评分状态
						if (sort==3||sort==6||sort==9){
								// 创建一个SimpleDateFormat对象用于解析日期字符串
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
								// 解析字符串"2024-01-01"为Date对象
								Date targetDate = sdf.parse("2024-01-01");
								// 使用compareTo方法比较两个日期
								int result=0;
								if (e.getTaskDistributionTime()!=null){
									result = targetDate.compareTo(e.getTaskDistributionTime());
									//2024-01-01之后派单返回-1

									if (result <0){
										t.setScoreStatus(1);
									}else {
										t.setScoreStatus(0);
									}
								}
								tOrderTaskMapper.update(t);
								taskScoreService.updateTOrderNewByTid(e.getId());
						}

				}
			} catch (JsonProcessingException | ParseException ex) {
				throw new RuntimeException(ex);
			}

    }

	private String pushStr(String s,Map map) {
		String date=null;
		Map map2 = (Map) map.get(s);
		if (map2!=null){
			date = (String) map2.get("date");
		}
		return date;
	}

}
