package com.goafanti.order.service.impl;


import com.alibaba.fastjson.JSON;
import com.goafanti.admin.bo.AdminListBo;
import com.goafanti.admin.service.DepartmentService;
import com.goafanti.common.bo.EmailBo;
import com.goafanti.common.bo.Error;
import com.goafanti.common.bo.OrderOperator;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.enums.OfficialPatentType;
import com.goafanti.common.enums.OrderLogProcess;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.*;
import com.goafanti.common.utils.excel.NewExcelUtil;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.JDBCIdGenerator;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.customer.bo.LockingReleaseBo;
import com.goafanti.order.bo.*;
import com.goafanti.order.enums.*;
import com.goafanti.order.service.OrderNewService;
import com.goafanti.order.service.OrderProjectService;
import com.goafanti.organization.bo.*;
import com.goafanti.patent.service.PatentNewService;
import groovy.transform.Synchronized;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
@EnableAsync
public class OrderNewServiceImpl extends BaseMybatisDao<TOrderNewMapper> implements OrderNewService {
	@Autowired
	private TOrderNewMapper	tOrderNewMapper;
	@Autowired
	private TOrderTaskMapper tOrderTaskMapper;
	@Autowired
	private NewOrderDunMapper	newOrderDunMapper;
	@Autowired
	private TOrderDunMapper tOrderDunMapper;
	@Autowired
	private TDunLogMapper tDunLogMapper;
	@Autowired
	private TOrderMidMapper	tOrderMidMapper;
	@Autowired
	private TOrderRefundMapper	tOrderRefundMapper;
	@Autowired
	private TOrderBackMapper	tOrderBackMapper;
	@Autowired
	private OrganizationContactBookMapper	organizationContactBookMapper;
	@Autowired
	private DepartmentMapper 	departmentMapper ;
	@Autowired
	private JDBCIdGenerator	idGenerator;
	@Autowired
	private AdminMapper	adminMapper;
	@Autowired
	private TOrderLogMapper tOrderLogMapper;
	@Autowired
	private TOrderExamineMapper	tOrderExamineMapper;
	@Autowired
	private IdleContractNoMapper	idleContractNoMapper;
	@Autowired
	private TOrderOutsourceMapper tOrderOutsourceMapper;
	@Autowired
	private UserLockReleaseMapper	userLockReleaseMapper;
	@Autowired
	private TArrearsDunMapper	tArrearsDunMapper;
	@Autowired
	private TOrderExtendMapper	tOrderExtendMapper;
	@Autowired
	private UserMapper	userMapper;
	@Autowired
	private OutsourceLogMapper	outsourceLogMapper;
	@Autowired
	private PaymentNodeMapper	paymentNodeMapper;
	@Autowired
	private ThirdPartyCompanyMapper	thirdPartyCompanyMapper;
	@Autowired
	private TTaskMidMapper	tTaskMidMapper;
	@Autowired
	private UserMidMapper	userMidMapper;
	@Autowired
	private ProjcetCheckLogMapper	projcetCheckLogMapper;
	@Autowired
	private OfficialFeePriceMapper	officialFeePriceMapper;
	@Autowired
	private PatentNewService	patentNewService;
	@Autowired
	private AsyncUtils	asyncUtils;
	@Autowired
	private PushOrderService pushOrderService;
	@Autowired
	private BusinessProjectMapper businessProjectMapper;
	@Autowired
	private BusinessCategoryMapper businessCategoryMapper;
	@Autowired
	private OrderProjectService orderProjectService;
	@Autowired
	private TTaskMemberMapper tTaskMemberMapper;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private TOrderPaymentMapper tOrderPaymentMapper;
	@Autowired
	private TOrderHighTechMapper tOrderHighTechMapper;
	@Autowired
	private FinanceCountMapper financeCountMapper;
	@Autowired
	private PublicReleaseMapper publicReleaseMapper;
	@Autowired
	private OrderYearMaxDurationMapper orderYearMaxDurationMapper;
	@Autowired
	private TOrderApprovalMapper tOrderApprovalMapper;
	@Autowired
	private TOrderPublicReleaseCountMapper tOrderPublicReleaseCountMapper;
	@Autowired
	private PublicConfigMapper publicConfigMapper;
	@Resource
	private TemporaryReceivablesMapper temporaryReceivablesMapper;
	@Autowired
	private ProjectAsyncService projectAsyncService;


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

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

	@Override
	public int createServiceOrder(String uid,Integer userType, Integer orderType,Integer salesType,String channelId,String other) {
		BigDecimal initial = new BigDecimal(0);
		Date date=new Date();
		TOrderNew t=new TOrderNew();
        String orderNo=idGenerator.generateId().toString();
		t.setOrderNo(orderNo);
		t.setOrderType(orderType);
		t.setUserType(userType);
		t.setOrderStatus(OrderNewState.DQD.getCode());
		t.setFirstAmount(initial);
		t.setTotalAmount(initial);
		t.setSettlementAmount(initial);
		t.setLiquidationStatus(LiquidationNewState.WAIT_PAY_FIRST_BALANCE.getCode());
		t.setProcessStatus(ProcessStatus.YPYXY.getCode());
		t.setProjectStatus(NewProjectStatus.WQD.getCode());
		t.setApproval(ApprovalNewState.FTP.getCode());
		//0-正常，1-作废，2-锁定
		t.setDeleteSign(0);
		t.setSalesmanId(TokenManager.getAdminId());
		t.setCreater(TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
		t.setOrderDep(adminMapper.selectById(TokenManager.getAdminId()).getDepartmentId());
		t.setCreateTime(date);
		t.setUpdateTime(date);
		t.setBuyerId(uid);
		t.setSalesType(salesType);
		if (salesType.equals(SalesTypes.qd.getCode()) &&channelId!=null){
			t.setChannelId(channelId);
		}
		if (other!=null ) {
			t.setOther(other);
		}
		User u=userMapper.queryById(uid);
		if(u.getShareType()!=null&&u.getShareType()==2){
			t.setNewUser(1);
		}else {
			t.setNewUser(0);
		}
		TOrderExtend te=new TOrderExtend();
		te.setOrderNo(orderNo);
		te.setServiceStatus(0);
		tOrderExtendMapper.insertSelective(te);
		addOrderExamine(t);
		return tOrderNewMapper.insertSelective(t);
	}

	private void addOrderExamine(TOrderNew o) {
		List<TOrderExamine> tOrderExamines = tOrderExamineMapper.selectByOrderNo(o.getOrderNo(),0);
		if (tOrderExamines.isEmpty()){
			addTOrderExamines(o);
		}
	}

	private List<TOrderExamine> addTOrderExamines(TOrderNew o) {
		tOrderExamineMapper.deleteByOrderNo(o.getOrderNo());
		OrganizationListOut dep = departmentMapper.selectAllById(o.getOrderDep());
		List<TOrderExamine> list =new ArrayList<>();
		if(!Objects.isNull(dep)){
			if (StringUtils.isNotBlank(dep.getFinanceId())){
				list.add(new TOrderExamine(o.getOrderNo(),0,dep.getFinanceId(),dep.getFinanceName()));
			}
			if (StringUtils.isNotBlank(dep.getRetrialFinanceId())){
				list.add(new TOrderExamine(o.getOrderNo(),0,dep.getRetrialFinanceId(),dep.getRetrialFinanceName()));
			}
			if(StringUtils.isNotBlank(dep.getTechAdminId())){
				list.add(new TOrderExamine(o.getOrderNo(),0,dep.getTechAdminId(),dep.getTechAdminName()));
			}
		}
		if (!list.isEmpty())tOrderExamineMapper.insertBatch(list);
		return list;
	}

	@Override
	public InputAddTask addOrderTask(InputAddTask t) {
		TOrderNew order=tOrderNewMapper.queryById(t.getOrderNo());
		checkOrder(order,t);
		t.setTaskStatus(TaskState.WFP.getCode());
		t.setProjectStatus(NewProjectStatus.WQD.getCode());
		if(t.getCommodityPrice()!=null) {
			order.setTotalAmount(order.getTotalAmount());
		}
		addTTaskMember(t);
		addTaskMid(t);
		//如果是会员添加同性质不同项目
		projectAsyncService.pushFinanceOrTechnology(t);
		return t;
	}





	private void addTTaskMember(InputAddTask t) {
		String str=tOrderTaskMapper.selectByidGetCname(t.getCommodityId());
		t.setCname(str);
		tOrderTaskMapper.insertSelective(t);
		addTTaskMember(t.getId(),t.getServiceLife(),t.getServiceYear(),t.getYearSum(),t.getContractTerm());
	}

	@Override
	public void addTTaskMember(Integer id, String serviceLife, String serviceYear, Integer yearSum, String contractTerm) {
		if (serviceLife!=null|| serviceYear!=null||yearSum!=null|| contractTerm!=null){
			TTaskMember ttm=new TTaskMember();
			ttm.setTid(id);
			if(serviceLife!=null)ttm.setServiceLife(serviceLife);
			if(serviceYear!=null)ttm.setServiceYear(serviceYear);
			if(yearSum!=null)ttm.setYearSum(yearSum);
			if(contractTerm!=null)ttm.setContractTerm(contractTerm);
			tTaskMemberMapper.insertSelective(ttm);
		}
	}

	@Override
	public int updateTag(String orderNo, Integer tag) {
		String[] str= orderNo.split(",");
		if(str.length>0){
			List<String> orderNos= Arrays.asList(str);
			tOrderNewMapper.updateTagByListOrderNo(orderNos,tag);
			return 1;
		}
		return 0;
	}

	@Override
	public int addTaskMid(Integer id, String commodityId, String orderNo) {
		InputAddTask t = new InputAddTask();
		t.setId(id);
		t.setCommodityId(commodityId);
		t.setOrderNo(orderNo);
		return  addTaskMid( t);
	}

	@Override
	public int addTaskMid(Integer id, String commodityId, String orderNo, Integer change) {
		InputAddTask t = new InputAddTask();
		t.setId(id);
		t.setCommodityId(commodityId);
		t.setOrderNo(orderNo);
		t.setChange(change);
		return  addTaskMid( t);
	}

	@Override
	public int addTaskMid(InputAddTask t) {
		TTaskMid tm=new TTaskMid();
		tm.setTid(t.getId());
		//判断这个项目是不是高新复审
		int highNewRetrial=0;
		BusinessProject b=businessProjectMapper.selectById(t.getCommodityId());
		if (b.getType()==5){
			int i=tOrderTaskMapper.getHighNewRetrial(t.getOrderNo());
			if (i>0) {
				highNewRetrial =1;
			}
			BusinessCategory bc =businessCategoryMapper.selectByPrimaryKey(b.getCid());
			if (bc !=null && bc.getSort().equals(6)){
				TOrderMid tom=new TOrderMid();
				tom.setOrderNo(t.getOrderNo());
				tom.setProjectType(1);
				tOrderMidMapper.updateByOrderNo(tom);
			}
		}
		tm.setHighNewRetrial(highNewRetrial);
		tm.setLastYear(t.getLastYear());
		tm.setLastYearCapital(t.getLastYearCapital());
		tm.setLastYearIncome(t.getLastYearIncome());
		//获取派单省份与部门
		TTaskMid dtails = tTaskMidMapper.getDtails(t.getId());
		tm.setDispatchProvince(dtails.getDispatchProvince());
		tm.setDutyDep(dtails.getDutyDep());
		tm.setChange(t.getChange());
		return tTaskMidMapper.insertSelective(tm);
	}

	@Override
	public int addMemberProject(InputAddTask t){
		TOrderNewBo tn = tOrderNewMapper.getSaleIdByOno(t.getOrderNo());
		addOrderTask(t);
		orderProjectService.addMemberLog(t.getId(),0,"新增会员项目",TokenManager.getAdminId());
		orderProjectService.addNoticMember(NoticeStatus.MENBER_START.getCode(),tn,null,0);
		return 1;
	}

	public void checkOrder(TOrderNew order,TOrderTask t){
		if(order == null) {
			throw new BusinessException(new Error(ErrorConstants.ORDER_NOT_EXIST, "" ,""));
		}
		if(order.getDeleteSign().equals(ActiveState.ABOLISH.getCode()) ) {
			throw new BusinessException(new Error(ErrorConstants.ORDER_ALREADY_FREEZE, order.getOrderNo(),""));
		}
		if(order.getDeleteSign().equals( ActiveState.LOCKING.getCode())) {
			throw new BusinessException(new Error(ErrorConstants.ORDER_ALREADY_REVOKE, order.getOrderNo(),""));
		}
		List<LockingReleaseBo> list=userLockReleaseMapper.checkTask(order.getBuyerId(),t.getCommodityId());
		if (list.size()>0) {
			for (LockingReleaseBo lockingReleaseBo : list) {
				if (!lockingReleaseBo.getAid().equals(order.getSalesmanId())) {
					throw new BusinessException(new Error( "该业务已经被其他人锁定","该业务已经被其他人锁定"));
				}
			}

		}

	}

	@Override
	public int updateOrderTask(InputAddTask t) {
		TOrderTask use=tOrderTaskMapper.queryById(t.getId());
		boolean flag=false;
		if(use.getCheckStatus()==1) {
			t.setCheckStatus(2);
			ProjcetCheckLog log=new ProjcetCheckLog();
			log.setTid(t.getId());
			log.setAid(TokenManager.getAdminId());
			StringBuffer str=new StringBuffer();
			if ((t.getOfficialCost()==null&&t.getCostReduction()==null&&t.getPatentType()==null)||
					(t.getOfficialCost().equals(use.getOfficialCost()) && t.getPatentType().equals(use.getPatentType()) && t.getCostReduction().equals(use.getCostReduction()))) {
				str.append("未做任何修改。");
			}else {
				str.append("修改了：");
				if (t.getPatentType()!=null&&
						(use.getPatentType()==null||!use.getPatentType().equals(t.getPatentType()))) {
					str.append("官费类型");
				}
				if (t.getOfficialCost()!=null&& !use.getOfficialCost().equals(t.getOfficialCost())) {
					str.append(",").append("有无官费");
						flag=true;
				}
				if (t.getCostReduction()!=null&& !use.getCostReduction().equals(t.getCostReduction())) {
					str.append(",").append("有无费减");
						flag=true;
				}
					str.append("。");
			}
			log.setRemarks(str.toString());
			log.setStatus(1);
			OrderOperator oo=tOrderTaskMapper.selectAidByParam(t.getId());
			if (oo!=null&&oo.getOrderNo()!=null&&oo.getSalesmanId()!=null) {
				Notice n =new Notice();
				String str2=String.format("[%s]完成了专利核对，客户名称[%s]订单编号[%s]项目编号[%s]。", oo.getSalesmanName(),oo.getBuyerName(),oo.getOrderNo(),oo.getTid());
				n.setId(UUID.randomUUID().toString());
				n.setAid(oo.getTechId());
				n.setNoticeType(NoticeStatus.ITEM_CHECK_END.getCode());
				n.setContent(str2);
				n.setReaded(0);//未读
				asyncUtils.addNoticAndEmail(n);
			}
			projcetCheckLogMapper.insertSelective(log);
		}
		//新增保存修改订单处理勾选项
		updateTaskMember(t);
		int  i=tOrderTaskMapper.update(t);
		if (t.getServiceLife()!=null||t.getServiceYear()!=null||t.getYearSum()!=null||t.getContractTerm()!=null){
			TTaskMember ttm=new TTaskMember();
			ttm.setTid(t.getId());
			if(t.getServiceLife()!=null)ttm.setServiceLife(t.getServiceLife());
			if(t.getServiceYear()!=null)ttm.setServiceYear(t.getServiceYear());
			if(t.getYearSum()!=null)ttm.setYearSum(t.getYearSum());
			if(t.getContractTerm()!=null)ttm.setContractTerm(t.getContractTerm());
			if (tTaskMemberMapper.updateByTid(ttm)==0){
				tTaskMemberMapper.insertSelective(ttm);
			}
			//如果是拆分主项目则同时改变子项目
			if (use.getSplitStatus()==1){
				tTaskMemberMapper.updateSplitSuper(use.getId(),t.getServiceLife(),t.getServiceYear(),t.getYearSum(),t.getContractTerm());
			}
		}
		if (t.getLastYear()!=null||t.getLastYearIncome()!=null||t.getLastYearCapital()!=null){
			TTaskMid tTaskMid = new TTaskMid();
			tTaskMid.setTid(t.getId());
			tTaskMid.setLastYear(t.getLastYear());
			tTaskMid.setLastYearIncome(t.getLastYearIncome());
			tTaskMid.setLastYearCapital(t.getLastYearCapital());
			tTaskMidMapper.updateByTid(tTaskMid);
		}
		if (flag) {
			patentNewService.updateCostReduction(t.getId());
		}
		return i;
	}


	private void updateTaskMember(InputAddTask t) {

//		List<TaskSon> list= JSON.parseArray(t.getSonListStr(),TaskSon.class);

		List<TOrderTaskListBo> list = tOrderTaskMapper.splitProjectList(t.getId(), 1);
		int a=0,b=0,c=0;
		for (TOrderTaskListBo e : list) {
			if (a==0&&e.getHtMember()!=null&&e.getHtMember()==1)a=e.getHtMember();
			if (b==0&&e.getAdditionalDeduction()!=null&&e.getAdditionalDeduction()==1)b=e.getAdditionalDeduction();
			if (c==0&&e.getRdAwardsubsidy()!=null&&e.getRdAwardsubsidy()==1)c=e.getRdAwardsubsidy();
		}
		t.setHtMember(a);
		t.setAdditionalDeduction(b);
		t.setRdAwardsubsidy(c);
	}

	@Override
	public int delectOrderTask(Integer id) {
		//连带催款一起删除
		newOrderDunMapper.deleteByTid(id);
		tOrderTaskMapper.deleteBySplitId(id);
		return tOrderTaskMapper.deleteById(id);
	}

	@Override
	public List<TOrderTaskBo> selectOrderTask(String orderNo,Integer type) {
		if (TokenManager.hasRole(AFTConstants.SALESMAN)||TokenManager.hasRole(AFTConstants.SALESMAN_MANAGER)){
			if (type==null) {
				type=0;
			}
		}else {
			if (type==null) {
				type=1;
			}
		}
		List<TOrderTaskBo> list=tOrderTaskMapper.selectOrderTask(orderNo,type);
			for (TOrderTaskBo t : list) {
				if (TokenManager.hasRole(AFTConstants.SALESMAN)&&TokenManager.hasRole(AFTConstants.TECH)) {
					//如果是双角色不做处理。
				} else if (TokenManager.hasRole(AFTConstants.SALESMAN)) {
				t.setOutsourceName("****");
				t.setOutsourcePrice(new BigDecimal(0));
				t.setDeclareUser("****");
				t.setDeclarePwd("****");
				t.setCertificateNumber("****");
				}else if (TokenManager.hasRole(AFTConstants.TECH)) {
					//设置隐藏金额
					t.setCommodityPrice(null);
					}
				if(t.getPatentType()!=null) {
					t.setPatentTypeName(OfficialPatentType.getValueByCode(t.getPatentType()));
				}
				//如果有拆分获取拆分数据
				if (t.getSplitStatus()==1){
					List<TOrderTaskListBo> l=orderProjectService.splitProjectList(t.getId(),type);
					t.setSplitList(l);
				}
		}
		return list;
	}

	@Override
	@Transactional
	public int updateServiceOrder(TOrderNewWithBLOBs t, Integer isSubmit) {
		Date date=new Date();
		TOrderNew t2=tOrderNewMapper.queryById(t.getOrderNo());
		//判断手机号码是否存在
		if (StringUtils.isNotBlank(t.getContacts())&&StringUtils.isNotBlank(t.getContactMobile())&&
				organizationContactBookMapper.checkContacts(t2.getBuyerId(), t2.getContactMobile(),TokenManager.getAdminId()==null?"1":TokenManager.getAdminId() )>0) {
			OrganizationContactBook contactBook=new OrganizationContactBook();
			contactBook.setId(UUID.randomUUID().toString());
			contactBook.setAid(TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
			contactBook.setUid(t2.getBuyerId());
			contactBook.setName(t.getContacts());
			contactBook.setMobile(t.getContactMobile());
			organizationContactBookMapper.insertSelective(contactBook);
		}
		Admin a = adminMapper.selectById(TokenManager.getAdminId());
		if (StringUtils.isBlank(t.getOrderDep())) {
			t.setOrderDep(a.getDepartmentId());
		}
		//处理特批类型相关字段
		pushApprovalType(t);
		if (t.getKnowledgeServices()!=null||t.getAuditServices()!=null||t.getAddDeductionServices()!=null){
			TOrderHighTech tighTech=new TOrderHighTech();
			tighTech.setOrderNo(t.getOrderNo());
			tighTech.setKnowledgeServices(t.getKnowledgeServices());
			tighTech.setAuditServices(t.getAuditServices());
			tighTech.setAddDeductionServices(t.getAddDeductionServices());
			tighTech.setKnowledgeOther(t.getKnowledgeOther());
			tighTech.setAuditOther(t.getAuditOther());
			tighTech.setAddDeductionOther(t.getAddDeductionOther());
			int i=tOrderHighTechMapper.updateByOrder(tighTech);
			if(i==0){
				tOrderHighTechMapper.insertSelective(tighTech);
			}
		}else {
			tOrderHighTechMapper.deleteByOrderNo(t.getOrderNo());
		}
		//如果修改了部门she审核财务也要切换
		if(!t.getOrderDep().equals(t2.getOrderDep())) {
			tOrderExamineMapper.deleteByOrderNo(t.getOrderNo());
			addOrderExamine(t);
		}

		//订单提交
		if (isSubmit==1) {

			t2.setApproval(t.getApproval());
			addOrderLog(t2.getOrderNo(),OrderLogProcess.TJ.getCode(), null);
			if(t2.getProcessStatus()<ProcessStatus.YPYXJL.getCode()) {
				//添加营销管理员审核经理
					Integer orderStatus=OrderNewState.QDDS.getCode();
					if (a.getManagerId()!=null){
						t.setProcessStatus(ProcessStatus.YPYXJL.getCode());
					}else {
						if (TokenManager.hasRole(AFTConstants.SALESMAN_ADMIN)){
							addOrderLog(t2.getOrderNo(),OrderLogProcess.SH.getCode(), "管理员跳过自己审核");
							t.setProcessStatus(ProcessStatus.YPCW_JSZJ.getCode());
							orderStatus=OrderNewState.QDSHTG.getCode();
							Admin admin=adminMapper.selectFinanceAdminByOrderDep(t2.getOrderDep());
							updateFinanceCount(admin.getId(),t2.getCreateTime());
						}else {
							addOrderLog(t2.getOrderNo(),OrderLogProcess.YXJLTT.getCode(), "无经理跳过审核");
							t.setProcessStatus(ProcessStatus.YPYXGLY.getCode());
						}
					}
					t.setOrderStatus(orderStatus);

			}
			//特批逻辑处理
			if (t2.getApproval()==ApprovalNewState.TPBH.getCode()||
					t2.getApproval()==ApprovalNewState.DSZBH.getCode()||
					t2.getApproval()==ApprovalNewState.TPDSH.getCode()){
				if (a.getId().equals(AFTConstants.CAOJIN_AID)){
					t.setApproval(ApprovalNewState.DSZDSH.getCode());
				}else {
					t.setApproval(ApprovalNewState.TPDSH.getCode());
				}
			}
			//生成流转
			if (StringUtils.isBlank(t2.getContractNo())) {
				//没有合同编号则生成
				createContractNo(t);
			}else if(!t.getOrderDep().equals(t2.getOrderDep())) {
				contractNoReplace(t.getOrderNo(), t2.getContractNo(),t2.getOrderDep());
				createContractNo(t);
			}
			t.setBuyerId(t2.getBuyerId());
			// 修改订单信息与中间表信息
			updateOrderMid(t);
			List<String> aids = new ArrayList<>();
			Integer type=NoticeStatus.OTHER.getCode();
			StringBuffer str =new StringBuffer();
			if (t.getProcessStatus()==ProcessStatus.YPYXJL.getCode()){
				type=NoticeStatus.ORDER_START.getCode();
				aids.add(a.getManagerId());
				Admin manager = adminMapper.selectById(a.getManagerId());
				str=str.append(manager.getName()).append(",");
			}else if (t.getProcessStatus()==ProcessStatus.YPYXGLY.getCode()){
				type=NoticeStatus.ORDER_YES.getCode();
				List<Admin> admins = adminMapper.listAdminBydepIdAndRoleType(t.getOrderDep(),AFTConstants.SALESMAN_ADMIN);
				if (!admins.isEmpty()){
					for (Admin admin : admins) {
						aids.add(admin.getId());
						if (!str.toString().contains(admin.getName()))str.append(admin.getName()).append(",");
					}
				}
			}else  if (t.getProcessStatus()==ProcessStatus.YPCW_JSZJ.getCode()){
				type=NoticeStatus.ORDER_YES.getCode();
				//为了防止中间加或者删除复审，在营销管理员审核的时候重新刷新
				List<TOrderExamine> tOrderExamines1 = addTOrderExamines(t2);
				for (TOrderExamine e : tOrderExamines1) {
					aids.add(e.getAid());
					str=str.append(e.getAname()).append(",");
				}
			}
			if (str.length()>0)t.setExamineName(str.substring(0,str.length()-1));
			TOrderNewBo order = tOrderNewMapper.getSaleIdByOno(t2.getOrderNo());
			pushGeneralSendNoticeAndEmail(aids, type,order, TokenManager.getAdminId(),t.getApproval());

			//如果有投标，标记成投标订单
			tOrderMidMapper.updateBidTypeByOrderNo(t.getOrderNo());
		}
		//驳回重新发起，需要刷新当天和今天
		boolean newOrderFlag=false;
		if (t2.getApproval().equals(ApprovalNewState.TPBH.getCode()) ||
				t2.getApproval().equals(ApprovalNewState.DSZBH.getCode()) ||
				t2.getOrderStatus().equals(OrderNewState.QDSHJJ.getCode()) ||
				t2.getOrderStatus().equals(OrderNewState.YBH.getCode())) {
			t.setCreateTime(date);
			newOrderFlag=true;
			tOrderBackMapper.updateByOrderNoAndBackStatus(t.getOrderNo());
		}
		// 0 相等
		// -1 小于
		// 1 大于
		//liquidation_status 清算状态 0-首付待付请，1-尾款待付清，2-已付请，3-部分退款，4-全部退款
		//settlement_amount 已付  total_amount 总价格   first_amount首付
		if(!t2.getLiquidationStatus().equals(LiquidationNewState.FULL_REFUND.getCode())) {
			if(t2.getSettlementAmount().compareTo(t.getTotalAmount()) == 0){//如果已付等于总价
				t.setLiquidationStatus(LiquidationNewState.ALREADY_PAY.getCode());
			}else if(t2.getSettlementAmount().compareTo(t.getFirstAmount()) >= 0){//如果大于等于首付
				t.setLiquidationStatus(LiquidationNewState.WAIT_PAY_LAST_BALANCE.getCode());
			} else if(t2.getSettlementAmount().compareTo(t.getFirstAmount()) < 0){//如果小于首付
				t.setLiquidationStatus(LiquidationNewState.WAIT_PAY_FIRST_BALANCE.getCode());
			}
		}
		tOrderNewMapper.update(t);
		pushOrderDunContent(t2);
		//计算公出统计
		pushOrderPublicReleaseCount(t2);
		//处理新旧订单问题
		if (isSubmit==1)pushNewSignUser(t);
		return 1;
	}

	@Override
	public void pushNewSignUser(TOrderNew t2) {
		//看有没有时间后的订单,有则先处理后订单
		List<TOrderNew> tOrderNews = tOrderNewMapper.selectBuyerIdAndSignTime(t2.getBuyerId(), t2.getSignTime(), 1);
		for (TOrderNew tOrderNew : tOrderNews) {
			pushOrderNewSignUser(tOrderNew);
		}
		pushOrderNewSignUser(t2);
	}

	private void pushOrderNewSignUser(TOrderNew t) {
		//最大年限设置3年
		int max=365*3;
		List<TOrderNew> tOrderNews = tOrderNewMapper.selectBuyerIdAndSignTime(t.getBuyerId(), t.getSignTime(), 0);
		TOrderNew updater = new TOrderNew();
		updater.setOrderNo(t.getOrderNo());
		if (tOrderNews.size()>0){
			TOrderNew tOrderNew = tOrderNews.get(tOrderNews.size() - 1);
			Date signTime = tOrderNew.getSignTime();
			long daysBetween = DateUtils.getDaysBetween(signTime,t.getSignTime());
			System.out.println(daysBetween);
			if (daysBetween<max){
				updater.setNewSignUser(1);
			}else {
				updater.setNewSignUser(0);
			}
		}else {
			updater.setNewSignUser(0);
		}
			tOrderNewMapper.update(updater);
	}

	private void pushApprovalType(TOrderNewWithBLOBs t) {
		if (StringUtils.isBlank(t.getType())|| Objects.equals(t.getApproval(), ApprovalNewState.FTP.getCode())){
			tOrderApprovalMapper.deleteByOderNo(t.getOrderNo());
		}else {
			String[] split = t.getType().split(",");
			List<TOrderApproval> tOrderApprovals = tOrderApprovalMapper.selectByOrderNo(t.getOrderNo());
			//删除
			int index = 0;
			for (TOrderApproval e : tOrderApprovals) {
				boolean flag=false;
				for (String s : split) {
					if (Integer.valueOf(s).equals(e.getType())){
						flag=true;
						break;
					}
				}
				if(!flag){
					tOrderApprovalMapper.deleteByPrimaryKey(e.getId());
				}else if(e.getType()==0&&index==0){
					index++;
					if (t.getTypeExplain()!=null){
						e.setTypeExplain(t.getTypeExplain());
						tOrderApprovalMapper.updateByPrimaryKeySelective(e);
					}
				}

			}
			//新增
			for (String s : split) {
				boolean flag=false;
				for (TOrderApproval e : tOrderApprovals) {
					if (Integer.valueOf(s).equals(e.getType())){
						flag=true;
					}
				}
				if (!flag){
					TOrderApproval newTOA=new TOrderApproval();
					newTOA.setType(Integer.valueOf(s));
					newTOA.setOrderNo(t.getOrderNo());
					if(t.getTypeExplain()!=null&&newTOA.getType()==0){
					newTOA.setTypeExplain(t.getTypeExplain());
					}
					tOrderApprovalMapper.insertSelective(newTOA);
				}
			}

		}
	}


	/**
	 * 处理订单公出&报销之间数据统计
	 */
	public void pushOrderPublicReleaseCount(TOrderNew orderNew) {
		//获取公出信息
		List<PublicRelease> list = publicReleaseMapper.selectByOrderNo(orderNew.getOrderNo());
		//公出时间统计
		BigDecimal durationCount = BigDecimal.ZERO;
		//公出次数
		int count=0;
		List<String> peopleList = new ArrayList<>();
		for (PublicRelease e : list) {
					durationCount=durationCount.add(BigDecimal.valueOf(e.getDuration()));
					if (!peopleList.contains(e.getAid())){
						peopleList.add(e.getAid());
					}
					count++;
		}
		TOrderPublicReleaseCount out = new TOrderPublicReleaseCount();
		out.setOrderNo(orderNew.getOrderNo());
		out.setActualDuration(durationCount.doubleValue());
		out.setPeopleCount(peopleList.size());
		out.setFrequency(count);
		TOrderPublicReleaseCount tOrderPublicReleaseCount = tOrderPublicReleaseCountMapper.selectByOrderNo(orderNew.getOrderNo());
		//将最大值、审核状态与最大分类传入
		pushOrderMaxDuration(orderNew,out);
		if (tOrderPublicReleaseCount!=null){
			tOrderPublicReleaseCountMapper.updateByOrderNo(out);
		}else {
			tOrderPublicReleaseCountMapper.insert(out);
		}
	}

	private void pushOrderMaxDuration(TOrderNew orderNew,TOrderPublicReleaseCount out) {
		BigDecimal maxDuration;
		//获取会员信息
		List<TTaskMember> tTaskMembers = tTaskMemberMapper.selectByOrderNo(orderNew.getOrderNo());
		int yearSum=0;
		String serviceLife = null;
		if (tTaskMembers.isEmpty()){
			OrderYearMaxDuration orderYearMaxDuration = new OrderYearMaxDuration();
			orderYearMaxDuration.setYear(0);
			maxDuration = pushMaxDuration(orderNew.getTotalAmount());
			//需修改成判定
			if (maxDuration.compareTo(new BigDecimal(-1))==0){
				orderYearMaxDuration.setMaxDuration(BigDecimal.ZERO);
				orderYearMaxDuration.setStatus(1);
				out.setMaxProcess(0);
				out.setMaxDuration(BigDecimal.ZERO.doubleValue());
				out.setMaxType(2);
			}else if (maxDuration.compareTo(new BigDecimal(0))==0){
				orderYearMaxDuration.setMaxDuration(BigDecimal.ZERO);
				orderYearMaxDuration.setStatus(0);
				out.setMaxDuration(BigDecimal.ZERO.doubleValue());
				out.setMaxType(0);
			}else {
				orderYearMaxDuration.setMaxDuration(maxDuration);
				orderYearMaxDuration.setStatus(0);
				out.setMaxDuration(maxDuration.doubleValue());
				out.setMaxType(1);
			}
			orderYearMaxDuration.setOrderNo(orderNew.getOrderNo());
			int x = orderYearMaxDurationMapper.queryAllByCount(new OrderYearMaxDuration(orderNew.getOrderNo(), 0));
			if (x>0){
				orderYearMaxDurationMapper.updateByOrderNoAndYear(orderYearMaxDuration);
			}else {
				orderYearMaxDurationMapper.insert(orderYearMaxDuration);
			}
		}else {
			for (TTaskMember e : tTaskMembers) {
				if (e.getYearSum()!=null&&e.getYearSum()>yearSum){
					yearSum=e.getYearSum();
					serviceLife=e.getServiceLife();
				}
			}
			List<String> strings = JSON.parseArray(serviceLife, String.class);
			List<Integer> collect;
			if (strings != null) {
				collect = strings.stream().map(this::extractYear).collect(Collectors.toList());
				int size = collect.size();
				//算出来平均值
				BigDecimal divide = orderNew.getTotalAmount().divide(new BigDecimal(size), RoundingMode.HALF_EVEN);
				maxDuration = pushMaxDuration(divide);
				BigDecimal yearMax=BigDecimal.ZERO;
				//如果是无限制或者限制公出则无需判定年份只有是限制需要单独判定
				boolean flag=false;
                for (Integer year : collect) {
					OrderYearMaxDuration orderYearMaxDuration = new OrderYearMaxDuration();
					orderYearMaxDuration.setYear(year);
					//需修改成判定
					if (maxDuration.compareTo(new BigDecimal(-1))==0){
						orderYearMaxDuration.setMaxDuration(BigDecimal.ZERO);
						orderYearMaxDuration.setStatus(1);
						out.setMaxProcess(0);
						out.setMaxDuration(BigDecimal.ZERO.doubleValue());
						out.setMaxType(2);
					}else if (maxDuration.compareTo(new BigDecimal(0))==0){
						orderYearMaxDuration.setMaxDuration(BigDecimal.ZERO);
						orderYearMaxDuration.setStatus(0);
						out.setMaxDuration(BigDecimal.ZERO.doubleValue());
						out.setMaxType(0);
					}else {
						yearMax = yearMax.add(maxDuration);
						orderYearMaxDuration.setYear(year);
						orderYearMaxDuration.setMaxDuration(yearMax);
						orderYearMaxDuration.setStatus(0);
						flag=true;
					}
					orderYearMaxDuration.setOrderNo(orderNew.getOrderNo());
                    int x = orderYearMaxDurationMapper.queryAllByCount(new OrderYearMaxDuration(orderNew.getOrderNo(), year));
					if (x>0){
						orderYearMaxDurationMapper.updateByOrderNoAndYear(orderYearMaxDuration);
					}else {
						orderYearMaxDurationMapper.insert(orderYearMaxDuration);
					}
				}
				if(flag){
					List<OrderYearMaxDuration> orderYearMaxDurations = orderYearMaxDurationMapper.selectByOrderNo(orderNew.getOrderNo());
					// 获取当前日期,提取当前年份
					LocalDate currentDate = LocalDate.now();
					int currentYear = currentDate.getYear();
					OrderYearMaxDuration matchedYearOrLast = findMatchedYearOrLast(orderYearMaxDurations, currentYear);
					out.setMaxDuration(matchedYearOrLast.getMaxDuration().doubleValue());
					out.setMaxType(1);
				}

			}else {
				//异常单处理
				OrderYearMaxDuration orderYearMaxDuration = new OrderYearMaxDuration();
				orderYearMaxDuration.setYear(0);
				orderYearMaxDuration.setOrderNo(orderNew.getOrderNo());
				maxDuration = pushMaxDuration(orderNew.getTotalAmount());
				//需修改成判定
				if (maxDuration.compareTo(new BigDecimal(-1))==0){
					orderYearMaxDuration.setMaxDuration(BigDecimal.ZERO);
					orderYearMaxDuration.setStatus(1);
					out.setMaxDuration(BigDecimal.ZERO.doubleValue());
					out.setMaxProcess(0);
					out.setMaxType(2);
				}else if (maxDuration.compareTo(new BigDecimal(0))==0){
					orderYearMaxDuration.setMaxDuration(BigDecimal.ZERO);
					orderYearMaxDuration.setStatus(0);
					out.setMaxDuration(BigDecimal.ZERO.doubleValue());
					out.setMaxType(0);
				}else {
					orderYearMaxDuration.setMaxDuration(maxDuration);
					orderYearMaxDuration.setStatus(0);
					out.setMaxDuration(maxDuration.doubleValue());
					out.setMaxType(1);
				}
				int x = orderYearMaxDurationMapper.queryAllByCount(new OrderYearMaxDuration(orderNew.getOrderNo(), 0));
				if (x>0){
					orderYearMaxDurationMapper.updateByOrderNoAndYear(orderYearMaxDuration);
				}else {
					orderYearMaxDurationMapper.insert(orderYearMaxDuration);
				}
			}
		}
		if(out.getMaxProcess()==null)out.setMaxProcess(0);
	}

	private OrderYearMaxDuration findMatchedYearOrLast(List<OrderYearMaxDuration> orderYearMaxDurations, int currentYear) {
		for (OrderYearMaxDuration e : orderYearMaxDurations) {
			if (e.getYear()==currentYear){
				return e;
			}
		}
		return orderYearMaxDurations.get(orderYearMaxDurations.size()-1);
	}

	private  Integer extractYear(String yearStr) {
		Pattern pattern = Pattern.compile("(\\d{4})");
		Matcher matcher = pattern.matcher(yearStr);
		if (matcher.find()) {
			return Integer.parseInt(matcher.group(1));
		}
		throw new BusinessException("年份提取失败");
	}


	@Override
	public List<TOrderNew> selectGetAll() {
		return tOrderNewMapper.selectgetAll();
	}

	@Override
	public Object addOperationGuaranteeAudit(String orderNo, Integer type, String reason) {
		TOrderNew t= new TOrderNew();
		TOrderNew t2= checkDeleteSign(orderNo);
		if (!Objects.equals(t2.getProcessStatus(), ProcessStatus.YYBZSH.getCode())){
			throw new BusinessException("订单审核状态错误");
		}
		List<String> aids = new ArrayList<>();
		StringBuffer str =new StringBuffer();
		t.setOrderNo(orderNo);
		TOrderLog tl=new TOrderLog();
		tl.setAid(TokenManager.getAdminId());
		tl.setOrderNo(orderNo);
		tl.setProcess(OrderLogProcess.YYBZSHTG.getCode());
		TOrderNewBo order = tOrderNewMapper.getSaleIdByOno(t2.getOrderNo());
		Integer noticeType=0;
		if (type==0){
			t.setProcessStatus(ProcessStatus.YPYXY.getCode());
			t.setOrderStatus(OrderNewState.YBH.getCode());
			tl.setProcess(OrderLogProcess.YYBZSHBH.getCode());
			aids.add(t.getSalesmanId());
			noticeType= NoticeStatus.ORDER_NO.getCode();
		} else if (type==1) {
			t.setProcessStatus(ProcessStatus.YPTPSH.getCode());
			tl.setProcess(OrderLogProcess.YYBZSHTG.getCode());
			if (t2.getApproval().equals(ApprovalNewState.TPDSH.getCode())){
				str.append(order.getApprovalName()).append(",");
				aids.add(order.getApprovalAid());
			}else if (t2.getApproval().equals(ApprovalNewState.DSZDSH.getCode())){
				List<Admin> admins = adminMapper.selectAdminByRoleType(AFTConstants.APPROVAL_DECISION);
				admins.forEach(e->{
					aids.add(e.getId());
					str.append(e.getName()).append(",");
				});
			}
			t.setExamineName(str.substring(0,str.length()-1));
			noticeType= NoticeStatus.ORDER_YES.getCode();
		}
		addOrderLog(tl,reason);
		pushGeneralSendNoticeAndEmail(aids, noticeType,order, TokenManager.getAdminId(),t2.getApproval());
		tOrderNewMapper.update(t);
		if (type==0){
			t.setBuyerId(t2.getBuyerId());
			t.setSignTime(t2.getSignTime());
			pushNewSignUser(t);
		}
		return 1;
	}



    /**
	 * 处理订单公出&报销最大公出
	 */
	private BigDecimal pushMaxDuration(BigDecimal totalAmount) {
		BigDecimal res=BigDecimal.ZERO;
		int status=1;
		if (totalAmount.compareTo(BigDecimal.valueOf(1)) < 0) {
			res=BigDecimal.ZERO;
		} else if (totalAmount.compareTo(BigDecimal.valueOf(3))<0) {
			res=BigDecimal.valueOf(15);

		} else if (totalAmount.compareTo(BigDecimal.valueOf(5))<0) {
			res=BigDecimal.valueOf(45);

		} else if (totalAmount.compareTo(BigDecimal.valueOf(10))<0) {
			res=BigDecimal.valueOf(120);

		} else if (totalAmount.compareTo(BigDecimal.valueOf(10))>=0) {
			res=BigDecimal.valueOf(-1);
		}
		return res;
	}




	public void updateFinanceCount(String aid, Date createTime){
		String startTime= DateUtils.formatDate(createTime,AFTConstants.YYYYMMDD);
		String endTime=startTime+" 23:59:59";
		int i = financeCountMapper.selectByAidAndDatesGetCount(aid, startTime);
		if (i==0){
			FinanceCount financeCount= FinanceCount.initialization(aid,startTime);
			financeCount.setOrderCount(1);
			financeCount.setOrderUnauditedCount(1);
			financeCountMapper.insertSelective(financeCount);
		}else {
			financeCountMapper.updateOrderCountAdd(aid,startTime);
		}
	}

	private void updateOrderMid(TOrderNew t) {
		TOrderMid tm=tOrderMidMapper.selectByOrderNo(t.getOrderNo());
		Admin admin=adminMapper.selectFinanceAdminByOrderDep(t.getOrderDep());
		Admin a=adminMapper.selectAllByid(TokenManager.getAdminId());
		User u=userMapper.queryById(t.getBuyerId());
		if (tm==null) {
			tm=new TOrderMid();
		}
			tm.setOrderNo(t.getOrderNo());
		if (u!=null&&u.getNickname()!=null) {
			tm.setBuyerName(u.getNickname());
		}
		if (admin!=null&&admin.getName()!=null) {
			t.setFinanceId(admin.getId());
			tm.setFinanceId(admin.getId());
			tm.setFinanceName(admin.getName());
		}
		if(a.getId()!=null&&a.getName()!=null) {
			tm.setSalesmanId(a.getId());
			tm.setSalesmanName(a.getName());
		}
		//判断订单是否为会员订单
		int i =tOrderMidMapper.judgeProjectType(t.getOrderNo());
		UserMid um=new UserMid();
		boolean flag=false;
		um.setUid(t.getBuyerId());
		if (i>0){
			tm.setProjectType(1);
			um.setMember(1);
			flag=true;
		}else{
			tm.setProjectType(0);
		}
		//如果订单金额超过10W标记为大客户
		if(t.getTotalAmount().compareTo(new BigDecimal("10"))>=0) {
			um.setUid(t.getBuyerId());
			um.setAid(t.getSalesmanId());
			um.setBigCustomer(1);
			flag=true;
		}
		if (flag){
			int x=userMidMapper.updateByUid(um);
			if (x==0) {
				um.setAid(TokenManager.getAdminId());
				userMidMapper.insertSelective(um);
			}
		}
		tm.setExpectProfit(t.getTotalAmount());
		tm.setDepName(tOrderMidMapper.selectDepNameByDepid(t.getOrderDep()));
		if (tm.getId()!=null) {
			tOrderMidMapper.update(tm);
		}else {
			tOrderMidMapper.insertSelective(tm);
		}
		//
		orderProjectService.updateMidServiceProject(t.getOrderNo());
	}

	/**
	 * 新建合同编号，优先获取闲置合同编号，否则按年份生成编号
	 */
	private void createContractNo(TOrderNew t) {
		//根据订单部门或许合同编号前缀
		Department dep=departmentMapper.selectByPrimaryKey(t.getOrderDep());
		//获取日期年份
		Calendar c=Calendar.getInstance();
		int y=c.get(Calendar.YEAR);
		if (dep==null||StringUtils.isBlank(dep.getAbbreviation())) {
			throw new BusinessException(new Error( "该部门缩写不存在","该部门缩写不存在"));
		}
		IdleContractNo i=idleContractNoMapper.selectByAbbreviation(dep.getAbbreviation(),y);
		if (i!=null&&i.getContractNo()!=null) {
			t.setContractNo(i.getContractNo());
			idleContractNoMapper.deleteByPrimaryKey(i.getId());
		}else {
			//根据前缀查询最大编号
			String max=departmentMapper.getMaxAbbreviation(dep.getAbbreviation()+"-");

			String sno=null;
			if (StringUtils.isBlank(max)||max.length()<13) {
				String cn=""+dep.getAbbreviation()+"-"+y+"0001";
				cn=iterationNo(cn,dep.getAbbreviation(),y,1);
				t.setContractNo(cn);
			}else {
				int ty=Integer.parseInt(max.substring(max.indexOf("-")+1, max.length()-4));
				int no=Integer.parseInt(max.substring(max.length()-4, max.length()));

				//得出字符串
				sno = countNo(dep.getAbbreviation(), sno, ty, no);
				//迭代得出最后编码
				sno=iterationNo(sno,dep.getAbbreviation(),ty,no);
				//年份小于等于则获取最大值加1，大于则获取最新年份
				if (y<=ty) {
					t.setContractNo(sno);
				}else {
					t.setContractNo(""+dep.getAbbreviation()+"-"+y+"0001");
				}
			}
		}
	}

	private String iterationNo(String sno ,Object mp, int ty, int no) {
		if (tOrderNewMapper.checkContractNo(sno)>0) {
			int i=Integer.parseInt(sno.substring(sno.indexOf("-")+5, sno.length()));
			sno=countNo(mp, sno, ty, i);
			sno=iterationNo(sno,mp,ty,i);
		}
		return sno;
	}

	private String countNo(Object object, String sno, int ty, int no) {
		no++;
		if (no>0&&no<10) {
			sno=object+"-"+ty+"000"+no;
		}else if (no>9&&no<100) {
			sno=object+"-"+ty+"00"+no;
		} else if (no>99&&no<1000) {
			sno=object+"-"+ty+"0"+no;
		} else if(no>1000){
			sno=object+"-"+ty+no;
		}
		return sno;
	}

	public void addOrderLog(TOrderLog tl, String reason) {
		tl.setAid(TokenManager.getAdminId());
		if(reason!=null) {
			tl.setRemarks(reason);
		}
		tOrderLogMapper.insertSelective(tl);

	}

	public void addOrderLog(String  orderNo,Integer process , String reason) {
		TOrderLog tl=new TOrderLog();
		tl.setOrderNo(orderNo);
		tl.setProcess(process);
		addOrderLog( tl,  reason);

	}


	@Override
	public TOrderNewBo getOrderNewDetail(String orderNo) {
		TOrderNewBo tOrder= tOrderNewMapper.getOrderNewDetail(orderNo);
		//设置合同查看权限
		tOrder.setContractPictureUrl(pushOrderService.processStatusConstant(tOrder));
		pushMyExamine(orderNo, tOrder);
		if (TokenManager.hasRole(AFTConstants.SUPERADMIN)||TokenManager.hasRole(AFTConstants.CUSTOMER_SERVICE)||
				tOrder.getSalesmanId().equals(TokenManager.getAdminId())) {
		}else {
			tOrder.setContacts("***");
			tOrder.setContactMobile("***");
			tOrder.setLegalPerson("***");
			tOrder.setLegalPersonTel("***");
		}
		return tOrder;
	}

	private void pushMyExamine(String orderNo, TOrderNewBo tOrder) {
		if (TokenManager.hasRole(AFTConstants.FINANCE)||TokenManager.hasRole(AFTConstants.TECH_ADMIN)){
			int i = tOrderExamineMapper.selectByOrderNoAndAid(orderNo, TokenManager.getAdminId());
			if (i==0) tOrder.setMyExamine(1);
			else tOrder.setMyExamine(0);
		}
	}

	@Override
	public int createOrderDun(String orderDun,String orderNo) {
		List<TOrderDun> l=  JSON.parseArray(orderDun, TOrderDun.class);
		List<TOrderDun> l2=tOrderDunMapper.selectByOrderNoDunSubject(orderNo);
		if (l!=null&&!l.isEmpty()) {
			for (TOrderDun t : l) {
				if (t.getId()==null||t.getId().equals("")) {//Id为空新增
					if (tOrderDunMapper.checkOrderDun(t.getDunSubject(),orderNo)>0) {
						throw new BusinessException(new Error( "该截点已经存在","该截点已经存在"));
					}
					t.setId(UUID.randomUUID().toString());
					t.setDunBy(TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
					t.setDunStatus(0);//未启动
					tOrderDunMapper.insertSelective(t);
				}else {
					tOrderDunMapper.updateByPrimaryKeySelective(t);
				}
			}
		}
		boolean flag=true;
		for (TOrderDun t2 : l2) {
			if (l.isEmpty()) {
				tOrderDunMapper.deleteByPrimaryKey(t2.getId());
			}else {
				for (TOrderDun t : l) {
					if (t2.getId().equals(t.getId())) {//查询集合与返回集合比较查出删除项
						flag=false;
					}
				}
				if (t2.getId()!=null&&flag) {
					tOrderDunMapper.deleteByPrimaryKey(t2.getId());
				}
				flag=true;
			}
		}
		return 1;
	}



	@SuppressWarnings("unchecked")
	@Override
	public Pagination<TOrderNewBo> orderNewList(InputOrderNewListBo in) {
		Map<String, Object> params = new HashMap<>();
		Pagination<TOrderNewBo> x = addParams(in, params);
		if (x != null) return x;
		Pagination<TOrderNewBo> p = (Pagination<TOrderNewBo>)findPage("selectOrderNewListByPage", "selectOrderNewListCount", params, in.getPageNo(), in.getPageSize());
		if (TokenManager.hasRole(AFTConstants.TECH_ADMIN)){
			List<TOrderNewBo> list = (List<TOrderNewBo>) p.getList();
			for (TOrderNewBo o : list) {
				int i = tOrderExamineMapper.selectByOrderNoAndAid(o.getOrderNo(), TokenManager.getAdminId());
				if (i==0) o.setMyExamine(1);
				else o.setMyExamine(0);
			}
		}

		return p;
	}


	private Pagination<TOrderNewBo> addParams(InputOrderNewListBo in, Map<String, Object> params) {
//		specially 0 个人 1 营销员管理 2 驳回 3 特批 4 咨询师管理 5部门订单查询 6客服查询 7统计签单订单 8客户订单列表 9 复审订单 10 营销经理
		if (in.getSpecially()!=null&&(in.getSpecially()==0|| in.getSpecially()==1|| in.getSpecially()==2||
				in.getSpecially()==4|| in.getSpecially()==5|| in.getSpecially()==7|| in.getSpecially()==10|| in.getSpecially()==11)) {
			//0 个人 1 营销员管理 2 驳回 3 特批 4 咨询师管理 5部门订单查询
			if (in.getSpecially()==0){
				params.put("maxStatus", in.getMaxStatus());
			}
			if (in.getSpecially()!=3&& in.getSpecially()!=4) {
				if (in.getAid() ==null){
					params.put("aid", TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
				}else{
					params.put("aid", in.getAid());
				}
			}
			//（咨询师管理列表 0 未分配 1部分   2全部）
			if(in.getSpecially()==4) {
				params.put("distribution", in.getDistribution());
			}
		}else if(in.getSpecially()==8){
			if (StringUtils.isNotBlank(in.getUid())) {
				params.put("uid", in.getUid());
			}
		}else if (in.getSpecially()==9){
			if (StringUtils.isNotBlank(in.getAid())) {
				params.put("aid", in.getAid());
			}
		}else if (in.getSpecially()==3){
			params.put("aid", TokenManager.getAdminId());

		}else if (in.getSpecially()==12){
			PublicConfig config=publicConfigMapper.queryById(1);
			String aid=TokenManager.getAdminId();
			int configType=9;
			if (aid.equals(config.getTechAuditor())){
				configType=1;
			}else if (aid.equals(config.getFinanceAuditor())){
				configType=2;
			}else if (aid.equals(config.getOtherAuditor())){
				configType=3;
			}
			params.put("configType", configType);
			params.put("aid", aid);
		}
		params.put("specially", in.getSpecially());
		if (StringUtils.isNotBlank(in.getName())) {
			params.put("name", in.getName());
		}
		if(in.getMaxProcessStatus()!=null)params.put("maxProcessStatus", in.getMaxProcessStatus());
		// 计算出所有本部门及所属部门的ID
		if(in.getSpecially()==1|| in.getSpecially()==5) {
			List<String>departmentList=new ArrayList<>();
			if (in.getDeps()!=null){
				departmentList=departmentService.selectSubDeps(in.getDeps());
				if (departmentList==null||departmentList.isEmpty()){
					return  new Pagination<>(1,10,0);
				}
			}else {
				departmentList=departmentService.selectMyDeps();
			}
			params.put("deps",departmentList);
		}else {
			if (in.getDeps()!=null) {
				params.put("deps",departmentService.parseArray(in.getDeps()));
			}
		}
		if (StringUtils.isNotBlank(in.getContractNo())) {
			params.put("contractNo", in.getContractNo());
		}
		if (null!= in.getLiquidationStatus()) {
			params.put("liquidationStatus", in.getLiquidationStatus());
		}
		if (null != in.getApproval()) {
			params.put("approval", in.getApproval());
		}
		if(null != in.getAmountStatus()) {
			params.put("amountStatus", in.getAmountStatus());
		}
		if (StringUtils.isNotBlank(in.getOrderNo())) {
			params.put("orderNo", in.getOrderNo().trim());
		}
		if (StringUtils.isNotBlank(in.getStarTime())) {
			params.put("starTime", in.getStarTime());
		}
		if (StringUtils.isNotBlank(in.getEndTime())) {
			params.put("endTime", in.getEndTime()+" 23:59:59");
		}
		if (StringUtils.isNotBlank(in.getContractStart())) {
			params.put("contractStart", in.getContractStart());
		}
		if (StringUtils.isNotBlank(in.getContractEnd())) {
			params.put("contractEnd", in.getContractEnd()+" 23:59:59");
		}
		if(null != in.getProjectType()) {
			params.put("projectType", in.getProjectType());
		}
		if(null != in.getProcessStatus()) {
			params.put("processStatus", in.getProcessStatus());
		}
		if(null != in.getTag()){
			params.put("tag",in.getTag());
		}
		if(in.getType()!=null){
			if (!in.getType().equals("0,1,2,3,4,5,6,7")){
				String[] split = in.getType().split(",");
				params.put("type", split);
			}
		}
		params.put("outsource", in.getOutsource());
		params.put("scoreStatus", in.getScoreStatus());
		if (in.getManageType()!=null){
			params.put("manageType", in.getManageType());
		}
		return null;
	}


	@Override
	public Pagination<TOrderNewBo> statisticsOrderList(InputStatisticsOrderList in) {
		Map<String, Object> params = new HashMap<String, Object>();
		if (in.getProvince()!=null) {
			params.put("province",in.getProvince());
			if (in.getSalesType()!=null) {
				params.put("salesType",in.getSalesType());
			}
			if (in.getOrderNo()!=null) {
				params.put("orderNo",in.getOrderNo());
			}
			if (in.getName()!=null) {
				params.put("name",in.getName());
			}
			if (in.getContractNo()!=null) {
				params.put("contractNo",in.getContractNo());
			}
			if (in.getLiquidationStatus()!=null) {
				params.put("liquidationStatus",in.getLiquidationStatus());
			}
			if (in.getApproval()!=null) {
				params.put("approval",in.getApproval());
			}
			if (in.getAmountStatus()!=null) {
				params.put("amountStatus",in.getAmountStatus());
			}
			if (in.getStartDate()!=null) {
				params.put("startDate",in.getStartDate());
			}
			if (in.getEndDate()!=null) {
				params.put("endDate",in.getEndDate()+" 23:59:59");
			}
		} else {
			if (in.getSalesType()!=null) {
				params.put("salesType",in.getSalesType());
			}
			if (in.getOrderNo()!=null) {
				params.put("orderNo",in.getOrderNo());
			}
			if (in.getName()!=null) {
				params.put("name",in.getName());
			}
			if (in.getContractNo()!=null) {
				params.put("contractNo",in.getContractNo());
			}
			if (in.getLiquidationStatus()!=null) {
				params.put("liquidationStatus",in.getLiquidationStatus());
			}
			if (in.getApproval()!=null) {
				params.put("approval",in.getApproval());
			}
			if (in.getAmountStatus()!=null) {
				params.put("amountStatus",in.getAmountStatus());
			}
			if (in.getStartDate()!=null) {
				params.put("startDate",in.getStartDate());
			}
			if (in.getEndDate()!=null) {
				params.put("endDate",in.getEndDate()+" 23:59:59");
			}
		}
		if (in.getDepId()!=null) {
			params.put("depId",in.getDepId());
		}
		Pagination<TOrderNewBo> p = (Pagination<TOrderNewBo>)findPage("selectstatisticsOrderListPage",
				"selectstatisticsOrderListCount", params, in.getPageNo(), in.getPageSize());
		return p;
	}

	@Override
	public int updateSalesType(TOrderNew in) {
		return tOrderNewMapper.update(in);
	}




	@Override
	public int updateOrderNew(String orderNo, Integer orderStatus,String reason,Integer outsource, TOrderOutsource o) {
		TOrderNew t= new TOrderNew();
		TOrderNew t2= checkDeleteSign(orderNo);
		t.setOrderNo(orderNo);
		t.setOrderDep(t2.getOrderDep());
		t.setSalesmanId(t2.getSalesmanId());
		List<String> aids = new ArrayList<>();
		Integer type=null;
		TOrderLog tl=new TOrderLog();
		tl.setAid(TokenManager.getAdminId());
		tl.setOrderNo(orderNo);
		if (orderStatus.equals(OrderNewState.QDSHTG.getCode())) {
			t.setOutsource(outsource);
			if (t2.getProcessStatus()==ProcessStatus.YPYXJL.getCode()){
				tl.setProcess(OrderLogProcess.YXJLTT.getCode());
				t.setProcessStatus(ProcessStatus.YPYXGLY.getCode());
				aids.addAll(adminMapper.listNameByDepAndName(t2.getOrderDep(), AFTConstants.SALESMAN_ADMIN));
			}else if (t2.getProcessStatus()==ProcessStatus.YPYXGLY.getCode()){
				tl.setProcess(OrderLogProcess.SH.getCode());
				t.setProcessStatus(ProcessStatus.YPCW_JSZJ.getCode());
				//为了防止中间加或者删除复审，在营销管理员审核的时候重新刷新
				List<TOrderExamine> tOrderExamines1 = addTOrderExamines(t2);
				for (TOrderExamine e : tOrderExamines1) {
					aids.add(e.getAid());
				}
				Admin admin=adminMapper.selectFinanceAdminByOrderDep(t2.getOrderDep());
				updateFinanceCount(admin.getId(),t2.getCreateTime());
			}
			type=NoticeStatus.ORDER_YES.getCode();
			//增加日志
			addOrderLog(tl,reason);
		}else if (orderStatus.equals(OrderNewState.QDSHJJ.getCode())) {//如果不通过新增驳回
				if (outsource==0) {//非外包
				t.setProcessStatus(ProcessStatus.YPYXY.getCode());
				addBackOrder(orderNo, reason);
			}
				aids.add(t2.getSalesmanId());
				type=NoticeStatus.ORDER_NO.getCode();
		}
		t.setOrderStatus(orderStatus);
		//设置审核人员名称
		pushExamineName(t);
		tOrderNewMapper.update(t);
		if (aids.isEmpty()) {
			throw new BusinessException(new Error( "邮件发送失败，对方设置邮箱错误","邮件发送失败，对方设置邮箱错误"));
		}
		TOrderNewBo order = tOrderNewMapper.getSaleIdByOno(t2.getOrderNo());
		pushGeneralSendNoticeAndEmail(aids, type,order, TokenManager.getAdminId(),t2.getApproval());
		if (orderStatus.equals(OrderNewState.QDSHJJ.getCode())) {
			t.setBuyerId(t2.getBuyerId());
			t.setSignTime(t2.getSignTime());
			pushNewSignUser(t);
		}
		return 1;
	}



	@Override
	public void pushExamineName(TOrderNew t){
		StringBuffer str =new StringBuffer();
		if (t.getProcessStatus()==ProcessStatus.YPYXY.getCode()){
			Admin admin = adminMapper.selectById(t.getSalesmanId());
			t.setExamineName(admin.getName());
		}else if (t.getProcessStatus()==ProcessStatus.YPYXJL.getCode()){
			Admin a = adminMapper.selectById(t.getSalesmanId());
			Admin admin = adminMapper.selectById(a.getManagerId());
			t.setExamineName(admin.getName());
		}else if (t.getProcessStatus()==ProcessStatus.YPYXGLY.getCode()){
			if (t.getOrderDep()!=null){
				List<Admin> admins = adminMapper.listAdminBydepIdAndRoleType(t.getOrderDep(), AFTConstants.SALESMAN_ADMIN);
				for (Admin admin : admins) {
					str=str.append(admin.getName()).append(",");
				}
			}
		}else if (t.getProcessStatus()==ProcessStatus.YPCW_JSZJ.getCode()){
			if (t.getOrderDep()!=null){
				List<TOrderExamine> list = tOrderExamineMapper.selectByOrderNo(t.getOrderNo(),0);
				for (TOrderExamine e : list) {
					str=str.append(e.getAname()).append(",");
				}
			}
		}else if (t.getProcessStatus()==ProcessStatus.YPYXY.getCode()){
			t.setExamineName("");
		} else {
			t.setExamineName("");
		}
		if (StringUtils.isNotBlank(str))t.setExamineName(str.substring(0,str.length()-1));

	}



	/**
	 *  订单分配触发
	 */
	@Override
	public void pushOrderDun(TOrderNew b) {
		if(b.getApproval()==0){
			Date date = new Date();
			List<OutNewOrderDunBo> list=newOrderDunMapper.selectListNewOrderDun(b.getOrderNo(),0);
			for (OutNewOrderDunBo o : list) {
				if (o.getDunType()==1) {
					o.setStatus(1);
					o.setStartTime(date);
					newOrderDunMapper.updateByPrimaryKeySelective(o);
					//催款统计算
					TOrderMid tm = pushOrderMidDun(b.getOrderNo(), b.getSettlementAmount(), date);
					TArrearsDun t=new TArrearsDun();
					t.setOrderArrears(tm.getOrderArrears());
					t.setOrderReceivables(tm.getOrderReceivables());
					if (tArrearsDunMapper.checkOrderNo(b.getOrderNo(),null)<1) {
						t.setOrderNo(b.getOrderNo());
						tArrearsDunMapper.insertSelective(t);
					}else if(tArrearsDunMapper.checkOrderNo(b.getOrderNo(),0)>0){
						Integer i=tArrearsDunMapper.selectByStatus(b.getOrderNo(), 0);
						t.setId(i);
						tArrearsDunMapper.updateByPrimaryKeySelective(t);
					}

					addNewDunNoticAndSendEmail(b.getOrderNo(),o);
				}
			}
		}
	}

	/**
	 * NewProjectStatus.YXZ.getCode()
	 * @param orderNo 订单编号
	 * @param settlementAmount 已收金额
	 * @param date 日期
	 * @return
	 */
	@Override
	@Synchronized
	public TOrderMid pushOrderMidDun(String orderNo, BigDecimal settlementAmount, Date date) {
		TOrderMid tm=tOrderMidMapper.selectByOrderNo(orderNo);
//		代码看不出异常，但是计算会出现重复，则修改方案，每一次触发，则重新统计
//		tm.setOrderReceivables(tm.getOrderReceivables().add(o.getMoney()));
		List<OutNewOrderDunBo>  list =newOrderDunMapper.selectListNewOrderDun(orderNo,1);
		BigDecimal cout=new BigDecimal(0);
		for (OutNewOrderDunBo bo : list) {
			BigDecimal money = bo.getMoney();
			if (money!=null)cout=cout.add(money);
		}
		tm.setOrderReceivables(cout);
		BigDecimal sum=tm.getOrderReceivables().subtract(settlementAmount);
		//如果金额大于欠款修改欠款为0
		if (sum.compareTo(new BigDecimal(0))<0) {
			sum=new BigDecimal(0);
		}
		tm.setOrderArrears(sum);
		if (tm.getDunStartTime()==null) {
			tm.setDunStartTime(date);
		}
		tOrderMidMapper.update(tm);
		return tm;
	}
	@Override
	public TOrderMid pushOrderMidDun(TOrderNew t) {
		return pushOrderMidDun(t.getOrderNo(),t.getSettlementAmount(),new Date());
	}



	@Override
	public void addNewDunNoticAndSendEmail(String  orderNo, OutNewOrderDunBo o) {
		AdminListBo a = adminMapper.getDeptNameByAid(TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
		TOrderNewBo b  = tOrderNewMapper.getSaleIdByOno(o.getOrderNo());
		addNotic(NoticeStatus.ORDER_DUN.getCode(), b,null);
		try {
			NewDunsendEmail(o.getOrderNo(),o.getId(), a, b);
		} catch (UnsupportedEncodingException | MessagingException e) {
			throw new BusinessException(new Error("邮件发送错误。"));
		}
	}

	@Override
	public void addTimingTaskNewDunNoticAndSendEmail(OutNewOrderDunBo o, Integer type) {
		AdminListBo a = adminMapper.getDeptNameByAid("1");
		TOrderNewBo b  = tOrderNewMapper.getSaleIdByOno(o.getOrderNo());
		StringBuilder sb=new StringBuilder();
		Integer noticType=NoticeStatus.ORDER_DUN.getCode();
		if (type==1){
			noticType=NoticeStatus.MENBER_DUN.getCode();
            sb.append("客户名称【").append(b.getUserName()).append("】催款截点将于").append(o.getCustomizeTimes()).append("进行催款，会员项目请提前2个月催款，以免延误会员派单");
        }else {
            sb.append("客户名称【").append(b.getUserName()).append("】,按时触发应收款欠款，请按时催款，并及时增减项目，以免项目延期等问题。");
        }
		addNotic(noticType, b,sb.toString());
		try {
			NewDunsendEmail(o.getOrderNo(),o.getId(), a, b,noticType,sb.toString());
		} catch (UnsupportedEncodingException | MessagingException e) {
			throw new BusinessException(new Error("邮件发送错误。"));
		}
	}
	public void  NewDunsendEmail(String orderNo,Integer dunId,AdminListBo a,TOrderNewBo b) throws UnsupportedEncodingException, MessagingException{
		NewDunsendEmail( orderNo, dunId, a, b, NoticeStatus.ORDER_DUN.getCode(),null);
	}

	public void  NewDunsendEmail(String orderNo,Integer dunId,AdminListBo a,TOrderNewBo b,Integer noticType,String content) throws UnsupportedEncodingException, MessagingException{
		NewOrderDun ob=newOrderDunMapper.selectByPrimaryKey(dunId);
		AdminListBo a2 = adminMapper.getDeptNameByAid(b.getSalesmanId());
		String dunTypeName="";
		if(ob.getDunType()!=null&&ob.getProjectType()!=null&&ob.getDunType()!=0) {
			dunTypeName= NewOrderDunType.getValueByCode(Integer.valueOf(""+ob.getProjectType()+ob.getDunType()));
		}else if(ob.getDunType()!=null&&ob.getProjectType()!=null&&ob.getDunType()==0){
			dunTypeName= NewOrderDunType.getValueByCode(Integer.valueOf(""+ob.getProjectType()+ob.getDunType()))+ob.getCustomizeName();
		}
			//发送驳回邮件
		if(SendEmailUtil.isEmail(b.getEmail())) {
			EmailBo bo =new EmailBo();
			if (noticType.equals(NoticeStatus.MENBER_DUN.getCode())){
				bo = new EmailBo("会员提前催收", b.getEmail(), content);
			}else {
				bo = new EmailBo("催收通知", b.getEmail(), a.getDepartmentName(), a.getName(),
						"", orderNo,b.getContractNo(),new SimpleDateFormat("yyyy-MM-dd").format(ob.getCreateTime()),dunTypeName,a2.getName(),b.getUserName(),1,0);
			}

				if(StringUtils.isNotBlank(b.getEmail())) {
					asyncUtils.patentSend(bo);
				}
	     }


	}

	private void addBackOrder(String orderNo, String reason) {
		TOrderBack ob=new TOrderBack();
		TOrderNew tOrder= tOrderNewMapper.queryById(orderNo);
		ob.setCreateTime(new Date());
		ob.setOrderNo(orderNo);
		ob.setReason(reason);
		ob.setBackStatus(0);//待处理
		ob.setInitiate(TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
		ob.setAccept(tOrder.getSalesmanId());
		TOrderLog tl=new TOrderLog();
		tl.setOrderNo(orderNo);
		tl.setProcess(OrderLogProcess.BH.getCode());
		addOrderLog(tl,reason);
		tOrderBackMapper.insertSelective(ob);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<outOrderDunListBo> dunOrderNewList(String name, String orderNo,String contractNo, String starTime, String endTime,
			Integer specially,String  aid, String adminName,String deps,Integer newStatus,Integer approval,Integer amountStatus,Integer memberType,Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(newStatus!=null&&newStatus==0) {
			params.put("newStatus", 0);
		} else {
			params.put("newStatus", tOrderDunMapper.selectByOrderNo(orderNo).isEmpty()?1:0);
		}
		if (StringUtils.isNotBlank(name)) {
			params.put("name", name);
		}
		if (StringUtils.isNotBlank(deps)) {
			params.put("deps", departmentService.parseArray(deps));
		}
		if (StringUtils.isNotBlank(adminName)) {
			params.put("adminName", adminName);
		}
		if (StringUtils.isNotBlank(orderNo)) {
			params.put("orderNo", orderNo);
		}
		if (StringUtils.isNotBlank(contractNo)) {
			params.put("contractNo", contractNo);
		}
		if (StringUtils.isNotBlank(starTime)) {
			params.put("starTime", starTime);
		}
		if (StringUtils.isNotBlank(endTime)) {
			params.put("endTime", endTime+" 23:59:59");
		}
		if (approval!=null ) {
			params.put("approval",approval);
		}
		if (amountStatus!=null ) {
			params.put("amountStatus",amountStatus);
		}
		if (memberType!=null ) {
			params.put("memberType",memberType);
		}
		if (specially==null) {
			specially=0;
		}
		params.put("specially", specially);
		Integer i=null;
		if (TokenManager.hasRole(AFTConstants.FINANCE)) {
			i=1;
			params.put("fid", TokenManager.getAdminId());
		}else if (TokenManager.hasRole(AFTConstants.FINANCE_MANAGER)) {
			i=2;
			params.put("fid", TokenManager.getAdminId());
		}else 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;
		}else {
				params.put("aid", TokenManager.getAdminId());
		}
		if (specially==1){
			params.put("aid", aid);
			params.put("dunStatus", 1);

		}
		if(i!=null) {
			params.put("shiroType", i);
		}
		Pagination<outOrderDunListBo> p = (Pagination<outOrderDunListBo>)findPage("selectDunOrderNewListByPage", "selectDunOrderNewListCount", params, pageNo, pageSize);
		List<outOrderDunListBo> list = (List<outOrderDunListBo>) p.getList();
		for (outOrderDunListBo o : list) {
			o.setDunSubject(getDunSubject(o));
		}
		return p;
	}

	public String getDunSubject(outOrderDunListBo o) {
		//旧催款
		if(o.getDunSubject()!=null) {
			return OrderDunSubject.getValueByCode(Integer.valueOf(o.getDunSubject()));
		}
		//新催款
		if(o.getDunType()!=null&&o.getDunType()!=0&&o.getProjectType()!=null) {
			return NewOrderDunType.getValueByCode(Integer.valueOf(""+o.getProjectType()+o.getDunType()));
		}
		if(o.getDunType()!=null&&o.getDunType()==0&&o.getProjectType()!=null) {
			return NewOrderDunType.getValueByCode(Integer.valueOf(""+o.getProjectType()+o.getDunType()))+o.getCustomizeName();
		}
		return "";
	}

	@Override
	public int createDunLog( String dunId, String dumTime, String remarks, String attUrl) {
		TDunLog d=new TDunLog();
		d.setId(UUID.randomUUID().toString());
		d.setDunId(dunId);
		d.setDumBy(TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
		d.setAttachmentUrl(attUrl);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			d.setDumTime(sdf.parse(dumTime));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		d.setRemarks(remarks);
		return tDunLogMapper.insertSelective(d);
	}

	@Override
	public List<TDunLogListBo> selectDunLogList(String dunId) {
		return tDunLogMapper.selectByDunId(dunId);
	}

	@Override
	public int addOrderRefund(TOrderRefundWithBLOBs t) {
		TOrderNew order =checkDeleteSign(t.getOrderNo());
		if(order.getDeleteSign()!=0) {
			throw new BusinessException(new Error( "订单变更锁定中","订单变更锁定中"));
		}
		t.setRefundStatus(refundState.DSH.getCode());
		t.setCreateTime(new Date());
		t.setInitiate(TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
		//t.setAccept("1");
		t.setAccept(order.getFinanceId());
		t.setResult("");
		TOrderNew tOrder=new TOrderNew();
		tOrder.setOrderNo(t.getOrderNo());
		tOrder.setOrderStatus(OrderNewState.TDZ.getCode());
		tOrderNewMapper.update(tOrder);
		TOrderLog tl=new TOrderLog();
		tl.setOrderNo(t.getOrderNo());
		tl.setProcess(OrderLogProcess.FQTD.getCode());
		addOrderLog(tl,null);
		return tOrderRefundMapper.insertSelective(t);
	}

	@Override
	public int updateApprovalOrder(String orderNo,Integer confirm,String reason) {
		TOrderNew t=new TOrderNew();
		TOrderNew t2=checkDeleteSign(orderNo);
		t.setOrderNo(orderNo);
		List<String> aids = new ArrayList<>();
		Integer type=null;
		TOrderLog tl=new TOrderLog();
		tl.setOrderNo(orderNo);

		if (confirm==2) {
			if (t2.getApproval()==ApprovalNewState.TPDSH.getCode())t.setApproval(ApprovalNewState.TPTG.getCode());
			else if (t2.getApproval()==ApprovalNewState.DSZDSH.getCode())t.setApproval(ApprovalNewState.DSZTG.getCode());
				t.setProcessStatus(ProcessStatus.YPZXSGLY.getCode());
				OrganizationListOut oo=departmentMapper.selectAllById(t2.getOrderDep());
				t.setFinanceId(oo.getFinanceId());
				StringBuffer str=new StringBuffer();
				for (Admin admin : adminMapper.getAdminRoleTypeList(AFTConstants.TECH_ADMIN)) {
					aids.add(admin.getId());
					if (!str.toString().contains(admin.getName()))str.append(admin.getName()).append(",");
				}
			if (str.length()>0)t.setExamineName(str.substring(0,str.length()-1));
			type=NoticeStatus.ORDER_APPROVA_YES.getCode();
			tl.setProcess(OrderLogProcess.TP.getCode());
			addOrderLog(tl,reason);
		} else {
			if (t2.getApproval()==ApprovalNewState.TPDSH.getCode())t.setApproval(ApprovalNewState.TPBH.getCode());
			else if (t2.getApproval()==ApprovalNewState.DSZDSH.getCode())t.setApproval(ApprovalNewState.DSZBH.getCode());
			t.setOrderStatus(OrderNewState.YBH.getCode());
			t.setProcessStatus(ProcessStatus.YPYXY.getCode());
			tl.setProcess(OrderLogProcess.BH.getCode());
			aids.add(t2.getSalesmanId());
			type=NoticeStatus.ORDER_APPROVA_NO.getCode();
			addBackOrder(orderNo, reason);
		}
		TOrderNewBo order = tOrderNewMapper.getSaleIdByOno(orderNo);
		order.setProcessStatus(t.getProcessStatus());
		pushGeneralSendNoticeAndEmail(aids, type,order, TokenManager.getAdminId(),t2.getApproval());
		//新增特批催款信息
		tOrderNewMapper.update(t);
		if (confirm==3){
			t.setBuyerId(t2.getBuyerId());
			t.setSignTime(t2.getSignTime());
			pushNewSignUser(t);
		}
		return 1;
	}

	@Override
	public List<TOrderDun> selectOrderDun(String orderNo) {
		return tOrderDunMapper.selectByOrderNoDunSubject(orderNo);
	}

	@Override
	public boolean checkOrderMain(TOrderTask t) {
		List<TOrderTaskBo> list=tOrderTaskMapper.selectOrderTask(t.getOrderNo(),0);
		int flag=0;
		if(t.getMain()==1) {
			flag++;
		}
		for (TOrderTask t2 : list) {
			if(t2.getMain()==1&&t.getId()==null) {
				flag++;
			}else if (t2.getMain()==1&&(!t.getId().equals(t2.getId()))) {
				flag++;
			}
		}
		if (flag>1) {
			return true;
		}
		return false;
	}

	@Override
	public boolean chekeOrderStatus(String orderNo) {
		TOrderNew tOrder= tOrderNewMapper.queryById(orderNo);
		if (tOrder.getOrderStatus().equals(OrderNewState.QDDS.getCode()) || tOrder.getOrderStatus().equals(OrderNewState.QDSHTG.getCode())) {
			return false;
		}
		return true;
	}

	@Override
	public boolean chekeProcessStatus(String orderNo) {
		TOrderNew tOrder= tOrderNewMapper.queryById(orderNo);
		if (tOrder.getProcessStatus().equals(ProcessStatus.YPYXY.getCode())) {
			return false;
		}
		return true;
	}


	@Override
	public boolean chekeApprovalOrderStatus(String orderNo) {
		TOrderNew tOrder= tOrderNewMapper.queryById(orderNo);
		if (tOrder.getApproval().equals(ApprovalNewState.FTP.getCode()) ||
				tOrder.getOrderStatus().equals(OrderNewState.QDSHJJ.getCode()) ||
				tOrder.getOrderStatus().equals(OrderNewState.YBH.getCode())) {
			return true;
		}
		return false;
	}

	@Override
	public int deleteOrderNew(String orderNo) {
		TOrderNew t=tOrderNewMapper.queryById(orderNo);
		if (t.getOrderStatus().equals(OrderNewState.YBH.getCode()) || t.getOrderStatus().equals(OrderNewState.YTD.getCode()) ||
				t.getOrderStatus().equals(OrderNewState.DQD.getCode()) || t.getOrderStatus().equals(OrderNewState.QDSHJJ.getCode())) {
			t.setOrderNo(orderNo);
			t.setDeleteSign(1);//作废
			if(t.getContractNo()!=null) {
				contractNoReplace(orderNo, t.getContractNo(),t.getOrderDep());
			}
			if(t.getSettlementAmount().compareTo(BigDecimal.ZERO) > 0){
				TemporaryReceivables tr=new TemporaryReceivables();
				tr.setOrderNo(orderNo);
				String financeId=null;
				if(t.getFinanceId()!=null){
					financeId=t.getFinanceId();

				}else{
					OrganizationListOut out = departmentMapper.selectAllById(t.getOrderDep());
					if (out.getFinanceId()!=null){
						financeId=out.getFinanceId();
					}
				}
				if(financeId==null){
					throw new BusinessException(new Error("订单部门财务负责人为空，请修改正确在操作","订单部门财务负责人为空，请修改正确在操作"));
				}
				tr.setAid(financeId);
				tr.setAmount(t.getSettlementAmount());
				User user = userMapper.queryById(t.getBuyerId());
				tr.setCorporateName(user.getNickname());
				tr.setStatus(ReceivablesStatus.DDYC.getCode());
				tr.setRemarks("订单作废，金额返回订单财务负责人");
				Date date = new Date();
				tr.setCreateTime(date);
				tr.setReceivablesTime(date);
				tr.setMergeStatus(0);
				temporaryReceivablesMapper.insertSelective(tr);
				asyncUtils.addNoticAndEmail(new Notice(financeId,NoticeStatus.ORDER_CANCELLATION_AMOUNT_RETURN.getCode(),"订单作废，金额返回订单财务负责人" ));
			}
			t.setContractNo("");
			return tOrderNewMapper.update(t);
		}
		return -1;
	}

	/**
	 *  	将合同编号置为闲置编号
	 * @param orderNo
	 */
	private void contractNoReplace(String orderNo, String  contractNo,String orderDep) {
		Calendar c=Calendar.getInstance();
		int y=c.get(Calendar.YEAR);
		String ys="-"+y;
		//判断编号是否类似‘-2019’，是则为有效编号
		if (contractNo.contains(ys)) {
			IdleContractNo i=new IdleContractNo();
			i.setAid(TokenManager.getAdminId());
			i.setContractNo(contractNo);
			i.setUsedOrderNo(orderNo);
			i.setYear(y);
			//如果找不到订单部门，则取订单编号-前面的缩写
			if(StringUtils.isNotBlank(orderDep)) {
				Department o=departmentMapper.selectByPrimaryKey(orderDep);
				i.setAbbreviation(o.getAbbreviation());
			}else {
				i.setAbbreviation(contractNo.substring(0, contractNo.indexOf("-")));
			}
			idleContractNoMapper.insertSelective(i);
		}
	}

	@Override
	public boolean checkOderSettlementAmount(String orderNo) {
		TOrderNew tOrder= tOrderNewMapper.queryById(orderNo);
		if (tOrder.getSettlementAmount()==null||
				tOrder.getSettlementAmount().doubleValue()==0||
				tOrder.getOrderStatus().equals(OrderNewState.TDZ.getCode())){
				return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<TOrderRefundBo> orderRefundList(String name, String orderNo, String starTime, String endTime, Integer specially,
			Integer pageNo, Integer pageSize) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("aid", TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
			if (StringUtils.isNotBlank(name)) {
				params.put("name", name);
			}
			if (StringUtils.isNotBlank(orderNo)) {
				params.put("orderNo", orderNo);
			}
			if (StringUtils.isNotBlank(starTime)) {
				params.put("starTime", starTime);
			}
			if (StringUtils.isNotBlank(endTime)) {
				params.put("endTime", endTime+" 23:59:59");
			}
			Pagination<TOrderRefundBo> p = (Pagination<TOrderRefundBo>)findPage("selectOrderRefundListByPage", "selectOrderRefundListCount", params, pageNo, pageSize);
			return p;

	}

	@Override
	public boolean checkORderTask(String orderNo) {
		List<TOrderTaskBo> list=tOrderTaskMapper.selectOrderTask(orderNo,0);
		for (TOrderTaskBo t : list) {
			if (t.getMain()==1) {
				return false;
			}
		}
		return true;
	}


	@Override
	public boolean checkOrderAmount(TOrderNewWithBLOBs t) {
		BigDecimal orderAmount=t.getTotalAmount();
		if (orderAmount==null){
			TOrderNew tOrderNew=tOrderNewMapper.getOrderNewDetail(t.getOrderNo());
			orderAmount=tOrderNew.getTotalAmount();
		}
		List<TOrderTaskBo> tOrderTaskBos = tOrderTaskMapper.selectOrderTaskAll(t.getOrderNo(),3);
		List<OutNewOrderDunBo> tOrderDuns = newOrderDunMapper.selectListNewOrderDun(t.getOrderNo(),null);
		BigDecimal taskAmount=new BigDecimal(0);
		for (TOrderTaskBo tOrderTaskBo : tOrderTaskBos) {
			if (tOrderTaskBo.getCommodityPrice()!=null){
				taskAmount=taskAmount.add(tOrderTaskBo.getCommodityPrice());
			}
		}
		BigDecimal dunAmount=new BigDecimal(0);
		for (OutNewOrderDunBo tOrderDun : tOrderDuns) {
			if(tOrderDun.getMoney()!=null){
				dunAmount=dunAmount.add(tOrderDun.getMoney());
			}
		}
		if (orderAmount.compareTo(taskAmount)==0&&orderAmount.compareTo(dunAmount)==0){
			return false;
		}
		return true;
	}

	/**
	 * 获取催款数据
     */
	@Override
	public Result exportOrderDunData(String name, String orderNo, String contractNo, String starTime, String endTime, Integer specially, String aid, String adminName,
									 String depId, Integer newStatus, Integer approval, Integer amountStatus, Integer memberType,
									 Integer pageNo, Integer pageSize){

			List<outOrderDunListBo> list=(List<outOrderDunListBo>) dunOrderNewList( name,  orderNo, contractNo, starTime,  endTime,specially,
					 aid,  adminName, depId,newStatus, approval, amountStatus, memberType, pageNo,  pageSize).getList();
		NewExcelUtil<outOrderDunListBo> excelUtil = new NewExcelUtil<>(outOrderDunListBo.class);
		return 	excelUtil.exportExcel(list,"催款截点统计表",uploadPath);
	}

	private String bigToString (BigDecimal o){
		if(o==null){return "";}
		else{
			return o.stripTrailingZeros().toEngineeringString();
		}
	}

	@Override
	public int updateOrderOver(String orderNo) {
		TOrderNew t=tOrderNewMapper.queryById(orderNo);
		if (!t.getLiquidationStatus().equals(LiquidationNewState.ALREADY_PAY.getCode()) ||
				!t.getProcessStatus().equals(ProcessStatus.YQBFPZXSGLY.getCode())) {
			return -1;
		}
		List<TOrderTaskBo> list=tOrderTaskMapper.selectOrderTask(orderNo,0);
		for (TOrderTaskBo task : list) {
			if (!task.getTaskStatus().equals(TaskState.CLYWC.getCode())) {
				return -1;
			}
		}
		t.setOrderStatus(OrderNewState.YJX.getCode());
		t.setSettlementTime(new Date());
		return tOrderNewMapper.update(t);
	}

	@Override
	public OrderRefundDetailBo orderRefundDetail(String id) {
		return tOrderNewMapper.orderRefundDetail(id);
	}

	@Override
	public int updateOrderRefund(TOrderRefundWithBLOBs t) {
		checkDeleteSign(t.getOrderNo());
		return tOrderRefundMapper.updateByPrimaryKeySelective(t);
	}

	@Override
	public int updatetechnicianBackOrder(String orderNo,String reason) {
		TOrderNew t = checkDeleteSign(orderNo);
		t.setOrderStatus(OrderNewState.YBH.getCode());
		t.setProcessStatus(ProcessStatus.YPYXY.getCode());
		t.setFinanceId("");
		addBackOrder(orderNo, reason);
		List<String> aids = new ArrayList<>();
		aids.add(t.getSalesmanId());
		TOrderNewBo order = tOrderNewMapper.getSaleIdByOno(orderNo);
		pushGeneralSendNoticeAndEmail(aids, NoticeStatus.ORDER_NO.getCode(),order, TokenManager.getAdminId(),t.getApproval());
		tOrderNewMapper.update(t);
		financeCountOrderUnauditedSubtraction(t,2);
		pushNewSignUser(t);
		return 1;
	}

	/**
	 *
	 * @param use
	 * @param type 0 未审核减一 1未审核与派单数都减一  2 派单减一
	 */
	@Override
	public void financeCountOrderUnauditedSubtraction(TOrderNew use,Integer type) {
		Admin admin = adminMapper.selectFinanceAdminByOrderDep(use.getOrderDep());
		String startTime= DateUtils.formatDate(use.getCreateTime(),AFTConstants.YYYYMMDD);
		FinanceCount financeCount = financeCountMapper.selectByAidAndDates(admin.getId(), startTime);
		if(financeCount!=null){
			FinanceCount newFinance=new FinanceCount();
			newFinance.setId(financeCount.getId());
			if(type==0){
				newFinance.setOrderUnauditedCount(financeCount.getOrderUnauditedCount()-1);
			}else if(type==1){
				newFinance.setOrderCount(financeCount.getOrderCount()-1);
				newFinance.setOrderUnauditedCount(financeCount.getOrderUnauditedCount()-1);
			}else if(type==2){
				newFinance.setOrderCount(financeCount.getOrderCount()-1);
			}
			financeCountMapper.updateByPrimaryKeySelective(newFinance);
		}
	}

	@Override
	public void orderNewListDownload(InputOrderNewListBo in,HttpServletResponse response) {
		in.setPageSize(99999);
		Pagination<TOrderNewBo> pagination = orderNewList(in);
		List<TOrderNewBo> list = (List<TOrderNewBo>) pagination.getList();
		downloadOrderImg( list,  response);
	}

	public void downloadOrderImg(List<TOrderNewBo> list, HttpServletResponse response){
			String downloadFileName = "";
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			ZipOutputStream zip = new ZipOutputStream(outputStream);
			downloadFileName="订单合同数据.zip";
			for (TOrderNewBo t : list) {
				String annexUrl = t.getContractPictureUrl();
				if (StringUtils.isNotBlank(annexUrl)) {
					String[] split = annexUrl.split(",");
					if (split.length>0){
						int index =0;
						for (String s : split) {
							if (StringUtils.isNotEmpty(s)){
								index++;
								String url=s.replace("/profile/upload","");
								url=uploadPath+url;
								System.out.println(url);
								File file = new File(url);
								if (file.exists()){
									try {
										String suffix = s.substring(s.indexOf("."));
										String fileName=t.getUserName()+"("+t.getContractNo()+")"+"/"+t.getContractNo()+"_"+index+suffix;
										ZipEntry e = new ZipEntry(fileName);
										zip.putNextEntry(e);
										IOUtils.write(FileUtils.getBytes(file),zip);
										zip.closeEntry();
										zip.flush();
									} catch (IOException e){
										throw  new BusinessException("文件写入压缩失败："+e.getLocalizedMessage());
									}
								}
							}
						}
					}
				}
			}
			IOUtils.closeQuietly(zip);
			try {
				byte[] data = outputStream.toByteArray();
				response.reset();
				response.addHeader("Access-Control-Allow-Origin", "*");
				response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
				response.setHeader("Content-Disposition", "attachment; filename=\"" + java.net.URLEncoder.encode(downloadFileName, "utf-8").replaceAll("\\+", "%20") + "\"");
				response.addHeader("Content-Length", "" + data.length);
				response.setContentType("application/octet-stream; charset=UTF-8");
				IOUtils.write(data,response.getOutputStream());
			} catch (IOException e) {
				throw new RuntimeException(e);
			}

	}
	private TOrderNew checkDeleteSign(String orderNo) {
		TOrderNew t=tOrderNewMapper.queryById(orderNo);
		//if(t.getDeleteSign()==2) throw new BusinessException(new Error(ErrorConstants.ORDER_ALREADY_REVOKE, t.getOrderNo(),""));
		return t;
	}



	@Override
	public void addNotic(Integer type,  TOrderNewBo b,String str) {
		String aid=null;
		StringBuffer sb=new StringBuffer();
		//预设值 默认发给营销员
		aid=b.getSalesmanId();
		if (str==null){
			if (type.equals(NoticeStatus.ORDER_ARREARS_DUN.getCode()) || type.equals(NoticeStatus.PAYMENT_DUN.getCode()) ||
					type.equals(NoticeStatus.ORDER_DUN.getCode()) || type.equals(NoticeStatus.MENBER_DUN.getCode())){
				sb=sb.append("客户名称【").append(b.getUserName()).append("】,按时触发应收款欠款，请按时催款，并及时增减项目，以免项目延期等问题。");
			}
		}else {
			sb=sb.append(str);
		}

		asyncUtils.addNotic(type,aid,sb.toString());
	}


	public void sendEmail(String dunId,AdminListBo a,TOrderNewBo b){
		LoggerUtils.debug(logger, "======================邮件信息发送===================");
		String content = "<div>客户名称: "+ b.getUserName() +"</div><div>订单编号: " + b.getOrderNo() + "</div><div>合同编号: " + b.getContractNo() + "</div>";
		String tite="订单驳回";
			if(StringUtils.isNotBlank(dunId)) {
				TOrderDun tDun=tOrderDunMapper.selectByPrimaryKey(dunId);
				content +="<div>催收时间: " +  new SimpleDateFormat("yyyy-MM-dd").format(tDun.getCreateTime()) +
						"</div><div>催收科目: " + OrderDunSubject.getValueByCode(tDun.getDunSubject()) +
						"</div><div>催收情况: " + (tDun.getDunStatus()==2?"已完成":"已启动") +"</div>";
				tite="催收通知";
			}
			//发送驳回邮件
			EmailBo bo = new EmailBo(tite, b.getEmail(), a.getDepartmentName(), b.getSalesmanName());
			if(StringUtils.isNotBlank(b.getEmail())) {
				asyncUtils.send(bo);
			}
			LoggerUtils.debug(logger, "=========================================发送邮件成功");
	}

	@Override
	public int updateFinance(String orderNo, String newFinance) {
		String aid=TokenManager.getAdminId();
			String[] l=orderNo.split(",");
			List<String> orderNos=new ArrayList<>(Arrays.asList(l));
			tOrderNewMapper.updateFinance(aid,orderNos,newFinance);
			return 1;
	}

	@Override
	public List<TOrderLogBo> selectOrderLog(String orderNo) {
		return tOrderLogMapper.selectOrderByNo(orderNo);
	}

	@Override
	public  void pushGeneralSendNoticeAndEmail(List<String> alist, Integer type, TOrderNewBo order, String adminId, Integer approval) {
		pushGeneralSendNoticeAndEmail( alist,  type, order, adminId, approval,null);
	}
	@Override
	public  void pushGeneralSendNoticeAndEmail(List<String> alist, Integer type, TOrderNewBo order, String adminId, Integer approval, Integer tid) {
		AdminListBo a = adminMapper.getDeptNameByAid(adminId);
		StringBuffer str=new StringBuffer();
		String approvalType="";
		String noticeTypeName = NoticeStatus.getValueByCode(type);
		if (!approval.equals(ApprovalNewState.FTP.getCode())) {
			approvalType="[特批]";
		}
		//只有到技术总监是派单，其他都是审核
		if (order.getProcessStatus()==null||(!order.getProcessStatus().equals(ProcessStatus.YPZXSGLY.getCode()))){
			str.append("[审核]");
		}else {
			str.append("[派单]");
		}
		str.append(approvalType).append(noticeTypeName).append(":");
		if (tid != null) {
			str.append("项目编号[").append(tid).append("],");
		}
		str.append("客户名称[") .append(order.getUserName()).append("],");
		if(StringUtils.isNotBlank(order.getContractNo())) {
			str.append("合同编号[").append(order.getContractNo()).append("],");
		}
		str.append("订单编号[").append(order.getOrderNo()).append("],").append("操作人:")
				.append(a.getDepartmentName()).append("-").append(a.getName()).append("。");
		StringBuilder adminIds= new StringBuilder();
		List<Notice> nlist=new  ArrayList<>();
		for (String string : alist) {
			Notice n =new Notice();
			n.setId(UUID.randomUUID().toString());
			n.setNoticeType(type);
			n.setContent(str.toString());
			n.setCreateTime(new Date());
			n.setReaded(0);//未读
			n.setAid(string);
			nlist.add(n);
			Admin admin = adminMapper.selectAllByid(string);
			//去除邮件重复的
			if(admin!=null&&admin.getEmail()!=null&&SendEmailUtil.isEmail(admin.getEmail().trim())){
				if (!adminIds.toString().contains(admin.getEmail())){
					adminIds.append(admin.getEmail()).append(",");
				}
			}
		}
		if(!nlist.isEmpty()) {
			asyncUtils.addNoticeBatch(nlist);
		}
		if (!nlist.isEmpty()&&StringUtils.isNotBlank(adminIds.toString())) {
			adminIds = new StringBuilder(adminIds.substring(0, adminIds.length() - 1));
			EmailBo bo=new EmailBo(noticeTypeName, adminIds.toString(),str.toString());
			asyncUtils.send(bo);
		}
	}

	@Override
	@Transactional
	public int pushOutsourceProjectAudit(TOrderOutsource o) {
		//前端加载缓慢避免重复提交
		if(o.getId()==null){
			OrderOutsourceDtails ood=tOrderOutsourceMapper.selectByOrderNo(null,o.getTid().toString());
			if (ood!=null){
				return 1;
			}
		}
		o.setRefundStatus(0);
		o.setCreateTime(new Date());
		if(o.getAmount()==null) {
			o.setAmount(new BigDecimal(0));
		}
		if(o.getStartType()==null) {
			o.setStartType(0);
		}
		if (o.getStartType()==0) {
			List<String> aids = new ArrayList<>();
			for (Admin admin : adminMapper.getAdminRoleNameList("外包审核员")) {
				aids.add(admin.getId());
			}
			TOrderNew t2= checkDeleteSign(o.getOrderNo());
			Admin a =adminMapper.selectById(TokenManager.getAdminId());
			OutsourceLog ol=new OutsourceLog(o.getTid(),0,o.getReason(), TokenManager.getAdminId(),a.getName());
			outsourceLogMapper.insertSelective(ol);
			TOrderNewBo order = tOrderNewMapper.getSaleIdByOno(o.getOrderNo());
			pushGeneralSendNoticeAndEmail(aids, NoticeStatus.PROJECT_OUTSOURCE_START.getCode(),order, TokenManager.getAdminId(),t2.getApproval(),o.getTid());
		}else {
			o.setRefundStatus(1);
		}
		List<OutPaymentNode> list=paymentNodeMapper.selectByStatus(0);
		for (OutPaymentNode outPaymentNode : list) {
			if (outPaymentNode.getDunType()==1) {
				PaymentNode pn=new PaymentNode();
				pn.setId(outPaymentNode.getId());
				pn.setDunStatus(1);
				paymentNodeMapper.updateByPrimaryKeySelective(pn);
			}
		}
		if (o.getId()==null) {
			tOrderOutsourceMapper.insertSelective(o);
		}else {
			tOrderOutsourceMapper.updateByPrimaryKeySelective(o);
			//旧项目变更，如果驳回修改成新的项目变更
			if(o.getUnitNumber()!=null) {
				tOrderOutsourceMapper.updateByidNull(o.getId());
			}
		}
		if (o.getRefundStatus()==1){
			updateOrderCostAmount(o.getTid(),o.getStartType());
		}
		return 1;
	}

	/**
	 * 发起外包时，通过计算获取项目的成本，订单的成本
	 *
	 * @param tid 项目编号
	 * @param type 0外包 1供应商
	 */
	@Override
	public void updateOrderCostAmount(Integer tid,Integer type) {
		//计算项目成本
		List<OutThirdPartyCompany>list=thirdPartyCompanyMapper.selectByTid(tid);

		BigDecimal tCount=new BigDecimal(0);
		for (OutThirdPartyCompany op : list) {
			tCount=tCount.add(new BigDecimal(op.getTotalAmount()));
		}
		if(type==1) {
			ProjectTypePuls tt=tOrderTaskMapper.selectByTidGetDtails(tid);
			if (tt.getOutPatentType()==0){
				if (tt.getOfficialCost()==1) {
					if (tt.getCostReduction()==1) {
						tCount=tCount.add(tt.getProportion85().multiply(new BigDecimal(tt.getQuantity())));
					}else {
						tCount=tCount.add(tt.getOfficialAmount().multiply(new BigDecimal(tt.getQuantity())));
					}
				}
			}
		}
		BigDecimal party=new BigDecimal(0);
		List<outOrderPayment> paymentList = tOrderPaymentMapper.selectByTid(tid, null, null);
		for (outOrderPayment oo : paymentList) {
			if (oo.getStatus()==3){
				party=party.add(oo.getApplicationAmount());
			}
		}
		tTaskMidMapper.updateCostAmount(tid,tCount,party);
		// //计算订单成本 分类成本
		ProjectTypePuls projectTypePuls = tOrderTaskMapper.selectByTidGetDtails(tid);
		tOrderMidMapper.updateCostAmount(projectTypePuls.getOrderNo());
	}

	@Override
	@Cacheable(cacheNames = "statisticsList#500",key = "'statisticsList:depId:'+#in.depId+'province:'+#in.province+" +
			"'startCreate:'+#in.startCreate+'endCreate:'+#in.endCreate+'startSign:'+#in.startSign+'endSign:'+#in.endSign")
	public List<OutStatisticsList> statisticsList(InputStatistics in) {
		if(in.getEndCreate()!=null) {
			in.setEndCreate(in.getEndCreate()+" 23:59:59");
		}
		if(in.getEndSign()!=null) {
			in.setEndSign(in.getEndSign()+" 23:59:59");
		}
		List<OutStatisticsList> outStatisticsLists =new ArrayList<>();
		//原来sql计算
//		outStatisticsLists=tOrderNewMapper.statisticsList(in);
		//新java内部计算
		outStatisticsLists= CountStatisticOrderList(in);

		return outStatisticsLists;
	}

	private List<OutStatisticsList> CountStatisticOrderList(InputStatistics in) {
		List<OutStatisticsList> result=new ArrayList<>();
		List<StatisOrderList> statisOrderLists = tOrderNewMapper.statisticsOrderList(in);
		Map<Integer,List<StatisOrderList>> classmap= statisOrderLists.stream().collect(Collectors.groupingBy(StatisOrderList::getId));
		for (Integer key : classmap.keySet()) {
			Integer id= key;
			String name=classmap.get(key).get(0).getProvince();
			Double quantity = classmap.get(key).stream().mapToDouble(StatisOrderList::getQuantity).sum();
			BigDecimal total =CountStatisticOrderTotal(classmap.get(key));
			Integer counts=CountStatisticOrderCount(classmap.get(key));
			OutStatisticsList out =new OutStatisticsList();
			out.setId(id);
			out.setProvince(name);
			out.setQuantity(quantity);
			out.setTotal(total);
			out.setCounts(counts);
			result.add(out);
		}
		return result;
	}

	private Integer CountStatisticOrderCount(List<StatisOrderList> statisOrderLists) {
		Integer result =0;
		List<String> list=new ArrayList<>();
		for (StatisOrderList statisOrderList : statisOrderLists) {
			if (!list.contains(statisOrderList.getAid())){
				list.add(statisOrderList.getAid());
				result++;
			}
		}
		return result;
	}

	private BigDecimal CountStatisticOrderTotal(List<StatisOrderList> statisOrderLists) {
		BigDecimal result=new BigDecimal(0);
		for (StatisOrderList out : statisOrderLists) {
			result=result.add(out.getTotal());
		}
		return result;
	}

	@Override
	@Cacheable(cacheNames = "provinceStatisticsList#500",key = "'provinceStatisticsList:depId:'+#in.depId+'province:'+#in.province+" +
			"'startCreate:'+#in.startCreate+'endCreate:'+#in.endCreate+'startSign:'+#in.startSign+'endSign:'+#in.endSign")
	public List<OutProvinceStatisticsList> provinceStatisticsList(InputStatistics in) {
		if(in.getSort()==null) {
			in.setSort(0);
		}
		if(in.getEndCreate()!=null) {
			in.setEndCreate(in.getEndCreate()+" 23:59:59");
		}
		if(in.getEndSign()!=null) {
			in.setEndSign(in.getEndSign()+" 23:59:59");
		}
		List<OutProvinceStatisticsList> outProvinceStatisticsLists=null;
		//原sql计算
//		outProvinceStatisticsLists = tOrderNewMapper.provinceStatisticsList(in);
		//java计算
		outProvinceStatisticsLists= CountProvinceStatisticsOrder(in);
		return outProvinceStatisticsLists;
	}

	private List<OutProvinceStatisticsList> CountProvinceStatisticsOrder(InputStatistics in) {
		List<OutProvinceStatisticsList> result=new ArrayList<>();
		List<StatisOrderList> statisOrderLists = tOrderNewMapper.statisticsOrderList(in);
		Map<String,List<StatisOrderList>> classmap= statisOrderLists.stream().collect(Collectors.groupingBy(StatisOrderList::getAid));
		for (String key : classmap.keySet()) {
			String aid= key;
			String name=classmap.get(key).get(0).getAname();
			String depName=classmap.get(key).get(0).getDepName();
			Double quantity = classmap.get(key).stream().mapToDouble(StatisOrderList::getQuantity).sum();
			BigDecimal total =CountStatisticOrderTotal(classmap.get(key));
			OutProvinceStatisticsList out =new OutProvinceStatisticsList();
			out.setAid(aid);
			out.setName(name);
			out.setDepName(depName);
			out.setQuantity(quantity);
			out.setTotal(total);
			result.add(out);
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OutArrearsDunListBo> arrearsDunList(InputArrearsDunListBo in) {

		Map<String, Object> params = new HashMap<String, Object>();
		if(in.getPageSize()==null||in.getPageSize()<0) {
			in.setPageSize(10);
		}
		if(in.getPageNo()==null||in.getPageNo()<0) {
			in.setPageNo(1);
		}
		if (StringUtils.isNotBlank(in.getName())) {
			params.put("name", in.getName());
		}
		if (in.getDeps()!=null) {
			params.put("deps",departmentService.parseArray(in.getDeps()));
		}
		if (StringUtils.isNotBlank(in.getAdminName())) {
			params.put("adminName", in.getAdminName());
		}
		if (StringUtils.isNotBlank(in.getOrderNo())) {
			params.put("orderNo", in.getOrderNo());
		}
		if (StringUtils.isNotBlank(in.getContractNo())) {
			params.put("contractNo", in.getContractNo());
		}
		if (StringUtils.isNotBlank(in.getStarTime())) {
			params.put("starTime", in.getStarTime());
		}
		if (StringUtils.isNotBlank(in.getEndTime())) {
			params.put("endTime", in.getEndTime()+" 23:59:59");
		}
		if (StringUtils.isNotBlank(in.gettStarTime())) {
			params.put("tStarTime", in.gettStarTime());
		}
		if (StringUtils.isNotBlank(in.gettEndTime())) {
			params.put("tEndTime", in.gettEndTime()+" 23:59:59");
		}
		Integer i=null;
		 if (TokenManager.hasRole(AFTConstants.FINANCE)) {
			i=1;
			params.put("fid", TokenManager.getAdminId());
		}else if (TokenManager.hasRole(AFTConstants.FINANCE_MANAGER)) {
			i=2;
			params.put("fid", TokenManager.getAdminId());
		}else{
			 params.put("aid", TokenManager.getAdminId());
		}
		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(i!=null) {
			params.put("shiroType", i);
		}
		Pagination<OutArrearsDunListBo> p = (Pagination<OutArrearsDunListBo>)findPage("selectArrearsDunListByPage", "selectArrearsDunListByCount", params, in.getPageNo(), in.getPageSize());
		return p;
	}

	@Override
	public boolean checkOfficialType(TOrderOutsource o) {
		TOrderTaskDetailBo t=tOrderTaskMapper.getOrderTaskDetail(o.getTid());
		//项目类型是专利不是转让就需要获取专利官费
		if(t.getPatentTransfer()==0){
			if(t.getBpType()==1) {
				OfficialFeePrice of=officialFeePriceMapper.selectBytype(o.getPatentNameType(), t.getPatentType());
				if (of==null) {
					return true;
				}
			}
		}
		return false;
	}



	@Override
	public int updateOrderUrl(String orderNo, String contractPictureUrl, String agreementUrl, String serviceContent) {
		TOrderNew t=new TOrderNew();
		t.setOrderNo(orderNo);
		t.setContractPictureUrl(contractPictureUrl);
		t.setAgreementUrl(agreementUrl);
		t.setServiceContent(serviceContent);
		if (t.getContractPictureUrl()!=null||t.getAgreementUrl()!=null||t.getServiceContent()!=null){
			return tOrderNewMapper.update(t);
		}
		return 0;
	}

	@Override
	public OrderProcessName getProcessName(String orderNo) {
		OrderProcessName names=tOrderNewMapper.getProcessName(orderNo);
		return names;
	}

	@Override
	public void pushDunNodeContent() {
		List<TOrderNew> tOrderNews = tOrderNewMapper.selectgetAll();
		for (TOrderNew e : tOrderNews) {
			pushOrderDunContent(e);
		}
//		TOrderNew tOrderNew = tOrderNewMapper.queryById("412255829035991040");
//		pushOrderDunContent(tOrderNew);
	}

	@Override
	public void pushOrderDunContent(TOrderNew e) {
		String valueByCode = pushOrderGetDunContent(e);
		if (StringUtils.isNotBlank(valueByCode)){
			TOrderMid mid=new TOrderMid();
			mid.setOrderNo(e.getOrderNo());
			mid.setDunNodeContent(valueByCode);
			tOrderMidMapper.updateByOrderNo(mid);
		}
	}

	@Override
	public String pushOrderGetDunContent(TOrderNew e) {
		List<OutNewOrderDunBo> dunBoList = newOrderDunMapper.selectListNewOrderDun(e.getOrderNo(), null);
		StringBuilder valueByCode= new StringBuilder();
		for (OutNewOrderDunBo bo : dunBoList) {
			String str =""+bo.getProjectType()+bo.getDunType();
			valueByCode.append(NewOrderDunType.getValueByCode(Integer.valueOf(str)));
			if (bo.getDunType().equals(0)){
				valueByCode.append(bo.getCustomizeName());
				if(StringUtils.isNotBlank(bo.getCustomizeTimes())){
					valueByCode.append(" ").append(bo.getCustomizeTimes());
				}
			}else if (bo.getProjectType().equals(5)||bo.getProjectType().equals(6)){
				if (bo.getDunType().equals(2)){
					valueByCode.append(" ").append(bo.getStartDate());
				}

			}
			if (bo.getAppropriationRatio()!=null){
				valueByCode.append(" ").append(bo.getAppropriationRatio().multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString()).append("%");
			}else {
				valueByCode.append(" ").append(bo.getMoney().stripTrailingZeros().toPlainString());
			}
			if (bo.getStatus()==0){
				valueByCode.append(" 未启动");
			}else if (bo.getStatus()==1){
				valueByCode.append(" 已启动");
			}
			valueByCode.append(",");
		}
		if (valueByCode.length()>0)valueByCode.deleteCharAt(valueByCode.length()-1);
		return valueByCode.toString();
	}

	@Override
	public void pushOrderMaxDuration() {
		List<TOrderNew> tOrderNews = tOrderNewMapper.selectgetAll();
		for (TOrderNew e : tOrderNews) {
//		TOrderNew e = tOrderNewMapper.selectByPrimaryKey("1032662365591977984");
		pushOrderPublicReleaseCount(e);

		}
	}



    @Override
    public Object updateAddGroupChat(TOrderMid in) {
		TOrderMid update =new TOrderMid();
		TOrderMid tOrderMid = tOrderMidMapper.selectByOrderNo(in.getOrderNo());
		Date date = new Date();
		if (tOrderMid !=null){
			update.setId(tOrderMid.getId());
			update.setAddGroupChat(in.getAddGroupChat());
			if (update.getAddGroupChat()==1){
				update.setAddGroupChatTime(date);
			}
			tOrderMidMapper.update(update);
		}else {
			if (in.getAddGroupChat()==1){
				in.setAddGroupChatTime(date);
			}
			tOrderMidMapper.insertSelective(in);

		}
		return 1;
	}

	@Override
	public Object pushOrderNewUser() {
		List<TOrderNew> tOrderNews = tOrderNewMapper.selectgetAll();
		//最大年限设置3年
		int max=365*3;
		List<String> list=new ArrayList<>();
		for (TOrderNew e : tOrderNews) {
			String buyerId = e.getBuyerId();
			List<TOrderNew> tOrderNews1 = tOrderNewMapper.selectBuyerIdAndSignTime(buyerId, e.getSignTime(), 0);
			if (tOrderNews1.size()>0){
				TOrderNew tOrderNew = tOrderNews1.get(tOrderNews1.size() - 1);
				Date signTime = tOrderNew.getSignTime();
				long daysBetween = DateUtils.getDaysBetween(signTime,e.getSignTime());
				System.out.println(daysBetween);
				if (daysBetween<max){
					list.add(e.getOrderNo());
				}
			}
		}
		for (String s : list) {
			TOrderNew tOrderNew = new TOrderNew();
			tOrderNew.setOrderNo(s);
			tOrderNew.setNewSignUser(1);
			tOrderNewMapper.update(tOrderNew);
		}
		return 1;
	}

}
