package com.goafanti.order.service.impl;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.mail.MessagingException;

import com.alibaba.fastjson.JSON;
import com.goafanti.admin.service.DepartmentService;
import com.goafanti.common.bo.*;
import com.goafanti.common.bo.Error;
import com.goafanti.common.dao.*;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.*;
import com.goafanti.common.utils.excel.NewExcelUtil;
import com.goafanti.order.bo.*;
import com.goafanti.order.controller.InputTaskStopLog;
import com.goafanti.order.enums.*;
import com.goafanti.order.service.OrderChangeService;
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 com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.enums.ChannelStatus;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.enums.OrderLogProcess;
import com.goafanti.common.error.BusinessException;
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.InputProjectCheck;
import com.goafanti.order.service.OrderNewService;
import com.goafanti.order.service.OrderProjectService;
import com.goafanti.organization.bo.OutPaymentNode;
import com.goafanti.techproject.enums.TaskState;

@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 OrderChangeService orderChangeService;



	@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.selectByPrimaryKey(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.selectByPrimaryKey(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.XMDDPD.getCode(),remarks);
			t.setManagerId(taskReceiverId);
			t.setConsultantId(null);
			//设置催款触发
			orderNewService.pushOrderDun(tn);
			//未锁定客户就锁定客户
			pushUser(t, tn, date);
			//处理客户已派项目
			projectDistributionPushUserMid(tn);
		}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.updateByPrimaryKey(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);
		//处理订单信息
		checkProjiectAllocation(t.getOrderNo());
		pushTaskChange(TokenManager.getAdminId(),taskReceiverId,type,t.getOrderNo());
		return 1;
	}

	/**
	 *
	 * @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);
		}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);
		}
		newOrderChangeMapper.updateTaskExamineName(aid,taskReceiverId,OrderChangeProcess.JSY.getCode());
		newOrderChangeMapper.updateTaskExamineName(aid,taskReceiverId,OrderChangeProcess.JSJL.getCode());
	}

	private void projectDistributionPushUserMid(TOrderNew tn) {
		if (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;
			Integer 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);
		}
	}


	/**
	 * 	推动客户、业务渠道的锁定
	 * @param t
	 * @param tn
	 * @param date
	 */
	private void pushUser(TOrderTask t, TOrderNew tn, Date date) {
		if (userMapper.checkLock(tn.getBuyerId())<1) {
			userLockReleaseMapper.updateByAidAndUid(tn.getSalesmanId(),tn.getBuyerId());
			userMapper.updateShareType(tn.getBuyerId(),tn.getSalesmanId());
		}
		//未锁定业务就锁定业务
		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);
		}
			UserBusiness ub=new UserBusiness();
			ub.setId(UUID.randomUUID().toString());
			ub.setUid(tn.getBuyerId());
			ub.setAid(tn.getSalesmanId());
			ub.setFollowSituation(5);
			ub.setCustomerStatus(4);
			ub.setCreateTime(date);
			ub.setUpdateTime(date);
			ub.setRemarks("派单自动锁定客户");
			ub.setBusinessProjectId(t.getCommodityId());
			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 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.selectByPrimaryKey(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.updateByPrimaryKeySelective(tNew);
	}

	@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);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<TOrderTaskListBo> orderTaskList(inuptTaskListBo ib) {
		Map<String, Object> params = new HashMap<String, Object>();
		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.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.getCid() !=null) params.put("cid", ib.getCid());
		List<String> fids=new ArrayList<>();
		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);
		} else {
			params.put("role", 0);
			params.put("aid", TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
		}
		Pagination<TOrderTaskListBo> p = (Pagination<TOrderTaskListBo>)findPage("selectOrderTaskListByPage", "selectOrderTaskListCount", 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);
		if (TokenManager.hasRole(AFTConstants.SUPERADMIN)||TokenManager.hasRole(AFTConstants.APPROVAL_DECISION)
				||TokenManager.hasRole(AFTConstants.APPROVAL_DECISION)||TokenManager.hasRole(AFTConstants.TECH_ADMIN)
					||TokenManager.getAdminId().equals(t.getTaskReceiver())) {
			return t;
		}else {
			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.updateByPrimaryKeySelective(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.updateByPrimaryKeySelective(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.selectByPrimaryKey(b.getTid());//查询出项目信息
		if(b.getProjectStatus()!=task2.getProjectStatus()){
				TTaskMid taskMid = new TTaskMid();
				taskMid.setTid(b.getTid());
			if(b.getProjectStatus()==NewProjectStatus.YLX.getCode()||b.getProjectStatus()==NewProjectStatus.YNGS.getCode()){
				t.setSetUpStatus(1);
				taskMid.setSetUpCount(task2.getCommodityQuantity());
				if (b.getProjectStatus()==NewProjectStatus.YNGS.getCode()){
					t.setIfPublicity(1);
					taskMid.setPromulgateCount(task2.getCommodityQuantity());
				}
			}
			//大于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);
			}
			tOrderTaskMapper.updateByPrimaryKeySelective(t);
			projectSplitPush(b.getTid(), b.getProjectStatus(),task2);
			pushTaskLog(b.getTid(), b.getProjectStatus());
			updateMidServiceProject(task2.getOrderNo());
		}
		return 1;
	}


	/**
	 * 推动项目日志
	 * @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.updateByPrimaryKeySelective(fatherTask);
			TOrderTask task3=tOrderTaskMapper.selectByPrimaryKey(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.updateByPrimaryKeySelective(task3);
			TOrderTask task4 = tOrderTaskMapper.selectByPrimaryKey(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.selectByPrimaryKey(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.selectByPrimaryKey(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.selectByPrimaryKey(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.updateByPrimaryKeySelective(tNew);
		}
		if (task.getProjectStatus()==NewProjectStatus.YTJ.getCode()||task.getProjectStatus()==NewProjectStatus.YLX.getCode()||
				task.getProjectStatus()==NewProjectStatus.YNGS.getCode()) {
			TOrderBonus tb=new TOrderBonus();
			TOrderNew t=tOrderNewMapper.selectByPrimaryKey(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.selectByPrimaryKey(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  , 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);
		Pagination<TOrderTaskListBo> p = (Pagination<TOrderTaskListBo>)findPage("selectTaskListByPage", "selectTaskListCount", params, pageNo, pageSize);
		return p;
	}
	@Override
	public List<TaskLogBo> TaskLogList(Integer id) {
		return taskLogMapper.selectTaskLogList(id);
	}
	@Override
	public int createTaskProgress(TaskProgressBo t) {
		TaskProgress tp=new TaskProgress();
		TOrderTask tt=tOrderTaskMapper.selectByPrimaryKey(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.selectByPrimaryKey(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.selectByPrimaryKey(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.updateByPrimaryKeySelective(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 ,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.updateByPrimaryKeySelective(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);
		return (Pagination<OutMemberList>) findPage("findMemberList","findMemberCount",map,in.getPageNo(), in.getPageSize());
	}

	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());
		map.put("aid",TokenManager.getAdminId());
	}

	@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());
			}
		}
		NewExcelUtil<OutMemberList> excelUtil=new NewExcelUtil<>(OutMemberList.class);
		return excelUtil.exportExcel(list,"会员审核列表",uploadPath);
	}



	@Override
	public int pushExamineMemberProject(InputMenber in) {
		TOrderTask task=tOrderTaskMapper.selectByPrimaryKey(in.getId());
		Integer status=1;
		TOrderTask nt=new TOrderTask();
		nt.setId(task.getId());
		Integer result=0;
		Integer notice=NoticeStatus.MENBER_YES.getCode();
		TOrderNewBo ono = tOrderNewMapper.getSaleIdByOno(task.getOrderNo());
		// 1=通过 0=驳回
		if (in.getResult()==1){
			//0=财务 1=特批
			if (in.getType()==0){
				if(task.getProcessStatus()!=1)throw  new BusinessException("审核状态错误");
				if (task.getMemberType()==1||task.getMemberType()==2){
					nt.setProcessStatus(2);
					status=1;
				}else if (task.getMemberType()==0){
					nt.setProcessStatus(3);
					status=3;
					result=1;
				}
			}else if(in.getType()==1){
				if(task.getProcessStatus()!=2)throw  new BusinessException("审核状态错误");
				nt.setProcessStatus(3);
				status=3;
				result=1;
			}
		}else if (in.getResult()==0){
			status=2;
			nt.setProcessStatus(4);
			notice=NoticeStatus.MENBER_NO.getCode();
		}
		addNoticMember(notice, ono, in.getType(),result);
		addMemberLog(in.getId(),status,in.getRemarks());
		if (nt.getProcessStatus()==3){
			tTaskMemberMapper.updateServiceYearBySplitSuper(task.getSplitSuper());
		}
		return tOrderTaskMapper.updateByPrimaryKeySelective(nt);
	}



	@Override
	public int updateMemberProject(InputAddTask t) {
		TOrderTask task=tOrderTaskMapper.selectByPrimaryKey(t.getId());
		if(task.getProcessStatus()!=4)throw  new BusinessException("审核状态错误，无法提交。");
		addMemberLog(t.getId(),0,"修改重新发起");
		t.setProcessStatus(1);
		TOrderNewBo ono = tOrderNewMapper.getSaleIdByOno(task.getOrderNo());
		addNoticMember(NoticeStatus.MENBER_START.getCode(), ono, null,0);
		return orderNewService.updateOrderTask(t);
	}
	@Override
	public void addMemberLog(Integer id,Integer status ,String remarks){
		MemberLog log = new MemberLog();
		log.setPid(id);
		log.setStatus(status);
		log.setRemarks(remarks);
		log.setAid(TokenManager.getAdminId());
		memberLogMapper.insertSelective(log);
	}

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

	@Override
	public TOrderTask addMemberSonProject(Integer tid, String serviceYear, String taskComment,Integer memberType,String pictureUrl) {
		Date date =new Date();
		TOrderTask tOrderTask =  tOrderTaskMapper.selectByPrimaryKey(tid);
		tOrderTask.setSplitStatus(1);
		tOrderTask.setSplitAid(TokenManager.getAdminId());
		tOrderTask.setSplitTime(date);
		tOrderTaskMapper.updateByPrimaryKey(tOrderTask);
		tOrderTask.setId(null);
		tOrderTask.setSplitStatus(2);
		tOrderTask.setSplitSuper(tid);
		if (memberType!=null){
			tOrderTask.setProcessStatus(1);
			tOrderTask.setMemberType(memberType);
			tOrderTask.setPictureUrl(pictureUrl);
		}
		Integer i=tOrderTaskMapper.getSplitCount(tid);
		i++;
		tOrderTask.setSplitId(i);
		tOrderTask.setCommodityQuantity(1);
		tOrderTask.setTaskComment(taskComment);
		tOrderTask.setMain(0);
		tOrderTask.setCommodityPrice(new BigDecimal(0));
		tOrderTaskMapper.insertSelective(tOrderTask);
		TTaskMember t = tTaskMemberMapper.selectByTid(tid);
		TOrderTaskBo tb=new TOrderTaskBo();
		BeanUtils.copyProperties(tOrderTask,tb);
		if (t.getServiceLife()!=null||t.getYearSum()!=null||t.getContractTerm()!=null||serviceYear!=null){
			TTaskMember ttm=new TTaskMember();
			ttm.setId(null);
			ttm.setTid(tOrderTask.getId());
			if(t.getServiceLife()!=null)ttm.setServiceLife(t.getServiceLife());
			ttm.setServiceYear(serviceYear);
			tb.setServiceYear(serviceYear);
			if(t.getYearSum()!=null)ttm.setYearSum(t.getYearSum());
			if(t.getContractTerm()!=null)ttm.setContractTerm(t.getContractTerm());
			tTaskMemberMapper.insertSelective(ttm);
		}

		orderNewService.addTaskMid(tOrderTask.getId(),tOrderTask.getCommodityId(), tOrderTask.getOrderNo());
		//处理主项目本次派单年份
		tTaskMemberMapper.updateServiceYearBySplitSuper(tid);
		addMemberLog(tOrderTask.getId(),0,"新增会员项目");
		addNoticMember(NoticeStatus.MENBER_START.getCode(),tOrderTask.getOrderNo(),null,0);
		return tb;
	}
	public void addNoticMember(Integer type,  String orderNo,Integer shiroType,Integer result) {
		TOrderNewBo tn = tOrderNewMapper.getSaleIdByOno(orderNo);
		addNoticMember(NoticeStatus.MENBER_START.getCode(),tn,null,0);
	}

	@Override
	public void addNoticMember(Integer type,  TOrderNewBo b,Integer shiroType,Integer result) {
		StringBuffer sb=new StringBuffer();
		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("发起会员项目，请及时审核");
			aid=b.getFinanceId();
		}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);
				}
			} 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){
			for (Admin admin : admins) {
				asyncUtils.addNotic(type,admin.getId(),sb.toString());
				sendMemberEmail(type,admin.getId(),sb.toString());
			}
		}else {
			asyncUtils.addNotic(type,aid,sb.toString());
			sendMemberEmail(type,aid,sb.toString());
		}
	}



	/**
	 * 会员项目完成审核调用
	 * @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.selectOrderTask(b.getOrderNo(), 0);
		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(4);
		} else if(x<counts) {
			n.setProcessStatus(5);
		} else if(x==counts) {
			n.setProcessStatus(6);
		}
		tOrderNewMapper.updateByPrimaryKeySelective(n);
	}

	/**
	 * 发送邮件使用
	 * @param type
	 * @param aid
	 * @param content
	 */
	private void sendMemberEmail(Integer type,String aid,String content) {
		Admin admin = adminMapper.selectByPrimaryKey(aid);
		EmailBo bo = new EmailBo(NoticeStatus.getValueByCode(type), admin.getEmail(),content);
		if(com.goafanti.common.utils.StringUtils.isNotBlank(admin.getEmail())) {
			asyncUtils.send(bo);
		}
	}

	@Override
	public int deleteMemberSonProject(Integer id) {
		TOrderTask task = tOrderTaskMapper.selectByPrimaryKey(id);
		tOrderTaskMapper.deleteByPrimaryKey(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.updateByPrimaryKeySelective(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, 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(",");

				}
				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 depId, String contractNo, String projectName,
										   Integer status,String startTime,String endTime,String receiverId, 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 (depId!=null)params.put("depId",depId);
		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 (TokenManager.hasRole(AFTConstants.SUPERADMIN)){
			params.put("shiro",0);
		}else if (TokenManager.hasRole(AFTConstants.SALESMAN)||TokenManager.hasRole(AFTConstants.SALESMAN_MANAGER)){
			params.put("shiro",1);
			params.put("aid",TokenManager.getAdminId());
		}else if (TokenManager.hasRole(AFTConstants.SALESMAN_ADMIN)){
			params.put("shiro",2);
			params.put("deps",departmentService.selectMyDeps());
		}else {
			return new Pagination<>();
		}
		return findPage("selectProjectSotpList","selectProjectSotpCount",params,pageNo,pageSize);
	}

	@Override
	public List<TaskStopLogBo> projectStopList(Integer taskStopId) {
		List<TaskStopLogBo> list =taskStopLogMapper.selectListBySoptId(taskStopId);
		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.selectByPrimaryKey(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("已暂停");
			}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.updateByPrimaryKeySelective(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 examineProjectSotpAddNotice(TOrderTask task,Integer status,Integer sotpType) {
		asyncUtils.addProjectSotpNotic(status,sotpType,null,task);
	}


}
