package com.goafanti.order.service.impl;

import com.goafanti.admin.service.DepartmentService;
import com.goafanti.business.bo.BusinessProjectBo;
import com.goafanti.common.bo.Error;
import com.goafanti.common.bo.OrderExamineBo;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.ExportExcelUtil;
import com.goafanti.common.utils.OrderUtils;
import com.goafanti.common.utils.StringUtils;
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.order.bo.*;
import com.goafanti.order.enums.*;
import com.goafanti.order.service.NewOrderDunService;
import com.goafanti.order.service.OrderChangeService;
import com.goafanti.order.service.OrderNewService;
import com.goafanti.order.service.OrderProjectService;
import com.goafanti.organization.bo.OrganizationListOut;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderChangeServiceImpl extends BaseMybatisDao<NewOrderChangeMapper> implements OrderChangeService {
	@Autowired
	private NewOrderChangeMapper	newOrderChangeMapper;
	@Autowired
	private OrderChangeLogMapper	orderChangeLogMapper;
	@Autowired
	private TOrderNewMapper			tOrderNewMapper;
	@Autowired
	private TOrderLogMapper 		tOrderLogMapper;
	@Autowired
	private TOrderTaskMapper	tOrderTaskMapper;
	@Autowired
	private TOrderInvoiceMapper	tOrderInvoiceMapper;
	@Autowired
	private OrderRefundInvoiceMapper	orderRefundInvoiceMapper;
	@Autowired
	private TTaskMemberMapper	tTaskMemberMapper;
	@Autowired
	private NewOrderRefundMapper	newOrderRefundMapper;
	@Autowired
	private OrderExamineMapper	orderExamineMapper;
	@Autowired
	private BusinessProjectMapper	businessProjectMapper;
	@Autowired
	private NewOrderDunMapper	newOrderDunMapper;
	@Autowired
	private JDBCIdGenerator	idGenerator;
	@Autowired
	private AdminMapper	adminMapper;
	@Autowired
	private OrderNewService	orderNewService;
	@Autowired
	private NewOrderDunService	newOrderDunService;
	@Autowired
	private TChangeTaskMapper	tChangeTaskMapper;
	@Autowired
	private TChangeDunMapper	tChangeDunMapper;
	@Autowired
	private TOrderBillNewMapper tOrderBillNewMapper;
	@Autowired
	private TTaskMidMapper	tTaskMidMapper;
	@Autowired
	private PushOrderService pushOrderService;
	@Autowired
	private TOrderMidMapper tOrderMidMapper;
	@Autowired
	private UserMidMapper userMidMapper;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private OrderProjectService orderProjectService;
	@Autowired
	private DepartmentMapper departmentMapper;





	@Override
	public int addOrderChange(NewOrderChangeBo t,String startRemarks) {
		TOrderNew ton=new TOrderNew();
		ton.setOrderNo(t.getOrderNo());
		ton.setDeleteSign(2);//将订单置为锁定
		tOrderNewMapper.update(ton);
		BigDecimal invoiceAmount=tOrderInvoiceMapper.conutAmountByOrderNo(t.getOrderNo());
		t.setInvoiceAmount(invoiceAmount);//开票金额
		BigDecimal paymentAmount=tOrderBillNewMapper.conutAmountByOrderNo(t.getOrderNo());
		t.setPaymentAmount(paymentAmount);//收款金额
		//预计成本与预计退款：预计成本=项目价格*数量    预计退款=收款-预计成本
		BigDecimal estimateCost=new BigDecimal(tOrderTaskMapper.selectEstimateCost(t.getOrderNo()));
		t.setEstimateCost(estimateCost);
		t.setEstimateRefundable(paymentAmount.subtract(estimateCost));
		t.setZxsRemarks(startRemarks);
		newOrderChangeMapper.insertSelective(t);
		NewOrderChangeBo ncb=newOrderChangeMapper.selectByorderNoAndStatus(t.getOrderNo());
		List<OutNewOrderDunBo> listDun=newOrderDunMapper.selectListNewOrderDun(t.getOrderNo(),null);
		List<TChangeDun> listcd=new ArrayList<>();
		if (listDun!=null&&!listDun.isEmpty()) {
			for (OutNewOrderDunBo d : listDun) {
				TChangeDun cd = getChangeDun(d, ncb);
				listcd.add(cd);
			}
			tChangeDunMapper.insertSelectiveList(listcd);
		}
		List<TChangeTask> listck=new ArrayList<>();
		List<TOrderTaskBo> listTask=tOrderTaskMapper.selectOrderTaskAll(t.getOrderNo(),null);
		if (listTask!=null&&!listTask.isEmpty()) {
			for (TOrderTaskBo tt : listTask) {
				TChangeTask ck = getChangeTask(tt, ncb);
				listck.add(ck);
			}
			tChangeTaskMapper.insertBatch(listck);
		}
	//处理中间表数据
		tOrderMidMapper.updateMid(t.getOrderNo());
	return 1;
	}

	private TChangeTask getChangeTask(TOrderTaskBo tt, NewOrderChangeBo ncb) {
		TChangeTask ck=new TChangeTask();
		ck.setOrderNo(tt.getOrderNo());
		ck.setCid(ncb.getId());
		ck.setCommodityId(tt.getCommodityId());
		ck.setOrderNo(tt.getOrderNo());
		ck.setCommodityName(tt.getCommodityName());
		ck.setCommodityPrice(tt.getCommodityPrice());
		ck.setCommodityQuantity(tt.getCommodityQuantity());
		ck.setTaskComment(tt.getTaskComment());
		ck.setSplitStatus(tt.getSplitStatus());
		ck.setSplitSuper(tt.getSplitSuper());
		ck.setReceiverName(tt.getReceiverName());
		ck.setMain(tt.getMain());
		ck.setTid(tt.getId());
		ck.setType(0);
		if(tt.getServiceLife()!=null)ck.setServiceLife(tt.getServiceLife());
		if(tt.getServiceYear()!=null)		ck.setServiceYear(tt.getServiceYear());
		if(tt.getYearSum()!=null)	ck.setYearSum(tt.getYearSum());
		if(tt.getContractTerm()!=null)	ck.setContractTerm(tt.getContractTerm());
		if(tt.getLastYear()!=null)	ck.setLastYear(tt.getLastYear());
		if(tt.getLastYearCapital()!=null)	ck.setLastYearCapital(tt.getLastYearCapital());
		if(tt.getLastYearIncome()!=null)	ck.setLastYearIncome(tt.getLastYearIncome());
		if (tt.getHtMember()!=null) ck.setHtMember(tt.getHtMember());
		if (tt.getAdditionalDeduction()!=null) ck.setAdditionalDeduction(tt.getAdditionalDeduction());
		if (tt.getRdAwardsubsidy()!=null) ck.setRdAwardsubsidy(tt.getRdAwardsubsidy());
		return ck;
	}

	private TChangeDun getChangeDun(OutNewOrderDunBo d, NewOrderChangeBo ncb) {
		TChangeDun cd=new TChangeDun();
		cd.setOrderNo(d.getOrderNo());
		cd.setAid(d.getAid());
		cd.setAppropriationRatio(d.getAppropriationRatio());
		cd.setCid(ncb.getId());
		cd.setDid(d.getId());
		cd.setTid(d.getTid());
		cd.setProjectType(d.getProjectType());
		cd.setDunType(d.getDunType());
		cd.setMoney(d.getMoney());
		cd.setWaitDay(d.getWaitDay());
		cd.setStartTime(d.getStartTime());
		cd.setEffectiveCount(d.getEffectiveCount());
		cd.setCustomizeTime(d.getCustomizeTime());
		cd.setCustomizeName(d.getCustomizeName());
		return cd;
	}

	/*
	 * 新增审核流程中的
	 */
	private void pushOrderExamine(String orderNo,Integer type) {
		orderExamineMapper.deleteByAidAndStatus(orderNo,null,null);
		List<TOrderTaskBo> list=tOrderTaskMapper.selectOrderTaskAll(orderNo,null);
		for (TOrderTaskBo t : list) {
			addOrderExamineByTask(orderNo, type, t);
		}
	}

	private void addOrderExamineByTask(String orderNo, Integer type, TOrderTaskBo t) {
		//重报和仅项目变更只需要当事人审核
		if (Objects.equals(type, OrderChangeType.CB.getCode()) || Objects.equals(type, OrderChangeType.JXMBG.getCode())){
			Integer receiverType=null;
			if (t.getTaskReceiver()!=null){
				//等于咨询师 做咨询新增
				if (t.getTaskReceiver().equals(t.getConsultantId())) {
					receiverType=0;
					//等于经理做经理新增
				}else if  (t.getTaskReceiver().equals(t.getManagerId())){
					receiverType=1;
				}
			}
			if (receiverType!=null){
				OrderExamine o=new OrderExamine();
				o.setAid(t.getTaskReceiver());
				o.setOrderNo(orderNo);
				o.setCreateTime(new Date());
				o.setType(receiverType);//咨询师
				o.setStatus(0);//正常
				orderExamineMapper.insertSelective(o);
			}
			//项目及金额、退单不退款、退单退款需要当事人和经理审核，其他不需要咨询师审核
		}else if (Objects.equals(type, OrderChangeType.XMJJEBG.getCode()) || Objects.equals(type, OrderChangeType.TDBTK.getCode()) ||
                Objects.equals(type, OrderChangeType.TDTK.getCode())){
			if (t.getConsultantId()!=null) {
				OrderExamine o=new OrderExamine();
				o.setAid(t.getConsultantId());
				o.setOrderNo(orderNo);
				o.setCreateTime(new Date());
				o.setType(0);//咨询师
				o.setStatus(0);//正常
				orderExamineMapper.insertSelective(o);
			}
			if (t.getManagerId()!=null) {
				OrderExamine o=new OrderExamine();
				o.setAid(t.getManagerId());
				o.setOrderNo(orderNo);
				o.setCreateTime(new Date());
				o.setType(1);//咨询师经理
				o.setStatus(0);//正常
				orderExamineMapper.insertSelective(o);
			}
		}
	}

	@Override
	public List<NewOrderChangeBo> orderChangeDetails(String orderNo) {
		List<NewOrderChangeBo> list=newOrderChangeMapper.selectByorderNo(orderNo);
		if (!list.isEmpty()){
			for (NewOrderChangeBo c : list) {
				if (c.getContacts()==null){
					TOrderNew t=tOrderNewMapper.queryById(orderNo);
					c.setContacts(t.getContacts());
					c.setContactMobile(t.getContactMobile());
				}
			}
		}
		return list;
	}



	@Override
	public NewOrderChangeBo orderChangeDetailsById(Integer id) {
		NewOrderChangeBo nb=newOrderChangeMapper.selectById(id);
		int isExamine=orderExamineMapper.selectByOrderNoAndAid(nb.getOrderNo(),TokenManager.getAdminId());
		nb.setIsExamine(isExamine);
		if(nb.getProcessState()!=null){

			nb.setVoucherUrl(pushOrderService.changeProcessStatusConstant(nb.getVoucherUrl(),nb.getOrderNo(),nb.getProcessState(),nb.getStatus()));
		}
		return nb;
	}
	@Override
	@Transactional
	public int pushOrderChangeAudit(String changeId, String remarks, Integer status,Integer processState,Integer rejectState) {
		NewOrderChangeBo nb=newOrderChangeMapper.selectByChangeId(changeId);
		String orderNo=nb.getOrderNo();
		Department dep = tOrderNewMapper.selectDepByOrderNo(orderNo);
		if (processState==null||(nb.getProcessState()!=9&& !processState.equals(nb.getProcessState())) ) {
			throw new BusinessException(new Error( "变更流程与您所操作流程不匹配","变更流程与您所操作流程不匹配"));
		}
		if (nb.getStatus()==4) {
			throw new BusinessException(new Error( "变更流程已通过审核","变更流程已通过审核"));
		}
		Date date =new Date();
		//2通过 3驳回
		if (status==2) {
			//变更类型 0退单退款 1项目及金额变更 2仅项目变更 3仅金额变更 4重报 5赠送 6退单不退款 7仅变更合同
			if(nb.getType() !=null){
				if(Objects.equals(nb.getType(), OrderChangeType.JBGGT.getCode())){
					//
					if(Objects.equals(nb.getProcessState(), OrderChangeProcess.YXGLY.getCode())){
						nb.setProcessState(OrderChangeProcess.YYBZ.getCode());
						if (dep.getOperationGuaranteeId()==null){
							date.setTime(date.getTime()+100);
							addOrderChangeLog("无运营保障自动通过", 2, nb.getOrderNo(), nb.getId(),date);
							completeChange(remarks, nb);
							return 1;
						}else {
							nb.setProcessState(OrderChangeProcess.YYBZ.getCode());
						}
					}else if(Objects.equals(nb.getProcessState(), OrderChangeProcess.YYBZ.getCode())){
						completeChange(remarks, nb);
						return 1;
					}
				} else {
/* 赠送：营销-经理-总经理审核-财务（已收款情况)-运营保障-总裁
   重报：营销-经理-总经理审核-技术员-财务-财务总监-运营保障-总裁
   仅项目：营销-经理-总经理审核-技术员-技术总监-财务-财务总监-运营保障-总裁
   项目&金额：营销-经理-总经理审核-技术员-技术经理-技术总监-财务-财务总监-运营保障-总裁
   退单退款：营销-经理-总经理审核-技术员-技术经理-技术总监-财务-财务总监-运营保障-总裁-董事长（大于2K，需董事长审核）-财务退票
   退单不退款：营销-经理-总经理审核-技术员-技术经理-技术总监-财务-财务总监-运营保障-总裁-财务退票
   仅金额：营销-经理-总经理审核-技术总监-财务-财务总监-运营保障-总裁
   框架协议审核流程： 营销员发起-营销经理审核-营销管理员审核-财务审核-运营保障-完成
   仅合同图片修改：营销-营销总经理-运营保障-完成
*/
					if (Objects.equals(nb.getProcessState(), OrderChangeProcess.YXJL.getCode())){
						nb.setProcessState(OrderChangeProcess.YXGLY.getCode());
					}else if (Objects.equals(nb.getProcessState(), OrderChangeProcess.YXGLY.getCode())){
						if (Objects.equals(nb.getType(), OrderChangeType.CB.getCode()) ||
                                Objects.equals(nb.getType(), OrderChangeType.JXMBG.getCode()) ||
                                Objects.equals(nb.getType(), OrderChangeType.XMJJEBG.getCode()) ||
                                Objects.equals(nb.getType(), OrderChangeType.TDTK.getCode()) ||
                                Objects.equals(nb.getType(), OrderChangeType.TDBTK.getCode())){
							pushZXS(nb, date,1);
						}else if (Objects.equals(nb.getType(), OrderChangeType.JJEBG.getCode())){
							nb.setProcessState(OrderChangeProcess.JSZJ.getCode());
						}else if (Objects.equals(nb.getType(), OrderChangeType.ZS.getCode()) || Objects.equals(nb.getType(), OrderChangeType.KJXY.getCode())){
							nb.setProcessState(OrderChangeProcess.CWZY.getCode());
						}
					}else if (Objects.equals(nb.getProcessState(), OrderChangeProcess.JSY.getCode())){
						orderExamineMapper.updateByOrderNoAndAid(orderNo,TokenManager.getAdminId(),0);
						pushZXS(nb,date,0);
						//咨询师审核，将自己审核的全部标记已审核
					}else if (Objects.equals(nb.getProcessState(), OrderChangeProcess.JSJL.getCode())){
						//咨询师经理审核，将自己审核的全部标记已审核
						orderExamineMapper.updateByOrderNoAndAid(orderNo,TokenManager.getAdminId(),1);
						pushZXSJL(nb,date,0);
					}else if (Objects.equals(nb.getProcessState(), OrderChangeProcess.JSZJ.getCode())){
						nb.setProcessState(OrderChangeProcess.CWZY.getCode());
					}else if (Objects.equals(nb.getProcessState(), OrderChangeProcess.CWZY.getCode())){
						if (Objects.equals(nb.getType(), OrderChangeType.ZS.getCode())){
							//新增运营保障审核
							if (dep.getOperationGuaranteeId()==null){
								date.setTime(date.getTime()+100);
								addOrderChangeLog("无运营保障自动通过", 2, nb.getOrderNo(), nb.getId(),date);
								boolean flag=pushApproval(nb, dep,remarks);
								if (flag) return 1;
							}else {
								nb.setProcessState(OrderChangeProcess.YYBZ.getCode());
							}
						}else if (Objects.equals(nb.getType(), OrderChangeType.KJXY.getCode())){
							//新增运营保障审核
							if (dep.getOperationGuaranteeId()==null){
								date.setTime(date.getTime()+100);
								addOrderChangeLog("无运营保障自动通过", 2, nb.getOrderNo(), nb.getId(),date);
								completeChange(remarks, nb);
								return 1;
							}else {
								nb.setProcessState(OrderChangeProcess.YYBZ.getCode());
							}
							nb.setProcessState(OrderChangeProcess.YYBZ.getCode());

						}else {
							nb.setProcessState(OrderChangeProcess.CWZJ.getCode());
						}
					}else if (Objects.equals(nb.getProcessState(), OrderChangeProcess.CWZJ.getCode())){
						//新增运营保障审核
						if (dep.getOperationGuaranteeId()==null){
							date.setTime(date.getTime()+100);
							addOrderChangeLog("无运营保障自动通过", 2, nb.getOrderNo(), nb.getId(),date);
							boolean flag=pushApproval(nb, dep,remarks);
							if (flag) return 1;
						}else {
							nb.setProcessState(OrderChangeProcess.YYBZ.getCode());
						}
					}else if (Objects.equals(nb.getProcessState(), OrderChangeProcess.YYBZ.getCode())){
						if (Objects.equals(nb.getType(), OrderChangeType.KJXY.getCode())){
							completeChange(remarks, nb);
							return 1;
						}else {
							boolean flag=pushApproval(nb, dep,remarks);
							if (flag){
								return 1;
							}
						}
					}else if(Objects.equals(nb.getProcessState(), OrderChangeProcess.TPSH.getCode())) {
						if (Objects.equals(nb.getType(), OrderChangeType.TDTK.getCode()) || Objects.equals(nb.getType(), OrderChangeType.TDBTK.getCode())) {
							nb.setStatus(2);
						}else {
							completeChange(remarks, nb);
							return 1;
						}
					}else if (Objects.equals(nb.getProcessState(), OrderChangeProcess.FZC.getCode())){
							if (Objects.equals(nb.getType(), OrderChangeType.TDTK.getCode())) {
								if (nb.getChangeAmount().compareTo(new BigDecimal("0.2")) < 0) {
									//小于则总裁通过，大于则董事长
									nb.setStatus(2);
								}else {
									nb.setProcessState(OrderChangeProcess.DSZ.getCode());
								}
							}else if (Objects.equals(nb.getType(), OrderChangeType.TDBTK.getCode())){
								nb.setStatus(2);
							}else {
								completeChange(remarks, nb);
								return 1;
							}

						}else if (Objects.equals(nb.getProcessState(), OrderChangeProcess.DSZ.getCode())){
							if (Objects.equals(nb.getType(), OrderChangeType.TDTK.getCode()) || Objects.equals(nb.getType(), OrderChangeType.TDBTK.getCode())) {
								nb.setStatus(2);
							}else {
								completeChange(remarks, nb);
								return 1;
							}
						}
					}
				}
			if(nb.getStatus()==3) {
				nb.setStatus(1);//如果驳回数据则改为正常数据
			}
			//通过订单取消记录的驳回位置
			if (processState.equals(nb.getBackStatus())) {
				nb.setBackStatus(0);
			}
		}else {
			nb.setProcessState(rejectState);
			nb.setStatus(3);//订单变更设置为驳回
			//驳回订单记录驳回位置
			if (processState>nb.getBackStatus()) {
				nb.setBackStatus(processState);
			}
			//驳回重置审核人
			if (rejectState<=3) {
				orderExamineMapper.updateByOrderNo(orderNo,1,null);
			}else if (rejectState==4){
				orderExamineMapper.updateByOrderNo(orderNo,1,1);
			}
			if (rejectState==3) {
				orderExamineMapper.updateByOrderNoAndAid(nb.getOrderNo(),TokenManager.getAdminId(),0);
				int wsh=orderExamineMapper.checkCountStatus(nb.getOrderNo(),0,0);
				if (wsh==0){
					pushZXSJL( nb,date,1);
				}
			}else if(rejectState==4){
				pushZXSJL(nb,date,1);
			}
		}
		addOrderChangeLog(remarks, status, orderNo, nb.getId());
		sendNotice(status,nb);
		pushOrderCangeProcess(nb);
		newOrderChangeMapper.updateByPrimaryKeySelective(nb);
		return 1;
	}

	@Transactional
	public void completeChange(String remarks, NewOrderChangeBo nb ) {
		nb.setStatus(4);
		addOrderChangeLog(remarks, 2, nb.getOrderNo(), nb.getId());
		pushCompleteOrderChange(nb);
	}

	private boolean pushApproval(NewOrderChangeBo nb, Department dep,String remarks) {
		TOrderNew tOrderNew = tOrderNewMapper.queryById(nb.getOrderNo());
		Date date = new Date();
		date.setTime(date.getTime()+500);
		if (tOrderNew.getSalesmanId().equals(AFTConstants.CAOJIN_AID)) {
			nb.setProcessState(OrderChangeProcess.DSZ.getCode());
		}else {
			if (dep.getApproval()==1){
				nb.setProcessState(OrderChangeProcess.TPSH.getCode());
			}else {
				addOrderChangeLog("公司/部门管理审核人员未设置，系统自动通过", 2, nb.getOrderNo(), nb.getId(),date,AFTConstants.SUPERADMIN_ID);
				if (Objects.equals(nb.getType(), OrderChangeType.TDTK.getCode()) || Objects.equals(nb.getType(), OrderChangeType.TDBTK.getCode())){
					nb.setProcessState(OrderChangeProcess.TPSH.getCode());
					nb.setStatus(2);
				}else {
					completeChange(remarks,nb);
					return true;
				}
			}

		}
		return false;
	}

	/**
	 *
	 * @param type 0正常审核  1跨流程需要通知
	 */
	@Override
	public void pushZXS(NewOrderChangeBo nb,  Date date,Integer type) {
		int zxs=orderExamineMapper.checkCountStatus(nb.getOrderNo(),0,0);
		if (zxs>0){
			nb.setProcessState(OrderChangeProcess.JSY.getCode());
		}else {
			if(type==1){
				date.setTime(date.getTime()+100);
				addOrderChangeLog("无咨询师自动通过", 2, nb.getOrderNo(), nb.getId(), date);
			}
			if (Objects.equals(nb.getType(), OrderChangeType.CB.getCode())){
				nb.setProcessState(OrderChangeProcess.CWZY.getCode());
			} else if (Objects.equals(nb.getType(), OrderChangeType.JXMBG.getCode())){
				nb.setProcessState(OrderChangeProcess.JSZJ.getCode());
			}else {
				pushZXSJL(nb,date,1);
			}

		}
	}

	/**
	 * 咨询师经理，跳过就返回x=1,在后续添加日志放到先审核，后添加日志
	 * @param type 0正常审核  1跨流程需要通知
	 */
	@Override
	public void pushZXSJL(NewOrderChangeBo nb,Date date,Integer type) {
		int zxsjl=orderExamineMapper.checkCountStatus(nb.getOrderNo(),1,0);
		if (Objects.equals(nb.getType(), OrderChangeType.XMJJEBG.getCode()) ||
                Objects.equals(nb.getType(), OrderChangeType.TDTK.getCode()) ||
                Objects.equals(nb.getType(), OrderChangeType.TDBTK.getCode()) ||
                Objects.equals(nb.getType(), OrderChangeType.CB.getCode()) ||
                Objects.equals(nb.getType(), OrderChangeType.JXMBG.getCode())){
			if (zxsjl>0){
				nb.setProcessState(OrderChangeProcess.JSJL.getCode());
			}else {
				if (type==1){
					date.setTime(date.getTime()+100);
					addOrderChangeLog("无咨询师经理自动通过", 2, nb.getOrderNo(), nb.getId(),date);
				}
				//重报 没有技术员跳入财务
				if (Objects.equals(nb.getType(), OrderChangeType.CB.getCode())){
					nb.setProcessState(OrderChangeProcess.CWZY.getCode());
					//项目变更没有跳入技术总监
				}else{
					nb.setProcessState(OrderChangeProcess.JSZJ.getCode());
				}
			}
		}
	}

	private void addOrderChangeLog(String remarks, Integer status, String orderNo, Integer id) {
		addOrderChangeLog(remarks,status,orderNo,id,null,null);
	}
	private void addOrderChangeLog(String remarks, Integer status, String orderNo, Integer id,Date date) {
		addOrderChangeLog(remarks,status,orderNo,id,date,null);
	}

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

	private void sendNotice(Integer status,NewOrderChangeBo nb) {
		//0发起2通过 3驳回
		Integer type=0;
		if(status==0)type=NoticeStatus.ORDER_CHANGE_START.getCode();
		if(status==2)type=NoticeStatus.ORDER_CHANGE_YES.getCode();
		if(status==3)type=NoticeStatus.ORDER_CHANGE_NO.getCode();
		//获取发起人与发起人部门
//		AdminListBo a = adminMapper.getDeptNameByAid(TokenManager.getAdminId());
		//获取客户信息
		TOrderNewBo o=tOrderNewMapper.getSaleIdByOno(nb.getOrderNo());
		//获取接收者
		//流程状态 0=营销员，1=营销经理，2=营销管理员，3=技术员，4=技术经理，5=技术总监，6=财务专员，7=财务总监，8=总裁，9=董事长
		List<String> alist = new ArrayList<>();
		if (nb.getProcessState().equals(OrderChangeProcess.YXY.getCode())){
			alist.add(o.getSalesmanId());
		} else if (nb.getProcessState().equals(OrderChangeProcess.YXJL.getCode())) {
			Admin saleaman = adminMapper.selectById(o.getSalesmanId());
			alist.add(saleaman.getManagerId());
		}else if (nb.getProcessState().equals(OrderChangeProcess.YXGLY.getCode())) {
			alist.addAll(adminMapper.listNameByDepAndName(o.getOrderDep(), AFTConstants.SALESMAN_ADMIN));
		}else if (nb.getProcessState().equals(OrderChangeProcess.JSY.getCode())) {
			alist.addAll(addOrderExamine(o.getOrderNo(),0));
		}else if (nb.getProcessState().equals(OrderChangeProcess.JSJL.getCode())) {
			alist.addAll(addOrderExamine(o.getOrderNo(),1));
		}else if (nb.getProcessState().equals(OrderChangeProcess.JSZJ.getCode())) {
			for (Admin admin : adminMapper.getAdminRoleTypeList(AFTConstants.TECH_ADMIN)) {
				alist.add(admin.getId());
			}
		}else if (nb.getProcessState().equals(OrderChangeProcess.CWZY.getCode())) {
			alist.add(o.getFinanceId());
		}else if (nb.getProcessState().equals(OrderChangeProcess.CWZJ.getCode())) {
			for (Admin admin : adminMapper.getAdminRoleTypeList(AFTConstants.FINANCE_ADMIN)) {
				alist.add(admin.getId());
			}
		}else if (nb.getProcessState().equals(OrderChangeProcess.YYBZ.getCode())) {
			alist.add(o.getOperationGuaranteeId());
		}else if (nb.getProcessState().equals(OrderChangeProcess.TPSH.getCode())) {
			if(nb.getStatus()==2) {
				alist.add(o.getFinanceId());
			}else {
				alist.add(o.getApprovalAid());
			}
		}else if (nb.getProcessState().equals(OrderChangeProcess.DSZ.getCode())) {
			if(nb.getStatus()==2) {
				alist.add(o.getFinanceId());
			}else {
				for (Admin admin : adminMapper.selectAdminByRoleType(AFTConstants.APPROVAL_DECISION)) {
					alist.add(admin.getId());
				}
			}
		}else if (nb.getProcessState().equals(OrderChangeProcess.FZC.getCode())) {
			if(nb.getStatus()==2) {
				alist.add(o.getFinanceId());
			}else {
				for (Admin admin : adminMapper.selectAdminByRoleType(AFTConstants.VICE_CED)) {
					alist.add(admin.getId());
				}
			}
		}
		//发送站内信息与邮件
		pushGeneralSendNoticeAndEmail(alist, type, o, TokenManager.getAdminId(),0);
	}

	public void pushGeneralSendNoticeAndEmail(List<String> alist, Integer type,TOrderNewBo o,String adminId,Integer approval){
		orderNewService.pushGeneralSendNoticeAndEmail(alist, type,o, adminId,approval);
	}

	/**
	 *
	 * @param orderNo 订单编号
	 * @param i	 0咨询师 1咨询师经理
	 */
	private List<String> addOrderExamine(String orderNo, Integer i) {
		List<String> list=new ArrayList<>();
		List<OrderExamineBo> orderExamineBos = orderExamineMapper.selectByOrderNo(orderNo, i);
		for (OrderExamineBo bo : orderExamineBos) {
			if (bo.getStatus()==0){
				list.add(bo.getAid());
			}
		}
		return list;
	}

	/**
	 * 变更完成复制出原订单镜像
	 */
	private void changeAdopt(NewOrderChangeBo nb) {
		TOrderNew t1=tOrderNewMapper.queryById(nb.getOrderNo());
		List<OutNewOrderDunBo> td2=newOrderDunMapper.selectListNewOrderDun(nb.getOrderNo(),  null);
		List<TOrderTaskBo> tt1=tOrderTaskMapper.selectOrderTaskAll(nb.getOrderNo(),null);
		List<TOrderLogBo> tl1=tOrderLogMapper.selectOrderByNo(nb.getOrderNo());
		String newOrderNo=idGenerator.generateId().toString();
		t1.setOrderNo(newOrderNo);
		nb.setUsedOrder(newOrderNo);
		t1.setDeleteSign(1);//将原订单作废，只能查看
		tOrderNewMapper.insertSelective(t1);
		Map<Integer, Integer> map=new HashMap<>();
		for (TOrderTaskBo tOrderTaskBo : tt1) {
			//处理父子项目关系 将员父项目存储
			int x=tOrderTaskBo.getId();
			tOrderTaskBo.setId(null);
			tOrderTaskBo.setOrderNo(newOrderNo);
			if(tOrderTaskBo.getSplitStatus()==2) {
				tOrderTaskBo.setSplitSuper(map.get(tOrderTaskBo.getSplitSuper()));
			}
			tOrderTaskBo.setProcessStatus(3);
			tOrderTaskMapper.insertSelective(tOrderTaskBo);
			TTaskMember tTaskMember = tTaskMemberMapper.selectByTid(x);
			if (tTaskMember!=null){
				tTaskMember.setId(null);
				tTaskMember.setTid(tOrderTaskBo.getId());
				tTaskMemberMapper.insertSelective(tTaskMember);
			}
			int y=tOrderTaskBo.getId();
			TTaskMid dtails = tTaskMidMapper.getDtails(tOrderTaskBo.getId());
			TTaskMid tTaskMid = new TTaskMid(y, new BigDecimal(0));
			tTaskMid.setDispatchProvince(dtails.getDispatchProvince());
			tTaskMid.setDutyDep(dtails.getDutyDep());
			tTaskMidMapper.insertSelective(tTaskMid);
			if(tOrderTaskBo.getSplitStatus()==1) {
				map.put(x, y);
			}
		}
		if (!td2.isEmpty()) {
			List<OutNewOrderDunBo> newtd2=new ArrayList<>();
			for (OutNewOrderDunBo outNewOrderDunBo : td2) {
				outNewOrderDunBo.setId(null);
				outNewOrderDunBo.setOrderNo(newOrderNo);
				newtd2.add(outNewOrderDunBo);
			}
			newOrderDunMapper.insertBatch(newtd2);
		}
		if (!tl1.isEmpty()) {
			List<TOrderLogBo> newtl1=new ArrayList<>();
			for (TOrderLogBo tOrderLogBo : tl1) {
				tOrderLogBo.setId(null);
				tOrderLogBo.setOrderNo(newOrderNo);
				newtl1.add(tOrderLogBo);
			}
			tOrderLogMapper.insertBatch(newtl1);
		}
		nb.setStatus(4);
		//将订单恢复正常
		TOrderNew orderNew =new TOrderNew();
		orderNew.setOrderNo(nb.getOrderNo());
		orderNew.setDeleteSign(0);
		orderNew.setPrimaryOrder(newOrderNo);
		int i =tOrderMidMapper.judgeProjectType(nb.getOrderNo());
		if (i>0){
			TOrderMid tm=new TOrderMid();
			tm.setOrderNo(nb.getOrderNo());
			tm.setProjectType(1);
			tm.setDunNodeContent(orderNewService.pushOrderGetDunContent(t1));
			tOrderMidMapper.updateByOrderNo(tm);
		}

		tOrderNewMapper.update(orderNew);
	}


	@Override
	public boolean checkOderNo(String orderNo) {
		int i=newOrderChangeMapper.checkOderNo(orderNo);
        return i > 0;
    }
	@Override
	public List<OrderChangeLogBo> selectOrderChangeLogList(String changeId) {
		return orderChangeLogMapper.selectOrderChangeLogList(changeId);
	}
	@Override
	public Pagination<NewOderCahngeListBo> selectOrderChangeList(String userName,Integer  processState,Integer timeType,String startTime,String endTime,
						String deps,String salesmanName,Integer complete,String orderNo, String contractNo,Integer type,Integer pageSize, Integer pageNo) {
		Map<String, Object> parameter=new HashMap<String, Object>();
		if(pageSize==null||pageSize<0)pageSize=10;
		if(pageNo==null||pageNo<0)pageNo=1;
		parameter.put("processState", processState==null?0:processState);
		parameter.put("complete", complete==null?0:complete);
		if (StringUtils.isNotBlank(userName)) parameter.put("userName", userName);
		if (StringUtils.isNotBlank(orderNo)) parameter.put("orderNo", orderNo);
		if (StringUtils.isNotBlank(contractNo)) parameter.put("contractNo", contractNo);
		if (null!=type) parameter.put("type", type);
		if (null!=timeType) parameter.put("timeType", timeType);
		if (StringUtils.isNotBlank(startTime)) parameter.put("startTime", startTime);
		if (StringUtils.isNotBlank(endTime)) parameter.put("endTime", endTime+" 23:59:59");
		if (processState==2){
			List<String > myDep;
			if (deps!=null) {
				myDep=departmentService.selectSubDeps(deps);
				if (myDep.isEmpty()){
					return new Pagination(1,10,0);
				}
			}else {
				myDep=departmentService.selectMyDeps();
			}
			parameter.put("deps",myDep);
		}else {
			if (deps!=null) {
				parameter.put("deps",departmentService.parseArray(deps));
			}
		}
		if (StringUtils.isNotBlank(salesmanName)) parameter.put("salesmanName", salesmanName);
		//财务专员有财务经理查看财务专员的权限
		if(processState.equals(OrderChangeProcess.CWZY.getCode()) &&TokenManager.hasRole(AFTConstants.FINANCE_MANAGER)) {
			parameter.put("aids", adminMapper.selectBySuperId(TokenManager.getAdminId()));
		}else {
			parameter.put("aid", TokenManager.getAdminId());
		}
		Pagination<NewOderCahngeListBo> data = (Pagination<NewOderCahngeListBo>)findPage("selectOrderChangeList", "selectOrderChangeCount", parameter, pageNo, pageSize);
		return data;
	}

	@Override
	public int updateOrderChange(NewOrderChangeBo t,Integer changeType,String startRemarks) {
		NewOrderChange  noc=new NewOrderChange();
		t.setProcessState(1);
		noc.setOrderNo(t.getOrderNo());
		noc.setId(t.getId());
		if (changeType==0) {
//			chekeChangeTaskNumber(noc);
			noc.setRemarks(t.getRemarks());
			if(t.getContractPictureUrl()!=null)noc.setContractPictureUrl(t.getContractPictureUrl());
			noc.setType(t.getType());
			noc.setVoucherUrl(t.getVoucherUrl());
			noc.setTotalAmount(t.getTotalAmount());
			noc.setSettlementAmount(t.getSettlementAmount());
			noc.setFirstAmount(t.getFirstAmount());
			noc.setChangeAmount(t.getChangeAmount());
			noc.setApplicant(t.getApplicant());
			noc.setStatus(1);//订单置为正常
			noc.setDepName(t.getDepName());
			noc.setContacts(t.getContacts());
			noc.setContactMobile(t.getContactMobile());
			noc.setManagerContacts(t.getManagerContacts());
			noc.setManagerContactMobile(t.getManagerContactMobile());
			Date date =new Date();
			addOrderChangeLog(startRemarks==null?"":startRemarks, 0, t.getOrderNo(), noc.getId(),date);
			if(t.getType()!=0)chekeAmout(t);
			TOrderNew ton=new TOrderNew();
			ton.setOrderNo(noc.getOrderNo());
			ton.setDeleteSign(2);
			if(t.getType()==OrderChangeType.KJXY.getCode()){
				ton.setTotalAmount(t.getTotalAmount());
			}
			tOrderNewMapper.update(ton);
			TOrderNewBo tOrderNew = tOrderNewMapper.getSaleIdByOno(t.getOrderNo());
			if (t.getType()!=OrderChangeType.JBGGT.getCode()){
			//不是仅合同变更就看营销经理是否存在
				if (tOrderNew.getManagerName()!=null){
					noc.setProcessState(OrderChangeProcess.YXJL.getCode());
				}else {
					//增加营销经理的日志
					date.setTime(date.getTime()+200);
					addOrderChangeLog("未设置营销经理自动通过", 2, t.getOrderNo(), noc.getId(),date);
					//营销经理不存在判定营销管理员
					List<Admin> admins = adminMapper.listAdminBydepIdAndRoleType(tOrderNew.getOrderDep(), AFTConstants.SALESMAN_ADMIN);
					boolean flag=false;
					for (Admin admin : admins) {
						if (tOrderNew.getSalesmanId().equals(admin.getId())){
							flag=true;
						}
					}
					//如果自己是审核人员则跳过
					if (flag){
						date.setTime(date.getTime()+200);
						addOrderChangeLog("审核人重复自动通过", 2, t.getOrderNo(), noc.getId(),date);
						noc.setProcessState(OrderChangeProcess.JSY.getCode());
						if (t.getType()==OrderChangeType.CB.getCode()||
								t.getType()==OrderChangeType.JXMBG.getCode()||
								t.getType()==OrderChangeType.XMJJEBG.getCode()||
								t.getType()==OrderChangeType.TDTK.getCode()||
								t.getType()==OrderChangeType.TDBTK.getCode()){
							//将所有审核重置
							orderExamineMapper.updateByOrderNo(t.getOrderNo(),null,null);
							pushZXS(t,date,1);
						}else if(t.getType()==OrderChangeType.ZS.getCode()||t.getType()==OrderChangeType.KJXY.getCode()){
							noc.setProcessState(OrderChangeProcess.CWZY.getCode());
						}else if(t.getType()==OrderChangeType.JJEBG.getCode()){
							noc.setProcessState(OrderChangeProcess.JSZJ.getCode());
						}
					}else {
						//不跳过就设置流程未营销管理员
						noc.setProcessState(OrderChangeProcess.YXGLY.getCode());
						t.setProcessState(OrderChangeProcess.YXGLY.getCode());
					}
				}
			}else {
				noc.setProcessState(OrderChangeProcess.YXGLY.getCode());
				t.setProcessState(OrderChangeProcess.YXGLY.getCode());
			}
			sendNotice(0, t);
			pushOrderCangeProcess(noc);
			//框架协议不需要设置咨询师审核角色
			if (t.getType()!=OrderChangeType.KJXY.getCode()){
				pushOrderExamine(noc.getOrderNo(),noc.getType());
			}
		}else  if (changeType==2) {
			noc.setCwCost(t.getCwCost());
			noc.setCwIndirectCost(t.getCwIndirectCost());
			noc.setRefundableAmount(t.getRefundableAmount());
		}
		if(changeType!=1)newOrderChangeMapper.updateByPrimaryKeySelective(noc);
		return 1;
	}

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


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

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

		}else if (Objects.equals(noc.getProcessState(), OrderChangeProcess.YYBZ.getCode())){
			TOrderNewBo ton = tOrderNewMapper.getSaleIdByOno(noc.getOrderNo());
			noc.setExamineName(ton.getOperationGuaranteeName());
		} else if (Objects.equals(noc.getProcessState(), OrderChangeProcess.TPSH.getCode())
				|| Objects.equals(noc.getProcessState(), OrderChangeProcess.DSZ.getCode())
				|| Objects.equals(noc.getProcessState(), OrderChangeProcess.FZC.getCode())){
			if(noc.getStatus()==1){
				StringBuilder str=new StringBuilder();
				if (Objects.equals(noc.getProcessState(), OrderChangeProcess.TPSH.getCode())){
					Department department = tOrderNewMapper.selectDepByOrderNo(noc.getOrderNo());
					Admin a = adminMapper.selectById(department.getApprovalAid());
                    str.append(a.getName()).append(",");
                }else if(Objects.equals(noc.getProcessState(), OrderChangeProcess.DSZ.getCode())){
					List<Admin> admins = adminMapper.getAdminRoleTypeList(AFTConstants.APPROVAL_DECISION);
					for (Admin a : admins) {
                        str.append(a.getName()).append(",");
                    }
				}
				if (str.length()>0)noc.setExamineName(str.substring(0,str.length()-1));
			} else if(noc.getStatus()==2){
				TOrderNewBo ton = tOrderNewMapper.getSaleIdByOno(noc.getOrderNo());
				OrganizationListOut dep = departmentMapper.selectAllById(ton.getOrderDep());
				noc.setExamineName(dep.getFinanceName());
			}else {
				noc.setExamineName("");
			}
		}
	}

	private void chekeAmout(NewOrderChangeBo t) {
		BigDecimal amout=t.getTotalAmount();
		List<TChangeTaskOut> list = selectChangeTask(t.getId());
		BigDecimal count=new BigDecimal(0);
		for (TChangeTaskOut tt : list) {
			if(tt.getType()!=null&&tt.getType()!=3)count=count.add(tt.getCommodityPrice());
		}
		if (amout.compareTo(count)!=0) {
			throw new BusinessException("项目金额总和不等于合同总金额。");
		}
		List<TChangeDunOut> list2 = selectChangeDun(t.getId());
		count=new BigDecimal(0);
		for (TChangeDunOut td : list2) {
			if(td.getMoney()==null)td.setMoney(new BigDecimal(0));
			if(td.getType()!=null&&td.getType()!=3)count=count.add(td.getMoney());
		}
		if (amout.compareTo(count)!=0) {
			throw new BusinessException("收款节点金额总和不等于合同总金额。");
		}
	}




	@Override
	public int addOrderRefundInvoice(OrderRefundInvoice o) {
		o.setCreateTime(new Date());
		newOrderChangeMapper.addRefundInvoice(o.getOrderNo(),o.getAmount());
		return orderRefundInvoiceMapper.insertSelective(o);
	}

	@Override
	public int deleteOrderRefundInvoice(Integer id) {
		OrderRefundInvoice or=orderRefundInvoiceMapper.selectByPrimaryKey(id);
		newOrderChangeMapper.subtractRefundInvoice(or.getOrderNo(),or.getAmount());
		return orderRefundInvoiceMapper.deleteByPrimaryKey(id);
	}

	@Override
	public List<OrderRefundInvoice> listOrderRefundInvoice(String orderNo) {
		return orderRefundInvoiceMapper.selectByorderNo(orderNo);
	}

	@Override
	@Transactional
	public int pushCompleteOrderChange(NewOrderChangeBo nb) {
		//变更完成
		changeAdopt(nb);
		pushChange(nb);
		newOrderChangeMapper.updateByPrimaryKeySelective(nb);
		TOrderNewBo order=tOrderNewMapper.getSaleIdByOno(nb.getOrderNo());
		List<String> alist = getAllAid(nb.getId());
		Date date=new Date();
		date.setTime(date.getTime()+500);
		addOrderChangeLog("变更完成。", 4, nb.getOrderNo(), nb.getId(),date);
		pushGeneralSendNoticeAndEmail(alist,NoticeStatus.ORDER_CHANGE_END.getCode(), order, TokenManager.getAdminId(),0);
		TOrderNew tOrderNew = tOrderNewMapper.queryById(nb.getOrderNo());
		orderNewService.pushOrderPublicReleaseCount(tOrderNew);
		//修改投标标识
		tOrderMidMapper.updateBidTypeByOrderNo(nb.getOrderNo());
		return 1;
	}

	/**
	 * 获取除当前审核者所有审核者
	 * @param id
	 * @return
	 */
	private List<String> getAllAid(Integer id) {
		List<String> alist = new ArrayList<>();
		List<String>newl=new ArrayList<>();
		List<OrderChangeLogBo>  list=orderChangeLogMapper.selectOrderChangeLogList(id.toString());
		for (OrderChangeLogBo log : list) {
			if (!TokenManager.getAdminId().equals(log.getAuditor())){
				if (!newl.contains(log.getAuditor())){
					newl.add(log.getAuditor());
				}
			}
		}
		alist.addAll(newl);
		return alist;
	}


	@Override
	public int pushCompleteRefund(NewOrderChangeBo nb) {
		NewOrderChangeBo nob=newOrderChangeMapper.selectById(nb.getId());
		TOrderNewBo o=tOrderNewMapper.getSaleIdByOno(nob.getOrderNo());
		List<String> alist = new ArrayList<>();
		alist.add(o.getSalesmanId());
		nb.setOrderNo(nob.getOrderNo());
		nb.setExamineName("");
		nb.setType(nob.getType());
		newOrderChangeMapper.updateByPrimaryKeySelective(nb);
		addOrderChangeLog("变更财务退票。", 2, nob.getOrderNo(), nb.getId());
		pushGeneralSendNoticeAndEmail(alist,NoticeStatus.ORDER_CHANGE_YES.getCode(), o, TokenManager.getAdminId(),0);
		nb.setStatus(4);
		pushCompleteOrderChange(nb);
		return 1;
	}

	@Override
	public boolean checkChangeId(Integer id) {
		NewOrderChangeBo nob=newOrderChangeMapper.selectById(id);
		if (nob.getStatus()==4){
			return true;
		}
		return false;
	}



	/**
	 * 修改订单数据
	 * @param nb
	 */
	private TOrderNew pushChange(NewOrderChangeBo nb) {
		TOrderNew o=tOrderNewMapper.queryById(nb.getOrderNo());
		NewOrderChangeBo nob=newOrderChangeMapper.selectById(nb.getId());
//		变更类型 0退单退款 1项目及金额变更 2仅项目变更 3仅金额变更 4重报 5赠送
		if(nob.getType()==OrderChangeType.TDTK.getCode()) {
			o.setTotalAmount(nob.getTotalAmount());
			if (nob.getFirstAmount()!=null)o.setFirstAmount(nob.getFirstAmount());
		}else if (nob.getType()==OrderChangeType.XMJJEBG.getCode()) {
			o.setTotalAmount(nob.getTotalAmount());
			if (nob.getFirstAmount()!=null)o.setFirstAmount(nob.getFirstAmount());
		}else if (nob.getType()==OrderChangeType.JJEBG.getCode()) {
			o.setTotalAmount(nob.getTotalAmount());
			if (nob.getFirstAmount()!=null)o.setFirstAmount(nob.getFirstAmount());
		}else if (nob.getType()==OrderChangeType.CB.getCode()){
			o.setTotalAmount(nob.getTotalAmount());
			if (nob.getFirstAmount()!=null)o.setFirstAmount(nob.getFirstAmount());
		}
		//处理变更项目与催款新增在订单中
		pushTaskAndDun(nob.getId(),o);
		o.setProcessStatus(orderProjectService.getOrderProcessStatus(nb.getOrderNo()));
		o.setDeleteSign(0);
		//处理客户中间表退单标识
		//处理客户已派项目
		UserMid um=new UserMid();
		String taskNames=userMidMapper.getUserTaskNames(o.getBuyerId());
		um.setUid(o.getBuyerId());
		um.setTaskNames(taskNames);
		if (nb.getType()==0)um.setChargeback(1);
		userMidMapper.updateByUid(um);
		//如果合同不是空，则修改合同
		if (nob.getContractPictureUrl()!=null)o.setContractPictureUrl(nob.getContractPictureUrl());
		//清算状态 0-首付待付请，1-尾款待付清，2-已付请，3-部分退款，4-全部退款
		o.setLiquidationStatus(OrderUtils.getLiquidationStatus(o));
		tOrderNewMapper.update(o);
		orderProjectService.updateMidServiceProject(o.getOrderNo());
		return o;
	}





	private void pushTaskAndDun(Integer id,TOrderNew o) {
		pushChangeAddOrderTask(id);

		//处理主项目显示派单年份
		List<TChangeDunOut> listcd=tChangeDunMapper.selectByCid(id);
		for (TChangeDunOut cd : listcd) {
			NewOrderDun nd=new NewOrderDun();
			if (cd.getType()==1) {
			nd.setOrderNo(cd.getOrderNo());
			nd.setAid(cd.getAid());
			nd.setAppropriationRatio(cd.getAppropriationRatio());
			nd.setTid(cd.getTid());
			nd.setProjectType(cd.getProjectType());
			nd.setDunType(cd.getDunType());
			nd.setMoney(cd.getMoney());
			nd.setWaitDay(cd.getWaitDay());
			nd.setStartTime(cd.getStartTime());
			nd.setEffectiveCount(cd.getEffectiveCount());
			nd.setCustomizeTime(cd.getCustomizeTime());
			nd.setCustomizeName(cd.getCustomizeName());
			if (cd.getDunType()==1) {
				nd.setStatus(1);
				nd.setStartTime(new Date());
			}
			newOrderDunMapper.insertSelective(nd);
			}else if (cd.getType()==2) {
				nd.setId(cd.getDid());
				nd.setMoney(cd.getMoney());
				newOrderDunMapper.updateByPrimaryKeySelective(nd);
			}else if(cd.getType()==3) {
				newOrderDunMapper.deleteByPrimaryKey(cd.getDid());
			}
		}
		orderNewService.pushOrderMidDun(o);
	}

	/**
	 * 通过变更id来处理变更，先将父级新增、再新增子集。为了获取到订单项目的父子级关系
	 * @param id
	 */
	private void pushChangeAddOrderTask(Integer id) {
		List<TChangeTaskOut> listct=tChangeTaskMapper.selectByCid(id,3);
		HashMap<Integer, Integer> map=changeAddOrderTask(listct,null);
		List<TChangeTaskOut> listct2=tChangeTaskMapper.selectByCid(id,2);
		changeAddOrderTask(listct2,map);
	}

	/**
	 *
	 * @param listct 变更数据
	 * @param input  新增数据Id
	 */
	private HashMap<Integer, Integer> changeAddOrderTask(List<TChangeTaskOut> listct, HashMap<Integer, Integer> input) {
		HashMap<Integer, Integer> map = new HashMap<>();
		for (TChangeTaskOut cd : listct) {
			TOrderTask ot=new TOrderTask();
			if (cd.getType()==1) {
				ot.setOrderNo(cd.getOrderNo());
				ot.setCommodityId(cd.getCommodityId());
				ot.setCommodityName(cd.getCommodityName());
				ot.setCommodityPrice(cd.getCommodityPrice());
				ot.setCommodityQuantity(cd.getCommodityQuantity());
				ot.setTaskComment(cd.getTaskComment());
				ot.setMain(cd.getMain());
				ot.setTaskStatus(0);
				ot.setSplitStatus(cd.getSplitStatus());
				if (cd.getSplitStatus()==2){
					Integer tid;
					//如果原本有上级直接使用
					if (cd.getSplitSuper()!=null){
						ot.setSplitSuper(cd.getSplitSuper());
					}else {
						//如果没有，原本项目，这用获取新增的项目
						if (cd.getTid()!=null){
							tid=cd.getTid();
						}else{
							tid=input.get(cd.getChangeSplitSuper());
						}
						if (tid==null)tid=tChangeTaskMapper.selectById(cd.getChangeSplitSuper()).getTid();
						ot.setSplitSuper(tid);
					}
					ot.setSplitId(pushSplitId(ot.getSplitSuper()));
					ot.setCommodityPrice(new BigDecimal(0));
				}
				ChangeTaskParam(cd,ot);
				tOrderTaskMapper.insertSelective(ot);
				InputAddTask inMid=new InputAddTask();
				inMid.setId(ot.getId());
				inMid.setCommodityId(ot.getCommodityId());
				inMid.setOrderNo(ot.getOrderNo());
				inMid.setChange(1);
				inMid.setLastYear(cd.getLastYear());
				inMid.setLastYearCapital(cd.getLastYearCapital());
				inMid.setLastYearIncome(cd.getLastYearIncome());
				orderNewService.addTaskMid(inMid);
				if (cd.getSplitStatus()==1){
					map.put(cd.getId(),ot.getId());
				}
				orderNewService.addTTaskMember(ot.getId(),cd.getServiceLife(),cd.getServiceYear(),cd.getYearSum(),cd.getContractTerm());
				cd.setTid(ot.getId());
				tChangeTaskMapper.update(cd);
				tChangeDunMapper.updateByCTid(cd.getId(), ot.getId());
			}else if (cd.getType()==2) {
				ot.setId(cd.getTid());
				ot.setCommodityPrice(cd.getCommodityPrice());
				ot.setCommodityQuantity(cd.getCommodityQuantity());
				ot.setSplitStatus(cd.getSplitStatus());
				ChangeTaskParam(cd,ot);
				tOrderTaskMapper.update(ot);
				if (cd.getServiceLife()!=null){
					updateTaskMember(ot.getId(),cd.getServiceLife(),cd.getServiceYear(),cd.getYearSum(),cd.getContractTerm());
				}
				if (cd.getLastYear()!=null){
					updateTaskMid(ot.getId(),cd.getLastYear(),cd.getLastYearCapital(),cd.getLastYearIncome());
				}
			}else if(cd.getType()==3) {
				tOrderTaskMapper.deleteById(cd.getTid());
			}
		}
		return map;
	}

	private void ChangeTaskParam(TChangeTaskOut cd, TOrderTask ot) {
		if (cd.getDeclarationBatch()!=null)ot.setDeclarationBatch(cd.getDeclarationBatch());
		if (cd.getPatentType()!=null)ot.setPatentType(cd.getPatentType());
		if (cd.getOfficialCost()!=null) ot.setOfficialCost(cd.getOfficialCost());
		if (cd.getCostReduction()!=null) ot.setCostReduction(cd.getCostReduction());
		if (cd.getHtMember() != null) ot.setHtMember(cd.getHtMember());
		if (cd.getAdditionalDeduction()!=null) ot.setAdditionalDeduction(cd.getAdditionalDeduction());
		if (cd.getRdAwardsubsidy()!=null) ot.setRdAwardsubsidy(cd.getRdAwardsubsidy());
		if (cd.getTechnologyProjectType()!=null) ot.setTechnologyProjectType(cd.getTechnologyProjectType());
		if (cd.getOrdinaryRisk()!=null) ot.setOrdinaryRisk(cd.getOrdinaryRisk());
		if (cd.getDays()!=null) ot.setDays(cd.getDays());
		if (cd.getScheme()!=null) ot.setScheme(cd.getScheme());
		//新项目内容
		if (cd.getHtMember()!=null)ot.setHtMember(cd.getHtMember());
		if (cd.getAdditionalDeduction()!=null)ot.setAdditionalDeduction(cd.getAdditionalDeduction());
		if (cd.getRdAwardsubsidy()!=null)ot.setRdAwardsubsidy(cd.getRdAwardsubsidy());
		if (cd.getTechnologyProjectType()!=null)ot.setTechnologyProjectType(cd.getTechnologyProjectType());
		if (cd.getOrdinaryRisk()!=null)ot.setOrdinaryRisk(cd.getOrdinaryRisk());
		if (cd.getDays()!=null)ot.setDays(cd.getDays());
		if (cd.getScheme()!=null)ot.setScheme(cd.getScheme());
	}

	private Integer pushSplitId(Integer splitSuper) {
		//计算出拆分编号
		Integer i = tOrderTaskMapper.getSplitCount(splitSuper);
		i++;
		return i;
	}

	private void updateTaskMid(Integer id, String lastYear, BigDecimal lastYearCapital, BigDecimal lastYearIncome) {
		TTaskMid tTaskMid = new TTaskMid();
		tTaskMid.setTid(id);
		tTaskMid.setLastYear(lastYear);
		tTaskMid.setLastYearCapital(lastYearCapital);
		tTaskMid.setLastYearIncome(lastYearIncome);
		tTaskMidMapper.updateByTid(tTaskMid);
	}



	private void updateTaskMember(Integer id, String serviceLife, String serviceYear, Integer yearSum,String contractTerm) {
		TTaskMember ttm=new TTaskMember();
		ttm.setTid(id);
		ttm.setServiceLife(serviceLife);
		ttm.setServiceYear(serviceYear);
		ttm.setYearSum(yearSum);
		ttm.setContractTerm(contractTerm);
		tTaskMemberMapper.updateByTid(ttm);
	}




	@Override
	public Map<String, Object> listOrderInvoiceAndBill(String orderNo) {
		Map<String, Object> map=new HashMap<>();
		List<BillBo>list=tOrderBillNewMapper.selectByOrderNo(orderNo);
		List<InvoiceBo>list2=tOrderInvoiceMapper.selectByOrderNo(orderNo);
		map.put("bill", list);
		map.put("invoice", list2);
		return map;
	}

	@Override
	public void exportMyChange(HttpServletResponse response, String userName, Integer processState, Integer timeType,
			String startTime, String endTime, String deps, String salesmanName, Integer complete,String orderNo, String contractNo,
							   Integer type,Integer pageSize,Integer pageNo) throws IOException {
		OutputStream out = response.getOutputStream();
		List<NewOderCahngeListBo>list=(List<NewOderCahngeListBo>) selectOrderChangeList( userName,  processState, timeType, startTime, endTime,
				 deps, salesmanName, complete, orderNo,  contractNo, type, pageSize,  pageNo).getList();
		try {
    		//设计表头  String[] comment = {"合同编号","订单编号","客户名称","订单部门","订单类型","下单时间","订单状态","合同额(万元)","已付额(万元)","欠款(万元)","订单负责人","变更类型","变更审核状态","变更提交时间"}
    		String[] comment = {"合同编号","订单编号","客户名称","订单部门","订单类型","下单时间","订单状态","合同额(万元)","已付额(万元)","欠款(万元)","订单负责人","变更类型","变更审核状态","变更提交时间"};
    		String fileName ="开票变更记录表" + new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()) + ".xls";
    		//type 0 变更
    		XSSFWorkbook wb =ExportExcelUtil.exportTemplateInfoS(comment,"开票变更记录");
    		//根据列表编写文档
    		XSSFSheet sheet =wb.getSheetAt(0);
    		for (NewOderCahngeListBo ob : (List<NewOderCahngeListBo>)list) {
    			//新增一行
    			XSSFRow r = sheet.createRow(sheet.getLastRowNum()+1);
    			for (int i = 0; i < comment.length; i++) {
    				//当前列的只
    				String o = "";
    				switch (comment[i]) {
//    				String[] comment = {"合同编号","订单编号","客户名称","订单部门","订单类型","下单时间",
//    				"订单状态","合同额(万元)","已付额(万元)","欠款(万元)","订单负责人","变更类型","变更审核状态","变更提交时间"};
    				case "合同编号": o = ob.getContractNo(); break;
    				case "订单编号": o = ob.getOrderNo().toString(); break;
    				case "客户名称": o = ob.getNickname(); break;
    				case "订单部门": o = ob.getDepName(); break;
    				case "订单类型": o = OrderType.getValueByCode(ob.getOrderType()); break;
    				case "下单时间": o = ob.getEstablishTimes(); break;
    				case "订单状态": o = OrderNewState.getValueByCode(ob.getOrderStatus()); break;
    				case "合同额(万元)": o = ob.getTotalAmount().toString(); break;
    				case "已付额(万元)": o = ob.getSettlementAmount().toString(); break;
    				case "欠款(万元)": o = ob.getArrears().toString(); break;
    				case "订单负责人": o = ob.getSalesmanName(); break;
    				case "变更类型": o = OrderChangeType.getValueByCode(ob.getType()); break;
    				case "变更审核状态": o = getProcessState(ob.getProcessState(),ob.getStatus()); break;
    				case "变更提交时间": o = ob.getCreateTimes(); break;
    				default: o = ""; break;
    				}
    				XSSFCell c = r.createCell(i);
    				c.setCellValue(o);
    			}
    		}
    		//返回名称及参数
			 response.addHeader("Content-Disposition", "attachment;filename="  + new String(fileName.getBytes(),"iso-8859-1"));
			 response.setContentType("application/octet-stream;charset=utf-8");
    		 // 返回数据流
			 wb.write(out);
			 out.flush();
			 out.close();
		} catch (Exception e) {
			throw new BusinessException(new Error("表格生成错误。"));
		}finally {
			out.flush();
			 out.close();
		}
	}


			public static String getProcessState(Integer processState,Integer status) {
				String str="";
				if (processState == 0) {
				      str = "营销员";
				    } else if (processState == 1) {
				      str = "营销管理员";
				    } else if (processState == 2) {
				      str = "咨询师";
				    } else if (processState == 3) {
				      str = "咨询师经理";
				    } else if (processState == 4) {
				      str = "咨询师总监";
				    } else if (processState == 5) {
				      str = "财务专员";
				    } else if (processState == 6) {
				      str = "财务总监";
				    } else if (processState == 7) {
				      str = "总裁";
				    } else if (processState == 8) {
				      str = "董事长";
				    }
					String num = "";
				    if (status == 0) {
				      num = "发起";
				    } else if (status == 1) {
				      num = "审核中";
				    } else if (status == 2) {
				      num = "通过";
				    } else if (status == 3) {
				      num = "驳回";
				      return num + "到" + str;
				    } else if (status == 4) {
				      num = "完成";
				    }
				    if (processState == 7 && status == 2) {
				      return "订单变更退票中";
				    } else if (processState == 8 && status == 2) {
				      return "订单变更退票中";
				    } else if (processState >= 7 && status == 4) {
				      return "订单变更已完成";
				    } else {
				      return str + num;
				    }
			}


			@Override
			public Object addChangeTask(InputTChangeTaskBo t) {
				t.setType(1);

				tChangeTaskMapper.insertSelective(t);
				//如果是会员添加同性质不同项目
				BusinessProject bp=businessProjectMapper.selectById(t.getCommodityId());

				if (bp.getProjectType().equals(NewProjectTypeEnum.HT.getCode())){
						//先新增子项目
						addSonProject(t);
					InputTChangeTaskBo t2=new InputTChangeTaskBo();
						BeanUtils.copyProperties(t,t2);
						List<BusinessProjectBo> list = businessProjectMapper.selectByFirstBName(null,1);
						for (BusinessProjectBo e : list) {
							if(!e.getId().equals(t.getCommodityId())){
								t2.setCommodityId(e.getId());
								t2.setCommodityName(e.getBname());
								t2.setMain(0);
								t2.setCommodityPrice(new BigDecimal(0));
								t2.setId(null);
								tChangeTaskMapper.insertSelective(t2);
								addSonProject(t2);
							}
						}
				}else if(bp.getProjectType().equals(NewProjectTypeEnum.SIMPLE.getCode())||bp.getProjectType().equals(NewProjectTypeEnum.UNILATERAL.getCode())){
					addSonProject(t);
				}
				return t;
			}

	private void addSonProject(InputTChangeTaskBo t) {
		List<TChangeTask> sonList = t.getSonList();
		if (sonList != null && !sonList.isEmpty()){
			for (TChangeTask e : sonList) {
				//会员新增子项
				InputAddSonProject in=new InputAddSonProject();
				in.setId(t.getId());
				in.setServiceYear(e.getServiceYear());
				in.setTaskComment(e.getTaskComment());
				in.setHtMember(e.getHtMember());
				in.setAdditionalDeduction(e.getAdditionalDeduction());
				in.setRdAwardsubsidy(e.getRdAwardsubsidy());
				addMemberSonProject( in );

			}
		}
		//新增完子项再修改
		pushSuerProject( t);
	}

	private void pushSuerProject( InputTChangeTaskBo tChangeTask) {
		List<TChangeTask> tChangeTasks;
		if (tChangeTask.getTid()==null){
			 tChangeTasks = tChangeTaskMapper.selectBySuper(null, tChangeTask.getId(), tChangeTask.getCid());
		}else{
			tChangeTasks = tChangeTaskMapper.selectBySuper(tChangeTask.getTid(), null, tChangeTask.getCid());
		}
		if (!tChangeTasks.isEmpty()){
			int a=0,b=0,c=0;
			StringBuilder str= new StringBuilder();
			tChangeTask.setSplitStatus(1);
			for (TChangeTask e : tChangeTasks) {
				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();
				if (e.getServiceYear()!=null&&e.getType()!=3){
					str.append(e.getServiceYear()).append(",");
				}
			}
			tChangeTask.setServiceYear(str.substring(0, str.length() - 1));
			tChangeTask.setHtMember(a);
			tChangeTask.setAdditionalDeduction(b);
			tChangeTask.setRdAwardsubsidy(c);
			//根据上级id修改上级
			tChangeTaskMapper.update(tChangeTask);
		}

	}

	@Override
			public int addChangeDun(TChangeDun d) {
				d.setAid(TokenManager.getAdminId());
				d.setType(1);
				if(d.getCustomizeTimes()!=null)d.setCustomizeTime(DateUtils.StringToDate(d.getCustomizeTimes(), AFTConstants.YYYYMMDD));
				return tChangeDunMapper.insertSelective(d);
			}

			@Override
			public int deleteChangeTask(Integer id) {
				return tChangeTaskMapper.deleteById(id);
			}

			@Override
			public int deleteChangeDun(Integer id) {
				return tChangeDunMapper.deleteByPrimaryKey(id);
			}

			@Override
			public List<TChangeTaskOut> selectChangeTask(Integer cid) {
				List<TChangeTaskOut> list=tChangeTaskMapper.selectByCid(cid,3);//3设置不等于2
				for (TChangeTaskOut tChangeTaskOut : list) {
					if(tChangeTaskOut.getSplitStatus()==1){
						//变更会员子项目有2中，一种是复制过来的，根据上级项目编号关联，还一种是新增的根据变更项目编号关联

						TChangeTask input= new TChangeTask();
						input.setCid(cid);
						input.setSplitSuper(tChangeTaskOut.getTid());
						input.setChangeSplitSuper(tChangeTaskOut.getId());
						tChangeTaskOut.setList(getChangeSonTasks(input));
					}
				}
				return list;
			}

			@Override
			public List<TChangeDunOut> selectChangeDun(Integer cid) {
				return tChangeDunMapper.selectByCid(cid);
			}

			@Override
			public int updateChangeTask(InputTChangeTask t) {
				//有tid是订单复制项目
				if(t.getTid()!=null) {
					//type 0正常 1新增 2修改 3删除
					TChangeTask tt=tChangeTaskMapper.selectById(t.getId());
					BusinessProject bp = businessProjectMapper.selectById(tt.getCommodityId());
					Integer member=null;
					if (t.getType()==3) {

						//删除首先将项目删除，然后将所属催款做删除
						if (bp.getType()==7)member=1;
						tChangeTaskMapper.updateByTid(t.getTid(),null,tt.getCid(),3,member);
						if (tt.getSplitStatus()==0) {
							tChangeDunMapper.updateByTid(tt.getTid(),tt.getCid(),3);
						}else if (tt.getSplitStatus()==1) {
							t.setServiceYear("");
							//删除父类下所有的子类
							if (tt.getType()==1){
								tChangeTaskMapper.deleteByChangeSplitSuper(tt.getTid());
							}else {
								tChangeTaskMapper.updateByTid(null,tt.getTid(),tt.getCid(),3,member);
								tChangeDunMapper.updateByTid(tt.getTid(),tt.getCid(),3);
							}
						}else if(tt.getSplitStatus()==2) {
							List<TChangeTask> list=tChangeTaskMapper.selectBySuper(tt.getSplitSuper(),null,tt.getCid());
							boolean flag=true;
							for (TChangeTask tc : list) {
								if (tc.getType()!=3) {
									flag=false;
									break;
								}
							}
							if (flag) {
								//如果所有子类删除判断删除父类
								tChangeTaskMapper.updateByTid(tt.getSplitSuper(),null,tt.getCid(),3,member);
								tChangeDunMapper.updateByTid(tt.getSplitSuper(),tt.getCid(),3);
							}
						}
					}else if(t.getType()==2){
//						tChangeTaskMapper.updateByTid(t.getTid(),null,tt.getCid(),2,member);
						if (tt.getSplitStatus()==1) {
							if (t.getServiceLife()!=null||t.getServiceYear()!=null||t.getYearSum()!=null||t.getContractTerm()!=null){
								tChangeTaskMapper.updateMemberByTid(tt.getTid(),t.getCid(),null,t.getServiceLife(),t.getServiceYear(),t.getYearSum(),t.getContractTerm());
							}
							updateChangeType(tt);
						}else if(tt.getSplitStatus()==2) {
								tChangeTaskMapper.updateByTid(tt.getSplitSuper(),null,tt.getCid(),2,member);
						}
					}
					//如果没有tid是新增项目则直接删除
				}else {
					if (t.getType()==3) {
						tChangeTaskMapper.deleteById(t.getId());
						tChangeTaskMapper.deleteByChangeSplitSuper(t.getId());
						tChangeDunMapper.deleteByCtid(t.getId());
					}
				}
				return tChangeTaskMapper.update(t);
			}

	private void updateChangeType(TChangeTask t) {
		List<TChangeTask> changeSonTasks = getChangeSonTasks(t);
		List<Integer> list=new ArrayList<>();
		for (TChangeTask changeSonTask : changeSonTasks) {
			if (changeSonTask.getType()==0||changeSonTask.getType()==2){
				list.add(changeSonTask.getId());
			}
		}
		if(!list.isEmpty())tChangeTaskMapper.updateTypeBatch(2,list);
	}

	@Override
			public int updateChangeDun(TChangeDun t) {
				if(t.getCustomizeTimes()!=null)t.setCustomizeTime(DateUtils.StringToDate(t.getCustomizeTimes(), AFTConstants.YYYYMMDD));
				if (t.getType()==1||t.getType()==2) {
					return tChangeDunMapper.updateByPrimaryKeySelective(t);
				}else if(t.getType()==3){
					if (t.getDid()!=null) {
						return tChangeDunMapper.updateByPrimaryKeySelective(t);
					}else {
						return tChangeDunMapper.deleteByPrimaryKey(t.getId());
					}

				}else {
					return 0;
				}

			}

			@Override
			public List<TOrderNewBo> orderChangeUsed(String orderNo) {
				List<TOrderNewBo> list=tOrderNewMapper.selectUsedOrderByOrder(orderNo);
				for (TOrderNewBo t : list) {
					t.setDunList(newOrderDunService.selectListNewOrderDun(orderNo));
					t.setTaskList(orderNewService.selectOrderTask(orderNo,0));
				}
				return list;
			}

			@Override
			public List<Map<String, String>> getOrderChange(String orderNo) {
				List<Map<String, String>> list=new ArrayList<>();
				list =newOrderChangeMapper.getOrderChange(orderNo);
				return list;
			}

			@Override
			public int addOrderRefund(InputNewOrderRefund or) {
				or.setRefundTime(DateUtils.StringToDate(or.getRefundDate(), AFTConstants.YYYYMMDD));
				return newOrderRefundMapper.insertSelective(or);
			}

			@Override
			public int deleteRefund(Integer id) {
				return newOrderRefundMapper.deleteByPrimaryKey(id);
			}

			@Override
			public List<OutNewOrderRefund> listRefund(Integer id) {
				return newOrderRefundMapper.listRefund(id);
			}

			@Override
			public int pushRefund(Integer id,String refundUrl) {
				NewOrderChange noc=newOrderChangeMapper.selectByPrimaryKey(id);
				if (noc.getRefundStatus()!=1) {
					List<OutNewOrderRefund> list=listRefund(id);
					BigDecimal bd=new BigDecimal(0);
					TOrderNew order=tOrderNewMapper.queryById(noc.getOrderNo());
					for (OutNewOrderRefund o : list) {
						TOrderBillNew tbn =new TOrderBillNew();
						tbn.setOrderNo(o.getOrderNo());
						tbn.setTransactionAmount(o.getRefundAmount().negate());// 取负数
						tbn.setBillNo(UUID.randomUUID().toString().replaceAll("-", ""));
						tbn.setCreater(TokenManager.getAdminId());
						tbn.setPayeeId(order.getBuyerId());
						tbn.setPayerId("0");
						tbn.setRemarks(o.getRemarks());
						tbn.setTransactionSubject(2);
						tbn.setTransactionChannel(2);
						tbn.setConfirmSign(1);
						tbn.setRefundTime(o.getRefundTime());
						bd=bd.add(o.getRefundAmount());
						tOrderBillNewMapper.insertSelective(tbn);
					}
					TOrderNew o=new TOrderNew();
					o.setOrderNo(noc.getOrderNo());
					o.setRefundAmount(bd);
					tOrderNewMapper.updaterefund(o);
					NewOrderChange n=new NewOrderChange();
					n.setId(id);
					n.setRefundStatus(1);
					n.setRefundUrl(refundUrl);
					newOrderChangeMapper.updateByPrimaryKeySelective(n);
				}
				return 1;
			}

			@Override
			public boolean checkrefund(InputNewOrderRefund or) {
				if (or.getOrderNo()!=null) {
					TOrderNew o=tOrderNewMapper.queryById(or.getOrderNo());
					BigDecimal refund=new BigDecimal(0);
					List<OutNewOrderRefund> list=listRefund(or.getCid());
					refund=refund.add(or.getRefundAmount());
					for (OutNewOrderRefund oor : list) {
						refund=refund.add(oor.getRefundAmount());
					}
					if (o.getSettlementAmount().compareTo(refund)!=-1) {
						return false;
					}else {
						return true;
					}
				}
				return true;
			}

			@Override
			public int updateCancelOrderChange(NewOrderChangeBo nb) {
				NewOrderChange noc=new NewOrderChange();
				noc.setId(nb.getId());
				noc.setStatus(5);
				newOrderChangeMapper.updateByPrimaryKeySelective(noc);
				TOrderNew t=new TOrderNew();
				t.setOrderNo(nb.getOrderNo());
				t.setDeleteSign(0);
				addOrderChangeLog("变更撤销成功", 5, nb.getOrderNo(), nb.getId());
				tOrderNewMapper.update(t);
				return 1;
			}

	@Override
	public Object addMemberSonProject(InputAddSonProject in ) {
		//先修改父项目
		TChangeTask tChangeTask = tChangeTaskMapper.selectById(in.getId());
		Integer tid=tChangeTask.getTid();
		tChangeTask.setSplitStatus(1);
		if (tChangeTask.getType()!=1)tChangeTask.setType(2);
		TChangeTask newT=new TChangeTask();
		BeanUtils.copyProperties(tChangeTask,newT);
		//在判断是否有删除的年份没有就新增
		newT.setId(null);
		newT.setTid(null);
		newT.setSplitStatus(2);
		if(tid!=null){
			newT.setSplitSuper(tid);
		}else {
			newT.setChangeSplitSuper(in.getId());
		}
		newT.setType(1);
		newT.setCommodityQuantity(1);
		newT.setCommodityPrice(new BigDecimal(0));
		newT.setTaskComment(in.getTaskComment());
		newT.setServiceYear(in.getServiceYear());
		if (in.getHtMember()!=null)newT.setHtMember(in.getHtMember());
		if (in.getAdditionalDeduction()!=null)newT.setAdditionalDeduction(in.getAdditionalDeduction());
		if (in.getRdAwardsubsidy()!=null)newT.setRdAwardsubsidy(in.getRdAwardsubsidy());
		tChangeTaskMapper.insertSelective(newT);
		return newT;
	}

	public  void updateSuperServiceYear(TChangeTask tChangeTask) {
		if(tChangeTask.getSplitSuper()!=null){
			tChangeTaskMapper.updateSuperServiceYear(tChangeTask);
		}else {
			tChangeTaskMapper.updateChangeSuperServiceYear(tChangeTask);
		}
	}

	@Override
	public int deleteMemberSonProject(Integer id) {
		TChangeTask tChangeTask = tChangeTaskMapper.selectById(id);
		if (tChangeTask.getType()==1){
			tChangeTaskMapper.deleteById(id);
		}else {
			TChangeTask newtChangeTask = new TChangeTask();
			newtChangeTask.setId(id);
			newtChangeTask.setType(3);
			tChangeTaskMapper.update(newtChangeTask);

		}
		List<TChangeTask> tChangeTasks = getChangeSonTasks(tChangeTask);
		//如果没有子项目则修改上级
		if (tChangeTasks.isEmpty()) {
			TChangeTask changeTask = new TChangeTask();
			changeTask.setId(tChangeTask.getSplitSuper());
			changeTask.setSplitStatus(0);
			tChangeTaskMapper.update(changeTask);
		}
		updateSuperServiceYear(tChangeTask);
		return 1;
	}

	@Override
	public Object updateMemberSonProject(InputAddSonProject in) {
		TChangeTask tChangeTask = tChangeTaskMapper.selectById(in.getId());
		tChangeTask.setType(2);
		if (in.getHtMember()!=null) tChangeTask.setHtMember(in.getHtMember());
		if (in.getAdditionalDeduction()!=null) tChangeTask.setAdditionalDeduction(in.getAdditionalDeduction());
		if (in.getRdAwardsubsidy()!=null) tChangeTask.setRdAwardsubsidy(in.getRdAwardsubsidy());
		tChangeTaskMapper.update(tChangeTask);
		return tChangeTask;
	}



	/**
	 * 	如果是有splitSuper 是父有项目的tid,变更父项目有订单项目，则需要看订单项目变更后的子集，反正则不需要
	 * 	changeSplitSuper 是当前变更项目的子集
	 * @param tChangeTask
	 * @return
	 */
	private List<TChangeTask> getChangeSonTasks(TChangeTask tChangeTask) {
		List<TChangeTask> tChangeTasks = new ArrayList<>();
		if (tChangeTask.getSplitSuper()!=null)tChangeTasks.addAll(tChangeTaskMapper.selectBySuper(tChangeTask.getSplitSuper(),null, tChangeTask.getCid()));
		tChangeTasks.addAll(tChangeTaskMapper.selectBySuper(null, tChangeTask.getChangeSplitSuper(), tChangeTask.getCid()));
		return tChangeTasks;
	}



	@Override
	public Object gerProcessName(Integer id) {
		NewOrderChange newOrderChange=newOrderChangeMapper.selectByPrimaryKey(id);
		OutProcessName processName = newOrderChangeMapper.getProcessName(id, newOrderChange.getOrderNo());
		if (processName.getSalesmanId().equals(AFTConstants.CAOJIN_AID)){
			processName.setSpecial(1);
		}else {
			if (processName.getApprovalStatus()==0){
				processName.setApprovalName("未设置特批审核人员");
			}

		}
//		processName.setYybz(processName.getYybz()==null?"未设置营运保障审核":processName.getYybz());
		return processName;
	}

	@Override
	public boolean checkTaskMain(TChangeTask t) {
			int i=0;
		if (t.getMain()==1){
			if (t.getId()!=null) {
				TChangeTask tChangeTask = tChangeTaskMapper.selectById(t.getId());
				t.setCid(tChangeTask.getCid());
			}
			List<TChangeTaskOut> l = tChangeTaskMapper.selectByCid(t.getCid(), null);
			for (TChangeTaskOut task : l) {
				if (task.getId().equals(t.getId())){
					task.setMain(1);
				}
				if (task.getMain()==1&&(task.getSplitStatus()==0||task.getSplitStatus()==1)){
						i++;
				}
			}
			if (i>1){
				return true;
			}
		}

		return false;
	}

	@Override
	public void pushChangeProcess(String taskReceiverId, Integer type) {
		List<Integer> list = newOrderChangeMapper.selectProcess(type, taskReceiverId);
		if(!list.isEmpty()){
			Date date =new Date();
			for (Integer i : list) {
				NewOrderChangeBo changeBo = orderChangeDetailsById(i);
				if (type==3)pushZXS(changeBo,date,1);
				if (type==4)pushZXSJL(changeBo,date,1);
				newOrderChangeMapper.updateByPrimaryKeySelective(changeBo);
			}
		}
	}

	@Override
	public boolean checkMember(InputAddSonProject in) {
		TChangeTask tChangeTask = tChangeTaskMapper.selectById(in.getId());
		BusinessProject businessProject = businessProjectMapper.selectById(tChangeTask.getCommodityId());
        return businessProject.getProjectType() == 1 && (in.getHtMember() == 0 && in.getAdditionalDeduction() == 0 && in.getRdAwardsubsidy() == 0);
    }

	@Override
	public void pushSuerProject(InputAddSonProject in) {
		TChangeTask tChangeTask = tChangeTaskMapper.selectById(in.getId());
		InputTChangeTaskBo it= new InputTChangeTaskBo();
		BeanUtils.copyProperties(tChangeTask,it);
		pushSuerProject(it);
	}

}
