package com.goafanti.organization.service.impl;

import com.goafanti.admin.bo.AdminListBo;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.OrderLogProcess;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.AsyncUtils;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.order.bo.TOrderNewBo;
import com.goafanti.order.enums.ApprovalNewState;
import com.goafanti.order.enums.OrderChangeProcess;
import com.goafanti.order.enums.ProcessStatus;
import com.goafanti.organization.bo.DepOut;
import com.goafanti.organization.bo.InputDep;
import com.goafanti.organization.bo.OrganizationListOut;
import com.goafanti.organization.service.OrganizationService;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrganizationServiceImpl extends BaseMybatisDao<DepartmentMapper> implements OrganizationService {
	@Autowired
	private DepartmentMapper departmentMapper;
	@Autowired
	private ExpenseConfigDetailsMapper expenseConfigDetailsMapper;
	@Autowired
	private TOrderNewMapper torderNewMapper;
	@Autowired
	private TOrderMidMapper torderMidMapper;
	@Autowired
	private TOrderExamineMapper torderExamineMapper;
	@Autowired
	private TOrderLogMapper tOrderLogMapper;
	@Autowired
	private AdminMapper	adminMapper;
	@Autowired
	private NewOrderChangeMapper newOrderChangeMapper;
	@Autowired
	private ExpenseAccountExamineMapper expenseAccountExamineMapper;


	@Autowired
	private AsyncUtils asyncUtils;


	@Override
	public Pagination<OrganizationListOut> listOrganizationManagement(OrganizationListOut olo, Integer pageNo,
			Integer pageSize) {
		/*olo.setCreateId(TokenManager.getAdminId());*/
		Map<String,Object> params =disposeParams(olo);
		@SuppressWarnings("unchecked")
		Pagination<OrganizationListOut> p=(Pagination<OrganizationListOut>)findPage("selectOrganizationList","selectOrganizationCount",params,pageNo,pageSize);
		return p;
	}
	private Map<String,Object> disposeParams(OrganizationListOut olo){
		Map<String,Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(olo.getId())) params.put("id", olo.getId());
		if(StringUtils.isNotBlank(olo.getCreateId())) params.put("createId", olo.getCreateId());
		if(StringUtils.isNotBlank(olo.getCreateTime())) params.put("createTime", olo.getCreateTime());
		if(StringUtils.isNotBlank(olo.getUpdateTime())) params.put("updateTime", olo.getUpdateTime());
		if(StringUtils.isNotBlank(olo.getDeletedSign())) params.put("deletedSign", olo.getDeletedSign());
		if(StringUtils.isNotBlank(olo.getName())) params.put("name", olo.getName());
		if(StringUtils.isNotBlank(olo.getType())) params.put("type", olo.getType());
		if(StringUtils.isNotBlank(olo.getManagerId())) params.put("managerId", olo.getManagerId());
		if(StringUtils.isNotBlank(olo.getDepNo())) params.put("depNo", olo.getDepNo());
		if(StringUtils.isNotBlank(olo.getSuperId())) params.put("superId", olo.getSuperId());
		if(StringUtils.isNotBlank(olo.getRemarks())) params.put("remarks", olo.getRemarks());
		if(StringUtils.isNotBlank(olo.getStatus())) params.put("status", olo.getStatus());
		return params;
	}
	@Override
	public List<DepOut> selectSuperId(Integer hideSign) {
		if(hideSign==null){
			hideSign=1;
		}
		//此处理用于前端不批量改接口
		if (hideSign>1){
			hideSign=null;
		}
		List<DepOut> depList=departmentMapper.selectSuperId(hideSign,null,null);
		return listSort(depList);
	}

	private List<DepOut> listSort(List<DepOut> depList) {
		HanyuPinyinOutputFormat format=new HanyuPinyinOutputFormat();
		Collections.sort(depList, (o1, o2) -> {
			String str1=null;
			String str2=null;
			try {
				str1= PinyinHelper.toHanYuPinyinString(o1.getName(),format," ",true);
				str2= PinyinHelper.toHanYuPinyinString(o2.getName(),format," ",true);
			} catch (BadHanyuPinyinOutputFormatCombination e) {
				throw new RuntimeException(e);
			}
			return str1.compareTo(str2);
		});
		return depList;
	}

	@Override
	public List<DepOut> getAllDep(Integer hideSign) {
		if(hideSign==null){
			hideSign=1;
		}
		//此处理用于前端不批量改接口
		if (hideSign>1){
			hideSign=null;
		}
		List<DepOut> allDep=departmentMapper.selectSuperId(hideSign,null,null);

		List<DepOut> dep1=new ArrayList<>();
		Integer x=3;//设置顶级
		for (DepOut e : allDep) {
			if (e.getLvl()==x){
				e.setList(selectDepLvl(allDep,e.getId(),x+1));
				dep1.add(e);
			}
		}
		return dep1;
	}

	private List<DepOut> selectDepLvl(List<DepOut> allDep,String id, Integer i) {
		List<DepOut> newDep=new ArrayList<>();
		for (DepOut depOut : allDep) {
			if (depOut.getLvl()==i&&depOut.getSuperId().equals(id)){
				if (i<7)depOut.setList(selectDepLvl(allDep,depOut.getId(),i+1));
				newDep.add(depOut);
			}
		}
		return newDep;
	}


	/**
	 *   XXIn form 提交 ,bo包中
	 *   xxOut 输出 bo包中
	 *   domain 类 model中
	 *
	 */
	@Override
	public int addOrganization( String name, String managerId, String type, String superId, String remarks,
								Integer workingHoursType,Integer hideSign,String depNo) {
		Department superDep=departmentMapper.selectByPrimaryKey(superId);
		String id = UUID.randomUUID().toString();
		Date now = new Date();
		Department dep=new Department();
		dep.setId(id);
		String createId =departmentMapper.selectAdminNameById(TokenManager.getAdminId());
		dep.setCreateId(createId);
		dep.setCreateTime(now);
		dep.setUpdateTime(now);
		dep.setDeletedSign(0);
		dep.setName(name);
		dep.setLvl(superDep.getLvl()+1);
		dep.setType(type);
		dep.setManagerId(managerId);
		dep.setDepNo(depNo);
	//	superId=departmentMapper.selectIdByName(superId);
		dep.setSuperId(superId);
		dep.setRemarks(remarks);
		dep.setStatus("0");
		dep.setHideSign(hideSign);
		dep.setWorkingHoursType(workingHoursType);
		departmentMapper.insertSelective(dep);
		return 1;
	}

	private String getMaxDep(Department superDep) {
		String sdepNo=superDep.getDepNo();
		Department maxDep=departmentMapper.selectByDepNo(superDep.getId());
		String depNo=new String();
		if (maxDep==null){
			depNo= sdepNo +"01";
		}else {
			String maxDepNo=maxDep.getDepNo();
			Integer countNo=Integer.valueOf(maxDepNo.substring(maxDepNo.length()-2));
			countNo++;
			if (countNo<10){
				depNo= sdepNo +"0"+countNo;
			}else {
				depNo= sdepNo +countNo;
			}
		}
		return depNo;
	}


	@Override
	public List<AdminListBo> selectName(String name) {
		List<AdminListBo> list=departmentMapper.selectName(name);
		return list;
	}
	@Override
	public OrganizationListOut selectAllById(String id) {
		OrganizationListOut olo=departmentMapper.selectAllById(id);
		List<ExpenseConfigDetails> list = expenseConfigDetailsMapper.selectByDepId(id);
		olo.setExpenseRetrialFinanceExamineList(list.stream().filter(e ->e.getType()==1).collect(Collectors.toList()));
		olo.setCeoExamineList(list.stream().filter(e ->e.getType()==2).collect(Collectors.toList()));
		olo.setCfoExamineList(list.stream().filter(e ->e.getType()==3).collect(Collectors.toList()));
		olo.setViceCeoExamineList(list.stream().filter(e ->e.getType()==4).collect(Collectors.toList()));
		olo.setCashierExamineList(list.stream().filter(e ->e.getType()==5).collect(Collectors.toList()));
		olo.setSuperId(departmentMapper.selectNameById(olo.getSuperId()));
		return olo;
	}
	@Override
	public int deleteById(String id) {
		departmentMapper.deleteById(id);
		return 1;
	}
	@Override
	public int updateOrganization(InputDep in) {
		//获取上级编号
		Department superDep=departmentMapper.selectByPrimaryKey(in.getSuperId());
		Department useDep = departmentMapper.selectByPrimaryKey(in.getId());
		Date now=new Date();
		Department dep=new Department();
		dep.setLvl(superDep.getLvl()+1);
		dep.setName(in.getName());
		dep.setType(in.getType());
		dep.setUpdateTime(now);
		dep.setManagerId(in.getManagerId());
		dep.setStatus(in.getStatus());
		dep.setRemarks(in.getRemarks());
		dep.setId(in.getId());
		dep.setSuperId(in.getSuperId());
		dep.setDepNo(in.getDepNo());
		dep.setAbbreviation(in.getAbbreviation());
		dep.setProvince(in.getProvince());
		dep.setHideSign(in.getHideSign());
		dep.setWorkingHoursType(in.getWorkingHoursType());
		dep.setApproval(in.getApproval());
		dep.setApprovalAid(in.getApprovalAid());
		dep.setTechAdminId(in.getTechAdminId());
		dep.setOperationGuaranteeId(in.getOperationGuaranteeId());
		pushUpdateDep(in, useDep, dep);
		return departmentMapper.updateByPrimaryKeySelective(dep);
	}

	/**
	 * 根据传入参数处理各种情况，并且处理传入数据
	 * @param in 输入部门参数
	 * @param useDep 原部门参数
	 * @param dep  修改部门参数
	 */
	private void pushUpdateDep(InputDep in, Department useDep, Department dep) {
		List<String> orderS = new ArrayList();
		//如果本来部分没有，新增财务
		if(StringUtils.isBlank(useDep.getFinanceId())&&StringUtils.isNotBlank(in.getFinanceId())){
			addExamine(useDep, in.getFinanceId(),orderS);
		}
		if(in.getManagerId()!=null&&useDep.getManagerId()!=null&&!in.getManagerId().equals(useDep.getManagerId())){

			expenseAccountExamineMapper.updateExamine(in.getManagerId(),useDep.getManagerId(),useDep.getId());
		}

		//财务复审
		if(StringUtils.isBlank(useDep.getRetrialFinanceId())&&StringUtils.isNotBlank(in.getRetrialFinanceId())){
			addExamine(useDep, in.getExpenseFinanceId(),orderS);
		}
		//技术总监审核人
		if(StringUtils.isBlank(useDep.getTechAdminId())&&StringUtils.isNotBlank(in.getTechAdminId())){
			addExamine(useDep, in.getTechAdminId(),orderS);
		}
		//已派财务与总监审核
		if(!orderS.isEmpty()){
			torderNewMapper.updateOrderDepFinanceExamineName(orderS,ProcessStatus.YPCW_JSZJ.getCode());
		}
		//运营保障审核人
		if(StringUtils.isBlank(useDep.getOperationGuaranteeId())&&StringUtils.isNotBlank(in.getOperationGuaranteeId())){
			List<String> strings = torderNewMapper.selectByDepAndProcess(useDep.getId(), ProcessStatus.YYBZSH.getCode());
			if(!strings.isEmpty()){
				torderNewMapper.updateOrderDepFinanceExamineName(strings, ProcessStatus.YYBZSH.getCode());
			}
		}
		//财务与复审切换的时候要切换所有未审核的财务
		boolean updateFinance=false;
		boolean updateRetrialFinance=false;
		//获取需要重新刷新的财务
		List<String> aids =new ArrayList<>();
		if(!in.getFinanceId().equals(useDep.getFinanceId())){
				dep.setFinanceId(in.getFinanceId());
				//审核人切换
				departmentMapper.updateOrderDepFinanceNotExamine(in.getFinanceId(), useDep.getFinanceId(), useDep.getId());
				//查询切换后的订单刷新审核人
				List<String> list = torderNewMapper.selectByFinanceNotExamine(in.getFinanceId(), useDep.getId());
				if (!list.isEmpty()){
					torderNewMapper.updateOrderDepFinanceExamineName(list,ProcessStatus.YPCW_JSZJ.getCode());
				}
				updateFinance=true;
		}
		//如果技术总监、运营保障审核、财务复审为空则修改为null
		if (StringUtils.isBlank(in.getTechAdminId())||StringUtils.isBlank(in.getOperationGuaranteeId())
				||StringUtils.isBlank(in.getRetrialFinanceId())){
			if(StringUtils.isBlank(in.getTechAdminId())){
				in.setTechAdminId(null);
				dep.setTechAdminId(null);
			}
			if(StringUtils.isBlank(in.getOperationGuaranteeId())){
				in.setOperationGuaranteeId(null);
				dep.setOperationGuaranteeId(null);
			}
			if(StringUtils.isBlank(in.getRetrialFinanceId())){
				in.setRetrialFinanceId(null);
				dep.setRetrialFinanceId(null);
			}
			departmentMapper.updateNull(in);
		}
		//处理去掉技术总监
		if (in.getTechAdminId()==null||!in.getTechAdminId().equals(useDep.getTechAdminId())){
			if(StringUtils.isBlank(in.getTechAdminId())){
				//先将旧的查出来
				List<String> list = torderNewMapper.selectByFinanceNotExamine(useDep.getTechAdminId(),useDep.getId());
				//再删除旧单需要审核的
				torderExamineMapper.deleteExamineFinance(useDep.getId(), useDep.getTechAdminId());
				if (!list.isEmpty()){
					//先把药推送到下个流程的查出来
					for (String s : list) {
						pushCW_JSZJ_Examine(in, s, aids,  0);
					}
					torderNewMapper.updateOrderDepFinanceExamineName(list,ProcessStatus.YPCW_JSZJ.getCode());
				}
			}else{
				//审核人切换
				departmentMapper.updateOrderDepFinanceNotExamine(in.getTechAdminId(), useDep.getTechAdminId(), useDep.getId());
				//查询切换后的订单刷新审核人
				List<String> list = torderNewMapper.selectByFinanceNotExamine(in.getTechAdminId(), useDep.getId());
				if (!list.isEmpty()){
					torderNewMapper.updateOrderDepFinanceExamineName(list,ProcessStatus.YPCW_JSZJ.getCode());
				}
			}
		}
		if (!Objects.equals(in.getRetrialFinanceId(),useDep.getRetrialFinanceId())){
			if(StringUtils.isBlank(in.getRetrialFinanceId())) {
				//先将旧的查出来
				List<String> list = torderNewMapper.selectByFinanceNotExamine(useDep.getRetrialFinanceId(), useDep.getId());
				//再删除旧单需要审核的
				torderExamineMapper.deleteExamineFinance(useDep.getId(), useDep.getRetrialFinanceId());
				if (!list.isEmpty()) {
					//先把药推送到下个流程的查出来
					for (String s : list) {
						pushCW_JSZJ_Examine(in, s, aids,  1);
					}
					torderNewMapper.updateOrderDepFinanceExamineName(list,ProcessStatus.YPCW_JSZJ.getCode());
				}
			}else {
				dep.setRetrialFinanceId(in.getRetrialFinanceId());
				departmentMapper.updateOrderDepFinanceNotExamine(in.getRetrialFinanceId(), useDep.getRetrialFinanceId(), useDep.getId());
				List<String> list = torderNewMapper.selectByFinanceNotExamine(in.getRetrialFinanceId(), useDep.getId());
				if (!list.isEmpty()){
					torderNewMapper.updateOrderDepFinanceExamineName(list,ProcessStatus.YPCW_JSZJ.getCode());
				}
			}
			updateRetrialFinance=true;
		}
		if (in.getOperationGuaranteeId()==null&&StringUtils.isNotBlank(useDep.getOperationGuaranteeId())){
			List<String> strings = torderNewMapper.selectByDepAndProcess(useDep.getId(), ProcessStatus.YYBZSH.getCode());
			for (String s : strings) {
				addOrderLog(s,OrderLogProcess.YYBZSHTG.getCode(),"运营保障审核人未设置，系统自动通过");
				TOrderNew tOrderNew = torderNewMapper.queryById(s);
				TOrderNewBo order = torderNewMapper.getSaleIdByOno(s);
				StringBuilder str = new StringBuilder();
				TOrderNew newOrder = new TOrderNew();
				newOrder.setOrderNo(s);
				if (order.getApprovalStatus() == 0) {
					addOrderLog(s,OrderLogProcess.TP.getCode(),"部门特批审核未设置，系统自动通过");
					newOrder.setProcessStatus(ProcessStatus.YPZXSGLY.getCode());
					newOrder.setApproval(ApprovalNewState.TPTG.getCode());
					pushJSZJidAndName(aids, str);
				} else {
					newOrder.setProcessStatus(ProcessStatus.YPTPSH.getCode());
					if (Objects.equals(tOrderNew.getApproval(), ApprovalNewState.TPDSH.getCode())){
						aids.add(order.getApprovalAid());
						str.append(order.getApprovalName()).append(",");
					}else {
						if (Objects.equals(tOrderNew.getApproval(), ApprovalNewState.DSZBH.getCode())) {
							List<Admin> admins = adminMapper.selectAdminByRoleType(AFTConstants.APPROVAL_DECISION);
							for (Admin admin : admins) {
								aids.add(admin.getId());
								str.append(admin.getName()).append(",");
							}

						}
					}
				}
				newOrder.setExamineName(str.substring(0,str.length()-1));
				torderNewMapper.update(newOrder);
			}
		} else if (Objects.equals(useDep.getOperationGuaranteeId(),in.getOperationGuaranteeId())) {
			List<String> strings = torderNewMapper.selectByDepAndProcess(useDep.getId(), ProcessStatus.YYBZSH.getCode());
			Admin admin = adminMapper.selectById(in.getOperationGuaranteeId());
			for (String s : strings) {
				TOrderNew newOrder = new TOrderNew();
				newOrder.setOrderNo(s);
				newOrder.setExamineName(admin.getName());
				torderNewMapper.update(newOrder);
			}
		}
		//关掉特批审核
		if (in.getApproval()==0&&useDep.getApproval()==1){
			List<String> strings = torderNewMapper.selectByDepAndProcess(useDep.getId(), ProcessStatus.YPTPSH.getCode());
			for (String s : strings) {
				TOrderNew tOrderNew = torderNewMapper.queryById(s);
				if (Objects.equals(tOrderNew.getApproval(), ApprovalNewState.TPDSH.getCode())){
					TOrderNew newOrder=new TOrderNew();
					List<Admin> admins = adminMapper.selectAdminByRoleType(AFTConstants.TECH_ADMIN);
					StringBuilder str = new StringBuilder();
					for (Admin admin : admins) {
						str.append(admin.getName()).append(",");
					}
					newOrder.setExamineName(str.substring(0,str.length()-1));
					newOrder.setOrderNo(s);
					newOrder.setApproval(ApprovalNewState.TPTG.getCode());
					newOrder.setProcessStatus(ProcessStatus.YPZXSGLY.getCode());
					torderNewMapper.update(newOrder);
					addOrderLog(s,OrderLogProcess.TP.getCode(),"特批审核关闭，系统自动通过");
				}
			}
		} else if (in.getApprovalAid().equals(useDep.getApprovalAid())) {
			List<String> strings = torderNewMapper.selectByDepAndProcess(useDep.getId(), ProcessStatus.YPTPSH.getCode());
			for (String s : strings) {
				TOrderNew tOrderNew = torderNewMapper.queryById(s);
				if (Objects.equals(tOrderNew.getApproval(), ApprovalNewState.TPDSH.getCode())){
					TOrderNewBo order = torderNewMapper.getSaleIdByOno(s);
					TOrderNew newOrder=new TOrderNew();
					newOrder.setOrderNo(s);
					newOrder.setExamineName(order.getApprovalName());
					torderNewMapper.update(newOrder);
				}
			}

		}
		//切换财务审核与财务复审
		if (in.getExpenseFinanceId()!=null&&!in.getExpenseFinanceId().equals(useDep.getExpenseFinanceId())){
			//如果新的财务审核人与旧财务审核人不一致，切换审核人
			dep.setExpenseFinanceId(in.getExpenseFinanceId());
			adminMapper.updateDepExpenseFinance(in.getId(),in.getExpenseFinanceId());
		}
		if (updateFinance){
			aids.add(in.getFinanceId());
			if(!aids.contains(useDep.getFinanceId())){
				aids.add(useDep.getFinanceId());
			}
			torderMidMapper.updateFinanceId(in.getId(), in.getFinanceId());
			newOrderChangeMapper.updateExamineById(in.getFinanceId(), OrderChangeProcess.CWZY.getCode());
		}
		if(updateRetrialFinance){
			if (!aids.contains(in.getRetrialFinanceId())){
				aids.add(in.getRetrialFinanceId());
			}
			if(!aids.contains(useDep.getRetrialFinanceId())){
				aids.add(useDep.getRetrialFinanceId());
			}
		}
		//
		checkFinaceUpdate(aids);
		if (in.getExpenseRetrialFinanceExamine()!=null){
			dep.setExpenseRetrialFinanceExamine(in.getExpenseRetrialFinanceExamine());
		}
		if (in.getCeoExamine()!=null){
			dep.setCeoExamine(in.getCeoExamine());
		}
		if (in.getCfoExamine()!=null){
			 dep.setCfoExamine(in.getCfoExamine());
		}
		if (in.getViceCeoExamine()!=null){
			dep.setViceCeoExamine(in.getViceCeoExamine());
		}
		if (in.getCashierExamine()!=null){
			dep.setCashierExamine(in.getCashierExamine());
		}
	}

	/**
	 * 推送财务/财务复审/技术总监审核下个流程
	 * @param in 部门信息
	 * @param s 订单编号
	 * @param aids 统计需要刷新的财务
	 * @param type 0 技术总监 1财务复审
	 */
	private void pushCW_JSZJ_Examine(InputDep in, String s, List<String> aids, Integer type) {
		List<TOrderExamine> tOrderExamines = torderExamineMapper.selectByOrderNo(s, 0);
		int i = 0;
		for (TOrderExamine e : tOrderExamines) {
			if (e.getStatus() == 1) i++;
		}
		if (i == tOrderExamines.size()) {
			//推送订单流程
			addOrderLog(s,OrderLogProcess.XMZJSH.getCode(),type==0?"部门修改技术总监为空，系统自动通过":"部门修改财务复审为空，系统自动通过");
			StringBuilder str = new StringBuilder();
			TOrderNew tOrderNew = torderNewMapper.queryById(s);
			TOrderNewBo order = torderNewMapper.getSaleIdByOno(s);
			TOrderNew newOrder = new TOrderNew();
			newOrder.setOrderNo(s);

			//如果订单是特批
			if (tOrderNew.getApproval() == ApprovalNewState.TPDSH.getCode() || tOrderNew.getApproval() == ApprovalNewState.TPBH.getCode()) {
				if (StringUtils.isNotEmpty(in.getOperationGuaranteeId())) {
					newOrder.setProcessStatus(ProcessStatus.YYBZSH.getCode());
					str.append(order.getOperationGuaranteeName()).append(",");
					aids.add(order.getOperationGuaranteeId());
				} else if (order.getApprovalStatus() == 0) {
					addOrderLog(s,OrderLogProcess.YYBZSHTG.getCode(),"运营保障审核人未设置，系统自动通过");
					addOrderLog(s,OrderLogProcess.TP.getCode(),"部门特批审核未设置，系统自动通过");
					newOrder.setProcessStatus(ProcessStatus.YPZXSGLY.getCode());
					newOrder.setApproval(ApprovalNewState.TPTG.getCode());
					pushJSZJidAndName(aids, str);
				} else {
					addOrderLog(s,OrderLogProcess.YYBZSHTG.getCode(),"运营保障审核人未设置，系统自动通过");
					newOrder.setProcessStatus(ProcessStatus.YPTPSH.getCode());
					if (Objects.equals(tOrderNew.getApproval(), ApprovalNewState.TPDSH.getCode())){
						aids.add(order.getApprovalAid());
						str.append(order.getApprovalName()).append(",");
					}else {
						if (Objects.equals(tOrderNew.getApproval(), ApprovalNewState.DSZBH.getCode())) {
							List<Admin> admins = adminMapper.selectAdminByRoleType(AFTConstants.APPROVAL_DECISION);
							for (Admin admin : admins) {
								aids.add(admin.getId());
								str.append(admin.getName()).append(",");
							}
						}
					}
				}
			}else {
				newOrder.setProcessStatus(ProcessStatus.YPZXSGLY.getCode());
				newOrder.setApproval(ApprovalNewState.TPTG.getCode());
				pushJSZJidAndName(aids, str);
			}
			newOrder.setExamineName(str.substring(0,str.length()-1));
			torderNewMapper.update(newOrder);
		}

	}

	private void pushJSZJidAndName(List<String> aids, StringBuilder str) {
		List<Admin> admins = adminMapper.selectAdminByRoleType(AFTConstants.TECH_ADMIN);
		for (Admin admin : admins) {
			aids.add(admin.getId());
			str.append(admin.getName()).append(",");
		}
	}

	/**
	 * 添加审核人 财务专员，财务复审，技术总监审核
	 * @param useDep 部门
	 * @param aid  人员编号
	 * @param list 需要刷新审核人的订单
	 */
	private void addExamine(Department useDep, String aid,List<String> list) {
		List<String> strings = torderNewMapper.selectByDepAndProcess(useDep.getId(), ProcessStatus.YPCW_JSZJ.getCode());
		Admin admin = adminMapper.selectById(aid);
		if (!strings.isEmpty()){
			for (String s : strings) {
				torderExamineMapper.insertSelective(new TOrderExamine(s,0,admin.getId(),admin.getName()));
				if(!list.contains(s)){
					list.add(s);
				}
			}
		}
	}

	private void addOrderLog(String orderNo, Integer process, String remarks) {
		TOrderLog tl=new TOrderLog();
		tl.setAid(AFTConstants.SUPERADMIN_ID);
		tl.setProcess(process);
		tl.setOrderNo(orderNo);
		tl.setRemarks(remarks);
		tOrderLogMapper.insertSelective(tl);
	}

	/**
	 * 如果更换了负责人刷新中间表
	 */
	private void checkFinaceUpdate(List<String> aids) {
		if (!aids.isEmpty()){
			asyncUtils.financeCoutSwitch(aids);
		}
	}

	@Override
	public boolean checkDepNo(String depNo,Integer type) {
		String useDepNo=departmentMapper.selectIdByDepNo(depNo);
		if (StringUtils.isNotBlank(useDepNo)){
			if (type==1){
				if (!depNo.equals(useDepNo)){
					return false;
				}else {
					return true;
				}
			}else {
				return true;
			}

		}
		return false;
	}

	private String countDepNo(String sdepNo, Integer count) {
		String dep=null;
		if(count<10){
			dep=sdepNo+"0"+count;
			String sid=departmentMapper.selectIdByDepNo(dep);
			while(sid!=null){
				count=(count+1)%100;
				if(count>=10){
					dep=sdepNo+count;
				}else{
					dep=sdepNo+"0"+count;
				}
				sid=departmentMapper.selectIdByDepNo(dep);
			}
		}else if(count>=10){
			dep=sdepNo+count;
			String sid=departmentMapper.selectIdByDepNo(dep);
			while(sid!=null){
				count=(count+1)%100;
				dep=sdepNo+count;
				sid=departmentMapper.selectIdByDepNo(dep);
			}
		}
		return dep;
	}

	private void updateLowerLevelNo(String id,String depNo,Integer lvl) {
		List<OrganizationListOut> Nos =departmentMapper.selectIDNBySuperId(id);
		int i=1;
		for (OrganizationListOut o : Nos) {
			o.setLvl(lvl+1);
			if(i<10){
				String dep=depNo+"0"+i;
				if(i>=10){
					dep=depNo+i;
				}else{
					dep=depNo+"0"+i;
				}
				o.setDepNo(dep);
			} else if(i>=10){
				String dep=depNo+i;
				dep=depNo+i;
				o.setDepNo(dep);
			}
			departmentMapper.updateByNumber(o);
			updateLowerLevelNo(o.getId(),o.getDepNo(),o.getLvl());
			i++;
		}
	}

}
