package com.prolog.rdc.tms.service.basicConfigure.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.prolog.common.util.DateUtils;
import com.prolog.common.util.ToolKits;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Order;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.framework.dao.util.PageUtils;
import com.prolog.product.core.framework.entity.UserEntity;
import com.prolog.product.core.framework.util.PlgFxUsrUtils;
import com.prolog.rdc.tms.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.constant.SeriaNnumberConstant;
import com.prolog.rdc.tms.dao.mapper.TmsApprovalBusinessMapper;
import com.prolog.rdc.tms.dao.mapper.TmsApprovalConditionMapper;
import com.prolog.rdc.tms.dao.mapper.TmsApprovalHeaderMapper;
import com.prolog.rdc.tms.dao.mapper.TmsApprovalNdApproveMapper;
import com.prolog.rdc.tms.dao.mapper.TmsApprovalNodeMapper;
import com.prolog.rdc.tms.model.dto.basicConfigure.ApprovalConditionViewDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.ApprovalNodeDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.ApprovalNodeQueryDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.ApprovalViewDTO;
import com.prolog.rdc.tms.model.entity.line.TmsApprovalBusinessModel;
import com.prolog.rdc.tms.model.entity.line.TmsApprovalCndModel;
import com.prolog.rdc.tms.model.entity.line.TmsApprovalHeaderModel;
import com.prolog.rdc.tms.model.entity.line.TmsApprovalNdApproverModel;
import com.prolog.rdc.tms.model.entity.line.TmsApprovalNodeModel;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalAddVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalConditionAddVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalConditionUpdateVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalNodeDeleteVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalNodeRoleQueryVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalNodeRoleVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalNodeUserQueryVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalNodeUserVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalNodeVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalUpdateVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ApprovalViewVO;
import com.prolog.rdc.tms.rmi.feign.MaindataFeign;
import com.prolog.rdc.tms.service.SysCodeengineService;
import com.prolog.rdc.tms.service.SysRefdatadService;
import com.prolog.rdc.tms.service.basicConfigure.ApprovalService;
import com.prolog.rdc.tms.util.PublicMethods;

import cn.hutool.core.date.DateUtil;

/**
 * 审批配置实现层
 *
 * @author :lhb
 * @version :1.0.0
 * @className :ApprovalServiceImpl
 * @creationTime :2022/04/29
 * @description :
 * @modifier :
 * @modifyTime :
 * @reviseRemarks:
 */
@Service
public class ApprovalServiceImpl implements ApprovalService {

	@Autowired
	private TmsApprovalHeaderMapper tmsApprovalHeaderMapper;

	@Autowired
	private TmsApprovalNdApproveMapper tmsApprovalNdApproveMapper;

	@Autowired
	private TmsApprovalNodeMapper tmsApprovalNodeMapper;

	@Autowired
	private TmsApprovalBusinessMapper tmsApprovalBussinessMapper;

	@Autowired
	private SysRefdatadService sysRefdatadService;

	@Autowired
	private SysCodeengineService sysCodeengineService;

	@Autowired
	private MaindataFeign maindataTmsResource;

	@Autowired
	private TmsApprovalConditionMapper tmsApprovalConditionMapper;

	/**
	 * 审批配置查询
	 *
	 * @param approvalViewVO
	 * @return
	 */
	@SuppressWarnings("resource")
	public Page<ApprovalViewDTO> query(ApprovalViewVO approvalViewVO) {

		ToolKits.isParamNull(approvalViewVO, "审批配置查看查询请求不为空");
		ToolKits.isParamNull(approvalViewVO.getPageNum(), "页码不为空");
		ToolKits.isParamNull(approvalViewVO.getPageSize(), "页码数量不为空");

		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		// 响应集合
		List<ApprovalViewDTO> approvalViewDTOs = new ArrayList<>();

		// 审批流程类型名称
		List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.APPROVAL_FLOW_TYPE, null, null, null);
		// 审批流程状态名称
		List<Map<String, Object>> restMessage2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.APPROVAL_STATUS, null, null, null);

		Criteria criteria = Criteria.forClass(TmsApprovalHeaderModel.class);
		Restriction r2 = ToolKits.isEmpty(approvalViewVO.getApprovalFlowTypeName()) ? null : Restrictions.like("approvalFlowTypeName", "%" + approvalViewVO.getApprovalFlowTypeName() + "%");
		Restriction r3 = ToolKits.isEmpty(approvalViewVO.getStatus()) ? null : Restrictions.eq("status", approvalViewVO.getStatus());
		Restriction r4 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		criteria.setRestriction(Restrictions.and(r2, r3, r4));
		criteria.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));
		PageUtils.startPage(approvalViewVO.getPageNum(), approvalViewVO.getPageSize());
		List<TmsApprovalHeaderModel> tmsApprovalHeaderModels = tmsApprovalHeaderMapper.findByCriteria(criteria);
		for (TmsApprovalHeaderModel tmsApprovalHeaderModel : tmsApprovalHeaderModels) {
			ApprovalViewDTO approvalViewDTO = new ApprovalViewDTO();
			BeanUtils.copyProperties(tmsApprovalHeaderModel, approvalViewDTO);
			approvalViewDTO.setStatusName(PublicMethods.change(restMessage2, String.valueOf(tmsApprovalHeaderModel.getStatus())));
			approvalViewDTO.setApprovalFlowTypeName(PublicMethods.change(restMessage1, String.valueOf(tmsApprovalHeaderModel.getApprovalFlowType())));

			// 审批流程条件类型
			List<Map<String, Object>> restMsgStyConditionType = sysRefdatadService.getDropDownById(DataDictionaryConstant.APPROVAL_CONDITION_TYPE, null, null, null);
			// 配送方式
			List<Map<String, Object>> restMsgDeliveryMethodType = sysRefdatadService.getDropDownById(DataDictionaryConstant.DELIVERY_METHOD_TYPE, null, null, null);
			// 订单类型
			List<Map<String, Object>> restMsgOrderType = sysRefdatadService.getDropDownById(DataDictionaryConstant.ORDER_TYPE, null, null, null);
			// 订单业务类型
			List<Map<String, Object>> restMsgOrderBusinessType = sysRefdatadService.getDropDownById(DataDictionaryConstant.ORDER_BUSINESS_TYPE, null, null, null);
			// 运输类型(运输模式)
			List<Map<String, Object>> restMsgTransportType = sysRefdatadService.getDropDownById(DataDictionaryConstant.TRANSPORT_TYPE, null, null, null);
			// 收货方类型
			List<Map<String, Object>> restMsgConsigneeType = sysRefdatadService.getDropDownById(DataDictionaryConstant.CONSIGNEE_TYPE, null, null, null);
			// 发货方类型
			List<Map<String, Object>> restMsgShipperType = sysRefdatadService.getDropDownById(DataDictionaryConstant.SHIPPER_TYPE, null, null, null);
			// 温度要求
			List<Map<String, Object>> restMsgTemperature = sysRefdatadService.getDropDownById(DataDictionaryConstant.TEMPERATURE_REQUIREMENT, null, null, null);

			// 满足条件
			Criteria ctCriteria = Criteria.forClass(TmsApprovalCndModel.class);
			Restriction r5 = Restrictions.eq(TmsApprovalCndModel::getApprovalId, tmsApprovalHeaderModel.getApprovalId());
			Restriction r6 = Restrictions.eq(TmsApprovalCndModel::getEnterpriseId, user.getEnterpriseId());
			ctCriteria.setRestriction(Restrictions.and(r5, r6));
			List<TmsApprovalCndModel> approvalCndModels = tmsApprovalConditionMapper.findByCriteria(ctCriteria);

			List<String> conditions = Lists.newArrayList();
			for (TmsApprovalCndModel ctModel : approvalCndModels) {
				conditions.add(PublicMethods.change(restMsgStyConditionType, String.valueOf(ctModel.getApprovalConditionType())));
				// 满足条件
				switch (ctModel.getApprovalConditionType().intValue()) {
				case 1:
					// 1配送方式
					conditions.add(PublicMethods.change(restMsgDeliveryMethodType, String.valueOf(ctModel.getApprovalConditionValue())));
					break;
				case 2:
					// 2发货方类型
					conditions.add(PublicMethods.change(restMsgShipperType, String.valueOf(ctModel.getApprovalConditionValue())));
					break;
				case 3:
					// 3收货方类型
					conditions.add(PublicMethods.change(restMsgConsigneeType, String.valueOf(ctModel.getApprovalConditionValue())));
					break;
				case 4:
					// 4订单类型
					conditions.add(PublicMethods.change(restMsgOrderType, String.valueOf(ctModel.getApprovalConditionValue())));
					break;
				case 5:
					// 5订单业务类型
					conditions.add(PublicMethods.change(restMsgOrderBusinessType, String.valueOf(ctModel.getApprovalConditionValue())));
					break;
				case 6:
					// 6运输模式
					conditions.add(PublicMethods.change(restMsgTransportType, String.valueOf(ctModel.getApprovalConditionValue())));
					break;
				case 7:
					// 7温度要求
					conditions.add(PublicMethods.change(restMsgTemperature, String.valueOf(ctModel.getApprovalConditionValue())));
					break;
				}
			}
			approvalViewDTO.setApprovalConditions(conditions.stream().collect(Collectors.joining(",")));

			approvalViewDTOs.add(approvalViewDTO);
		}

		Page<ApprovalViewDTO> page = PageUtils.getPage(approvalViewDTOs);
		if (tmsApprovalHeaderModels instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<TmsApprovalHeaderModel> p0 = (com.github.pagehelper.Page<TmsApprovalHeaderModel>) tmsApprovalHeaderModels;
			page.setPageCount(p0.getPages());
			page.setPageNum(p0.getPageNum());
			page.setPageSize(p0.getPageSize());
			page.setTotalCount(p0.getTotal());
			page.setStartRow(p0.getStartRow());
			page.setEndRow(p0.getEndRow());
		}
		return page;
	}

	/**
	 * 审批配置新增
	 *
	 * @param approvalAddVO
	 * @return
	 */
	public void add(ApprovalAddVO approvalAddVO) {
		ToolKits.isParamNull(approvalAddVO.getApprovalName(), "审批流程名称不为空");
		ToolKits.isParamNull(approvalAddVO.getApprovalFlowType(), "审批流程类型不为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "没有操作权限！");

		Criteria headerCriteria = Criteria.forClass(TmsApprovalHeaderModel.class);
		Restriction r1 = Restrictions.eq(TmsApprovalHeaderModel::getEnterpriseId, user.getEnterpriseId());
		Restriction r2 = Restrictions.eq(TmsApprovalHeaderModel::getStatus, DataDictionaryConstant.APPROVAL_STATUS_ENABLE);
		Restriction r6 = Restrictions.eq("approvalFlowType", approvalAddVO.getApprovalFlowType());
		headerCriteria.setRestriction(Restrictions.and(r1, r2, r6));
		List<TmsApprovalHeaderModel> approvalHeaderModels = tmsApprovalHeaderMapper.findByCriteria(headerCriteria);
		if (ToolKits.isNotEmpty(approvalHeaderModels) && approvalHeaderModels.get(0).getApprovalFlowType().equals(DataDictionaryConstant.APPROVAL_FLOW_TYPE_CARRIER)) {
			throw new PrologException("承运商审批流程已经存在");
		}

		// 运单匹配条件集合
		Map<Integer, String> conditionMap = Maps.newHashMap();
		if (ToolKits.isNotEmpty(approvalAddVO.getApprovalConditionAddVOS())) {
			for (ApprovalConditionAddVO conditionVO : approvalAddVO.getApprovalConditionAddVOS()) {
				if (ToolKits.isEmpty(conditionVO.getApprovalConditionType())) {
					continue;
				}
				// 配送方式
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_DELIVERY) {
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_DELIVERY, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_DELIVERY) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()));
					continue;
				}
				// 订单类型
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_ORDER) {
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_ORDER, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_ORDER) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()));
					continue;
				}
				// 订单业务类型
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_ORDER_BUSINESS) {
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_ORDER_BUSINESS, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_ORDER_BUSINESS) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()));
					continue;
				}
				// 运输模式
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_TRANSPORT) {
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_TRANSPORT, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_TRANSPORT) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()));
					continue;
				}
				// 温度要求
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_TEMPERATURE) {
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_TEMPERATURE, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_TEMPERATURE) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()));
					continue;
				}
				// 货主ID
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_OWNER) {
					if (ToolKits.isEmpty(conditionVO.getUnitId())) {
						throw new PrologException("货主不为空");
					}
					String units = Arrays.stream(String.valueOf(conditionVO.getUnitId()).split(",")).sorted().collect(Collectors.joining(","));
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_OWNER, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_OWNER) + "_" + units);
					continue;
				}

				// 部门ID
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_DEPARTMENT) {
					if (ToolKits.isEmpty(conditionVO.getUnitId())) {
						throw new PrologException("部门不为空");
					}
					String units = Arrays.stream(String.valueOf(conditionVO.getUnitId()).split(",")).sorted().collect(Collectors.joining(","));
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_DEPARTMENT, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_DEPARTMENT) + "_" + units);
					continue;
				}
				// 收货方类型
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_CONSIGNEE) {
					if (ToolKits.isEmpty(conditionVO.getUnitId())) {
						throw new PrologException("收货方不为空");
					}
					String units = Arrays.stream(String.valueOf(conditionVO.getUnitId()).split(",")).sorted().collect(Collectors.joining(","));
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_CONSIGNEE, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_CONSIGNEE) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()) + "," + units);
					continue;
				}
				// 发货方类型
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_SHIPPER) {
					if (ToolKits.isEmpty(conditionVO.getUnitId())) {
						throw new PrologException("发货方不为空");
					}
					String units = Arrays.stream(String.valueOf(conditionVO.getUnitId()).split(",")).sorted().collect(Collectors.joining(","));
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_SHIPPER, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_SHIPPER) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()) + "," + units);
					continue;
				}
			}
		}

		for (TmsApprovalHeaderModel approvalHeaderModel : approvalHeaderModels) {
			// 满足条件
			Criteria ctCriteria = Criteria.forClass(TmsApprovalCndModel.class);
			Restriction r3 = Restrictions.eq(TmsApprovalHeaderModel::getApprovalId, approvalHeaderModel.getApprovalId());
			Restriction r4 = Restrictions.eq(TmsApprovalHeaderModel::getEnterpriseId, user.getEnterpriseId());
			ctCriteria.setRestriction(Restrictions.and(r3, r4));
			List<TmsApprovalCndModel> approvalCndModels = tmsApprovalConditionMapper.findByCriteria(ctCriteria);

			// 判定满足条件
			int fitCnt = 0;
			for (TmsApprovalCndModel conditionModel : approvalCndModels) {
				switch (conditionModel.getApprovalConditionType().intValue()) {
				case 2:
				case 3:
					String unit1s = Arrays.stream(String.valueOf(conditionModel.getUnitId()).split(",")).sorted().collect(Collectors.joining(","));
					if (conditionMap.containsValue(String.valueOf(conditionModel.getApprovalConditionType()) + "_" + String.valueOf(conditionModel.getApprovalConditionValue()) + "," + unit1s)) {
						fitCnt++;
					}
					break;
				case 8:
				case 9:
					String unit2s = Arrays.stream(String.valueOf(conditionModel.getUnitId()).split(",")).sorted().collect(Collectors.joining(","));

					if (conditionMap.containsValue(String.valueOf(conditionModel.getApprovalConditionType()) + "_" + unit2s)) {
						fitCnt++;
					}
					break;
				default:
					String unit3s = Arrays.stream(String.valueOf(conditionModel.getApprovalConditionValue()).split(",")).sorted().collect(Collectors.joining(","));

					if (conditionMap.containsValue(String.valueOf(conditionModel.getApprovalConditionType()) + "_" + unit3s)) {
						fitCnt++;
					}
					break;
				}
			}
			// 已经存在相同条件的审批流
			Assert.isTrue(fitCnt != approvalCndModels.size(), "审批流程的条件已经存在，请重新配置审批流程条件!");
		}

		// 当前时间
		Date date = DateUtil.date();

		String id = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_APPROVAL_HEADER_ID, "L");
		ToolKits.isParamNull(id, "获取审批流程ID失败！");

		List<Map<String, Object>> data1 = Lists.newArrayList();

		RestMessage<List<Map<String, Object>>> restMessage1 = maindataTmsResource.getDropDownById(DataDictionaryConstant.APPROVAL_FLOW_TYPE, null, null, null);
		if (!restMessage1.isSuccess()) {
			throw new PrologException("审批流程类型翻译失败!");
		} else {
			data1 = restMessage1.getData();
		}

		TmsApprovalHeaderModel approvalHeaderModel = new TmsApprovalHeaderModel();
		BeanUtils.copyProperties(approvalAddVO, approvalHeaderModel);

		// ID赋值
		approvalHeaderModel.setApprovalId(Long.valueOf(id));

		approvalHeaderModel.setApprovalFlowTypeName(PublicMethods.change(data1, String.valueOf(approvalAddVO.getApprovalFlowType())));
		approvalHeaderModel.setStatus(DataDictionaryConstant.APPROVAL_STATUS_ENABLE);
		approvalHeaderModel.setEnterpriseId(user.getEnterpriseId());
		approvalHeaderModel.setEnterpriseName(user.getEnterpriseName());
		approvalHeaderModel.setCreateperson(user.getNickname());
		approvalHeaderModel.setCreatetime(date);
		// 保存
		tmsApprovalHeaderMapper.save(approvalHeaderModel);

		// 审批流程条件
		if (ToolKits.isNotEmpty(approvalAddVO.getApprovalConditionAddVOS())) {
			for (ApprovalConditionAddVO conditionAddVO : approvalAddVO.getApprovalConditionAddVOS()) {
				if (ToolKits.isEmpty(conditionAddVO.getApprovalConditionType())) {
					continue;
				}
				String cid = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_APPROVAL_HEADER_CT_ID, "L");
				ToolKits.isParamNull(cid, "审批流程条件ID生成失败");
				TmsApprovalCndModel approvalCndModel = new TmsApprovalCndModel();
				BeanUtils.copyProperties(conditionAddVO, approvalCndModel);
				approvalCndModel.setId(Long.valueOf(cid));
				approvalCndModel.setApprovalId(Long.valueOf(id));

				approvalCndModel.setEnterpriseId(user.getEnterpriseId());
				approvalCndModel.setEnterpriseName(user.getEnterpriseName());
				approvalCndModel.setCreateperson(user.getNickname());
				approvalCndModel.setCreatetime(date);
				tmsApprovalConditionMapper.save(approvalCndModel);
			}
		}
	}

	/**
	 * 审批配置启用
	 *
	 * @param approvalIds
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void approvalEnable(List<Long> approvalIds) {
		ToolKits.isParamNull(approvalIds, "审批流程ID不为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "没有操作权限！");

		Date date = DateUtils.nowDate();

		Map<String, Object> mapUpdate = Maps.newHashMap();
		mapUpdate.put("status", DataDictionaryConstant.APPROVAL_STATUS_ENABLE);
		mapUpdate.put("updateperson", user.getNickname());
		mapUpdate.put("updatetime", date);

		for (Long approvalId : approvalIds) {
			// 流程审批表启用
			tmsApprovalHeaderMapper.updateMapById(approvalId, mapUpdate, TmsApprovalHeaderModel.class);

			// 流程审批节点表中该流程对应的所有节点都启用
			tmsApprovalNodeMapper.updateMapById(approvalId, mapUpdate, TmsApprovalNodeModel.class);
		}
	}

	/**
	 * 审批配置停用
	 *
	 * @param approvalIds
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public void approvalDisable(List<Long> approvalIds) {

		ToolKits.isParamNull(approvalIds, "审批流程ID不为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "没有操作权限！");

		Date date = DateUtils.nowDate();

		Map<String, Object> mapUpdate = Maps.newHashMap();
		mapUpdate.put("status", DataDictionaryConstant.APPROVAL_STATUS_DISABLE);
		mapUpdate.put("updateperson", user.getNickname());
		mapUpdate.put("updatetime", date);

		for (Long approvalId : approvalIds) {
			// 流程在使用中的判断
			Criteria criteria = Criteria.forClass(TmsApprovalBusinessModel.class);
			Restriction r1 = Restrictions.eq("approvalId", approvalId);
			Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
			Restriction r3 = Restrictions.lt("status", DataDictionaryConstant.APPROVAL_BUSINESS_STATUS_INVALID);
			criteria.setRestriction(Restrictions.and(r1, r2, r3));
			List<TmsApprovalBusinessModel> tmsApprovalBussinessModels = tmsApprovalBussinessMapper.findByCriteria(criteria);
			Assert.isTrue(tmsApprovalBussinessModels == null || tmsApprovalBussinessModels.size() == 0, "流程【" + approvalId + "】在审核中，请先审核完成");

			// 流程审批表停用
			tmsApprovalHeaderMapper.updateMapById(approvalId, mapUpdate, TmsApprovalHeaderModel.class);

			// 流程审批节点表中该流程对应的所有节点都停用
			tmsApprovalNodeMapper.updateMapById(approvalId, mapUpdate, TmsApprovalNodeModel.class);
		}
	}

	/**
	 * 审批配置删除
	 *
	 * @param approvalIds
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public void approvalDelete(List<Long> approvalIds) {
		ToolKits.isParamNull(approvalIds, "审批流程ID不为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "没有操作权限！");

		for (Long approvalId : approvalIds) {
			// 流程在使用中的判断
			Criteria criteria = Criteria.forClass(TmsApprovalBusinessModel.class);
			Restriction r1 = Restrictions.eq("approvalId", approvalId);
			Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
			Restriction r3 = Restrictions.lt("status", DataDictionaryConstant.APPROVAL_BUSINESS_STATUS_INVALID);

			criteria.setRestriction(Restrictions.and(r1, r2, r3));
			List<TmsApprovalBusinessModel> tmsApprovalBussinessModels = tmsApprovalBussinessMapper.findByCriteria(criteria);
			Assert.isTrue(tmsApprovalBussinessModels == null || tmsApprovalBussinessModels.size() == 0, "流程【" + approvalId + "】在审核中，请先审核完成");

			// 流程审批表删除
			Criteria criteriaHeader = Criteria.forClass(TmsApprovalHeaderModel.class);
			Restriction r6 = Restrictions.eq("approvalId", approvalId);
			Restriction r7 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
			criteriaHeader.setRestriction(Restrictions.and(r6, r7));
			tmsApprovalHeaderMapper.deleteByCriteria(criteriaHeader);

			// 流程审批条件表删除
			Criteria approvalCondition = Criteria.forClass(TmsApprovalCndModel.class);
			Restriction r12 = Restrictions.eq(TmsApprovalCndModel::getApprovalId, approvalId);
			Restriction r13 = Restrictions.eq(TmsApprovalCndModel::getEnterpriseId, user.getEnterpriseId());
			approvalCondition.setRestriction(Restrictions.and(r12, r13));
			tmsApprovalConditionMapper.deleteByCriteria(approvalCondition);

			// 流程审批节点表中该流程对应的所有节点都删除
			Criteria criteriaNode = Criteria.forClass(TmsApprovalNodeModel.class);
			Restriction r8 = Restrictions.eq("approvalId", approvalId);
			Restriction r9 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
			criteriaNode.setRestriction(Restrictions.and(r8, r9));
			tmsApprovalNodeMapper.deleteByCriteria(criteriaNode);

			// 节审批流程点审批者表中该流程对应的所有审批者都删除
			Criteria criteriaNodeApprover = Criteria.forClass(TmsApprovalNdApproverModel.class);
			Restriction r10 = Restrictions.eq("approvalId", approvalId);
			Restriction r11 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
			criteriaNodeApprover.setRestriction(Restrictions.and(r10, r11));
			tmsApprovalNodeMapper.deleteByCriteria(criteriaNodeApprover);
		}
	}

	/**
	 * 审批配置修改
	 *
	 * @param approvalUpdateVO
	 * @return
	 */
	public void approvalUpdate(ApprovalUpdateVO approvalUpdateVO) {
		ToolKits.isParamNull(approvalUpdateVO, "审批流程不为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "没有操作权限！");

		// 运单匹配条件集合
		Map<Integer, String> conditionMap = Maps.newHashMap();
		if (ToolKits.isNotEmpty(approvalUpdateVO.getApprovalConditionUpdateVOS())) {
			for (ApprovalConditionUpdateVO conditionVO : approvalUpdateVO.getApprovalConditionUpdateVOS()) {
				if (ToolKits.isEmpty(conditionVO.getApprovalConditionType())) {
					continue;
				}
				// 配送方式
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_DELIVERY) {
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_DELIVERY, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_DELIVERY) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()));
					continue;
				}
				// 订单类型
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_ORDER) {
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_ORDER, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_ORDER) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()));
					continue;
				}
				// 订单业务类型
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_ORDER_BUSINESS) {
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_ORDER_BUSINESS, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_ORDER_BUSINESS) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()));
					continue;
				}
				// 运输模式
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_TRANSPORT) {
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_TRANSPORT, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_TRANSPORT) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()));
					continue;
				}
				// 温度要求
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_TEMPERATURE) {
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_TEMPERATURE, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_TEMPERATURE) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()));
					continue;
				}
				// 货主ID
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_OWNER) {
					if (ToolKits.isEmpty(conditionVO.getUnitId())) {
						throw new PrologException("货主不为空");
					}
					String units = Arrays.stream(String.valueOf(conditionVO.getUnitId()).split(",")).sorted().collect(Collectors.joining(","));
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_OWNER, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_OWNER) + "_" + units);
					continue;
				}

				// 部门ID
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_DEPARTMENT) {
					if (ToolKits.isEmpty(conditionVO.getUnitId())) {
						throw new PrologException("部门不为空");
					}
					String units = Arrays.stream(String.valueOf(conditionVO.getUnitId()).split(",")).sorted().collect(Collectors.joining(","));
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_DEPARTMENT, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_DEPARTMENT) + "_" + units);
					continue;
				}
				// 收货方类型
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_CONSIGNEE) {
					if (ToolKits.isEmpty(conditionVO.getUnitId())) {
						throw new PrologException("收货方不为空");
					}
					String units = Arrays.stream(String.valueOf(conditionVO.getUnitId()).split(",")).sorted().collect(Collectors.joining(","));
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_CONSIGNEE, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_CONSIGNEE) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()) + "," + units);
					continue;
				}
				// 发货方类型
				if (conditionVO.getApprovalConditionType() == DataDictionaryConstant.APPROVAL_CONDITION_TYPE_SHIPPER) {
					if (ToolKits.isEmpty(conditionVO.getUnitId())) {
						throw new PrologException("发货方不为空");
					}
					String units = Arrays.stream(String.valueOf(conditionVO.getUnitId()).split(",")).sorted().collect(Collectors.joining(","));
					conditionMap.put(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_SHIPPER, String.valueOf(DataDictionaryConstant.APPROVAL_CONDITION_TYPE_SHIPPER) + "_" + String.valueOf(conditionVO.getApprovalConditionValue()) + "," + units);
					continue;
				}
			}
		}

		Criteria headerCriteria = Criteria.forClass(TmsApprovalHeaderModel.class);
		Restriction r1 = Restrictions.eq(TmsApprovalHeaderModel::getEnterpriseId, user.getEnterpriseId());
		Restriction r2 = Restrictions.eq(TmsApprovalHeaderModel::getStatus, DataDictionaryConstant.APPROVAL_STATUS_ENABLE);
		Restriction r3 = Restrictions.ne(TmsApprovalHeaderModel::getApprovalId, approvalUpdateVO.getApprovalId());
		Restriction r6 = Restrictions.eq("approvalFlowType", approvalUpdateVO.getApprovalFlowType());
		headerCriteria.setRestriction(Restrictions.and(r1, r2, r3, r6));
		List<TmsApprovalHeaderModel> approvalHeaderModels = tmsApprovalHeaderMapper.findByCriteria(headerCriteria);

		for (TmsApprovalHeaderModel approvalHeaderModel : approvalHeaderModels) {
			// 满足条件
			Criteria ctCriteria = Criteria.forClass(TmsApprovalCndModel.class);
			Restriction r4 = Restrictions.eq(TmsApprovalCndModel::getApprovalId, approvalHeaderModel.getApprovalId());
			Restriction r5 = Restrictions.eq(TmsApprovalCndModel::getEnterpriseId, user.getEnterpriseId());
			ctCriteria.setRestriction(Restrictions.and(r4, r5));
			List<TmsApprovalCndModel> approvalCndModels = tmsApprovalConditionMapper.findByCriteria(ctCriteria);

			// 判定满足条件
			int fitCnt = 0;
			for (TmsApprovalCndModel conditionModel : approvalCndModels) {
				switch (conditionModel.getApprovalConditionType().intValue()) {
				case 2:
				case 3:
					String unit1s = Arrays.stream(String.valueOf(conditionModel.getUnitId()).split(",")).sorted().collect(Collectors.joining(","));
					if (conditionMap.containsValue(String.valueOf(conditionModel.getApprovalConditionType()) + "_" + String.valueOf(conditionModel.getApprovalConditionValue()) + "," + unit1s)) {
						fitCnt++;
					}
					break;
				case 8:
				case 9:
					String unit2s = Arrays.stream(String.valueOf(conditionModel.getUnitId()).split(",")).sorted().collect(Collectors.joining(","));

					if (conditionMap.containsValue(String.valueOf(conditionModel.getApprovalConditionType()) + "_" + unit2s)) {
						fitCnt++;
					}
					break;
				default:
					String unit3s = Arrays.stream(String.valueOf(conditionModel.getApprovalConditionValue()).split(",")).sorted().collect(Collectors.joining(","));

					if (conditionMap.containsValue(String.valueOf(conditionModel.getApprovalConditionType()) + "_" + unit3s)) {
						fitCnt++;
					}
					break;
				}
			}
			// 已经存在相同条件的审批流程
			Assert.isTrue(fitCnt != approvalCndModels.size(), "审批流程的条件已经存在，请重新配置审批流程条件!");
		}
		// 当前时间
		Date date = DateUtil.date();

		Map<String, Object> mapUpdateApprovalHeaderModel = Maps.newHashMap();
		mapUpdateApprovalHeaderModel.put("status", DataDictionaryConstant.APPROVAL_STATUS_ENABLE);
		mapUpdateApprovalHeaderModel.put("memo", approvalUpdateVO.getMemo());
		mapUpdateApprovalHeaderModel.put("updateperson", user.getNickname());
		mapUpdateApprovalHeaderModel.put("updatetime", date);

		// 修改
		tmsApprovalHeaderMapper.updateMapById(approvalUpdateVO.getApprovalId(), mapUpdateApprovalHeaderModel, TmsApprovalHeaderModel.class);

		// 删除条件
		Criteria approvalConditionCriteria = Criteria.forClass(TmsApprovalCndModel.class);
		Restriction r7 = Restrictions.eq(TmsApprovalCndModel::getApprovalId, approvalUpdateVO.getApprovalId());
		approvalConditionCriteria.setRestriction(Restrictions.and(r7));
		tmsApprovalConditionMapper.deleteByCriteria(approvalConditionCriteria);

		// 审批流程条件修改
		if (ToolKits.isNotEmpty(approvalUpdateVO.getApprovalConditionUpdateVOS())) {
			for (ApprovalConditionUpdateVO approvalConditionUpdateVO : approvalUpdateVO.getApprovalConditionUpdateVOS()) {
				if (ToolKits.isEmpty(approvalConditionUpdateVO.getApprovalConditionType())) {
					continue;
				}
				String cid = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_APPROVAL_HEADER_CT_ID, "L");
				ToolKits.isParamNull(cid, "审批流程条件ID生成失败");
				TmsApprovalCndModel conditiontModel = new TmsApprovalCndModel();
				BeanUtils.copyProperties(approvalConditionUpdateVO, conditiontModel);
				conditiontModel.setId(Long.valueOf(cid));
				conditiontModel.setApprovalId(Long.valueOf(approvalUpdateVO.getApprovalId()));

				conditiontModel.setEnterpriseId(user.getEnterpriseId());
				conditiontModel.setEnterpriseName(user.getEnterpriseName());
				conditiontModel.setCreateperson(user.getNickname());
				conditiontModel.setCreatetime(date);
				tmsApprovalConditionMapper.save(conditiontModel);
			}
		}
	}

	/**
	 * 审批配置查看
	 *
	 * @param approvalId
	 * @return
	 */
	public ApprovalViewDTO approvalView(String approvalId) {
		ToolKits.isParamNull(approvalId, "审批流程ID不为空");
		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		// 响应集合
		ApprovalViewDTO approvalViewDTO = new ApprovalViewDTO();
		// 审批流程类型名称
		List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.APPROVAL_FLOW_TYPE, null, null, null);
		List<Map<String, Object>> restMessage2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.APPROVAL_STATUS, null, null, null);

		TmsApprovalHeaderModel model = tmsApprovalHeaderMapper.findById(approvalId, TmsApprovalHeaderModel.class);
		BeanUtils.copyProperties(model, approvalViewDTO);

		approvalViewDTO.setApprovalFlowTypeName(PublicMethods.change(restMessage1, String.valueOf(model.getApprovalFlowType())));
		approvalViewDTO.setStatusName(PublicMethods.change(restMessage2, String.valueOf(model.getStatus())));

		// 审批流程条件类型
		List<Map<String, Object>> restMsgStyConditionType = sysRefdatadService.getDropDownById(DataDictionaryConstant.APPROVAL_CONDITION_TYPE, null, null, null);
		// 配送方式
		List<Map<String, Object>> restMsgDeliveryMethodType = sysRefdatadService.getDropDownById(DataDictionaryConstant.DELIVERY_METHOD_TYPE, null, null, null);
		// 订单类型
		List<Map<String, Object>> restMsgOrderType = sysRefdatadService.getDropDownById(DataDictionaryConstant.ORDER_TYPE, null, null, null);
		// 订单业务类型
		List<Map<String, Object>> restMsgOrderBusinessType = sysRefdatadService.getDropDownById(DataDictionaryConstant.ORDER_BUSINESS_TYPE, null, null, null);
		// 运输类型(运输模式)
		List<Map<String, Object>> restMsgTransportType = sysRefdatadService.getDropDownById(DataDictionaryConstant.TRANSPORT_TYPE, null, null, null);
		// 收货方类型
		List<Map<String, Object>> restMsgConsigneeType = sysRefdatadService.getDropDownById(DataDictionaryConstant.CONSIGNEE_TYPE, null, null, null);
		// 发货方类型
		List<Map<String, Object>> restMsgShipperType = sysRefdatadService.getDropDownById(DataDictionaryConstant.SHIPPER_TYPE, null, null, null);
		// 温度要求
		List<Map<String, Object>> restMsgTemperature = sysRefdatadService.getDropDownById(DataDictionaryConstant.TEMPERATURE_REQUIREMENT, null, null, null);

		// 满足条件
		Criteria ctCriteria = Criteria.forClass(TmsApprovalCndModel.class);
		Restriction r1 = Restrictions.eq(TmsApprovalCndModel::getApprovalId, Long.valueOf(approvalId));
		Restriction r2 = Restrictions.eq(TmsApprovalCndModel::getEnterpriseId, user.getEnterpriseId());
		ctCriteria.setRestriction(Restrictions.and(r1, r2));
		List<TmsApprovalCndModel> approvalCndModels = tmsApprovalConditionMapper.findByCriteria(ctCriteria);

		List<ApprovalConditionViewDTO> ctViewDTOS = Lists.newArrayList();
		for (TmsApprovalCndModel ctModel : approvalCndModels) {
			ApprovalConditionViewDTO ctViewDTO = new ApprovalConditionViewDTO();
			BeanUtils.copyProperties(ctModel, ctViewDTO);
			ctViewDTO.setApprovalConditionTypeName(PublicMethods.change(restMsgStyConditionType, String.valueOf(ctModel.getApprovalConditionType())));

			// 满足条件
			switch (ctModel.getApprovalConditionType().intValue()) {
			case 1:
				// 1配送方式
				ctViewDTO.setApprovalConditionValueName(PublicMethods.change(restMsgDeliveryMethodType, String.valueOf(ctModel.getApprovalConditionValue())));
				break;
			case 2:
				// 2发货方类型
				ctViewDTO.setApprovalConditionValueName(PublicMethods.change(restMsgShipperType, String.valueOf(ctModel.getApprovalConditionValue())));
				break;
			case 3:
				// 3收货方类型
				ctViewDTO.setApprovalConditionValueName(PublicMethods.change(restMsgConsigneeType, String.valueOf(ctModel.getApprovalConditionValue())));
				break;
			case 4:
				// 4订单类型
				ctViewDTO.setApprovalConditionValueName(PublicMethods.change(restMsgOrderType, String.valueOf(ctModel.getApprovalConditionValue())));
				break;
			case 5:
				// 5订单业务类型
				ctViewDTO.setApprovalConditionValueName(PublicMethods.change(restMsgOrderBusinessType, String.valueOf(ctModel.getApprovalConditionValue())));
				break;
			case 6:
				// 6运输模式
				ctViewDTO.setApprovalConditionValueName(PublicMethods.change(restMsgTransportType, String.valueOf(ctModel.getApprovalConditionValue())));
				break;
			case 7:
				// 7温度要求
				ctViewDTO.setApprovalConditionValueName(PublicMethods.change(restMsgTemperature, String.valueOf(ctModel.getApprovalConditionValue())));
				break;
			}
			ctViewDTOS.add(ctViewDTO);
		}
		approvalViewDTO.setApprovalConditionViewDTOS(ctViewDTOS);

		return approvalViewDTO;
	}

	/**
	 * 审批流程节点配置
	 *
	 * @param approvalNodeVOs
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public void approvalNodeConfig(List<ApprovalNodeVO> approvalNodeVOs) {
		ToolKits.isParamNull(approvalNodeVOs, "流程配置节点不为空");
		Assert.isTrue(approvalNodeVOs.size() > 0, "流程配置节点不为空");

		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		Date date = DateUtils.nowDate();

		Criteria criteria = Criteria.forClass(TmsApprovalBusinessModel.class);
		Restriction r1 = Restrictions.eq("approvalId", approvalNodeVOs.get(0).getApprovalId());
		Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		Restriction r3 = Restrictions.lt("status", DataDictionaryConstant.APPROVAL_BUSINESS_STATUS_INVALID);

		criteria.setRestriction(Restrictions.and(r1, r2, r3));
		List<TmsApprovalBusinessModel> tmsApprovalBussinessModels = tmsApprovalBussinessMapper.findByCriteria(criteria);
		Assert.isTrue(tmsApprovalBussinessModels == null || tmsApprovalBussinessModels.size() == 0, "流程【" + approvalNodeVOs.get(0).getApprovalId() + "】在审核中，请先审核完成");

		// 删除流程审批节点表
		Criteria criteriaNode = Criteria.forClass(TmsApprovalNodeModel.class);
		Restriction r4 = Restrictions.eq("approvalId", approvalNodeVOs.get(0).getApprovalId());
		Restriction r5 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		criteriaNode.setRestriction(Restrictions.and(r4, r5));
		tmsApprovalNodeMapper.deleteByCriteria(criteriaNode);

		// 删除节审批流程点审批者表
		Criteria criteriaNodeApprover = Criteria.forClass(TmsApprovalNdApproverModel.class);
		Restriction r6 = Restrictions.eq("approvalId", approvalNodeVOs.get(0).getApprovalId());
		Restriction r7 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		criteriaNodeApprover.setRestriction(Restrictions.and(r6, r7));
		tmsApprovalNdApproveMapper.deleteByCriteria(criteriaNodeApprover);

		for (ApprovalNodeVO vo : approvalNodeVOs) {
			String nodeId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_APPROVAL_NODE_ID, "L");
			ToolKits.isParamNull(nodeId, "获取审批流程节点ID失败！");

			TmsApprovalNodeModel nodeModel = new TmsApprovalNodeModel();
			// 审批节点ID
			nodeModel.setNodeId(Long.valueOf(nodeId));
			// 审批流程ID
			nodeModel.setApprovalId(vo.getApprovalId());
			// 审批节点状态
			nodeModel.setStatus(vo.getStatus());
			// 节点审批者类型
			nodeModel.setNodeApproverType(vo.getNodeApproverType());
			// 审批方式
			nodeModel.setNodeApprovalType(vo.getNodeApprovalType());
			// 审批节点顺序
			nodeModel.setNodeOrder(vo.getNodeOrder());
			// 设置企业
			nodeModel.setEnterpriseId(user.getEnterpriseId());
			nodeModel.setEnterpriseName(user.getEnterpriseName());
			// 设置创建人
			nodeModel.setCreatetime(date);
			nodeModel.setCreateperson(user.getNickname());
			nodeModel.setUpdatetime(date);
			nodeModel.setUpdateperson(user.getNickname());
			tmsApprovalNodeMapper.save(nodeModel);
			// 保存节点审批者表
			if (vo.getNodeApproverType() == DataDictionaryConstant.NODE_APPROVER_TYPE_ROLE) {
				for (ApprovalNodeRoleVO roleVo : vo.getApprovalNodeRoleVOs()) {
					// 保存节点审批者表
					TmsApprovalNdApproverModel nodeApproverModel = new TmsApprovalNdApproverModel();
					String nodeApproverId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_APPROVAL_NODE_APPROVER_ID, "L");
					ToolKits.isParamNull(nodeApproverId, "获取审批流程节点ID失败！");
					// ID
					nodeApproverModel.setId(Long.valueOf(nodeApproverId));
					// 审批节点ID
					nodeApproverModel.setApprovalNodeId(Long.valueOf(nodeId));
					nodeApproverModel.setNodeOrder(vo.getNodeOrder());
					// 审批流程ID
					nodeApproverModel.setApprovalId(vo.getApprovalId());
					// 审批角色ID
					nodeApproverModel.setApproverRoleId(roleVo.getApproverRoleId());
					// 审批角色名称
					nodeApproverModel.setApproverRoleName(roleVo.getApproverRoleName());
					// 设置企业
					nodeApproverModel.setEnterpriseId(user.getEnterpriseId());
					nodeApproverModel.setEnterpriseName(user.getEnterpriseName());

					// 设置创建人
					nodeApproverModel.setCreatetime(date);
					nodeApproverModel.setCreateperson(user.getNickname());
					nodeApproverModel.setUpdatetime(date);
					nodeApproverModel.setUpdateperson(user.getNickname());
					tmsApprovalNdApproveMapper.save(nodeApproverModel);
				}
			} else if (vo.getNodeApproverType() == DataDictionaryConstant.NODE_APPROVER_TYPE_USER) {
				for (ApprovalNodeUserVO userVo : vo.getApprovalNodeUserVOs()) {
					// 保存节点审批者表
					TmsApprovalNdApproverModel nodeApproverModel = new TmsApprovalNdApproverModel();
					// ID
					String nodeApproverId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_APPROVAL_NODE_APPROVER_ID, "L");
					ToolKits.isParamNull(nodeApproverId, "获取审批流程节点ID失败！");
					// ID
					nodeApproverModel.setId(Long.valueOf(nodeApproverId));
					// 审批节点ID
					nodeApproverModel.setApprovalNodeId(Long.valueOf(nodeId));
					nodeApproverModel.setNodeOrder(vo.getNodeOrder());
					// 审批流程ID
					nodeApproverModel.setApprovalId(vo.getApprovalId());
					// 审批用户ID
					nodeApproverModel.setApproverUserId(userVo.getApproverUserId());
					// 审批用户名称
					nodeApproverModel.setApproverUserName(userVo.getApproverUserName());
					// 设置企业
					nodeApproverModel.setEnterpriseId(user.getEnterpriseId());
					nodeApproverModel.setEnterpriseName(user.getEnterpriseName());
					// 设置创建人
					nodeApproverModel.setCreatetime(date);
					nodeApproverModel.setCreateperson(user.getNickname());
					nodeApproverModel.setUpdatetime(date);
					nodeApproverModel.setUpdateperson(user.getNickname());
					tmsApprovalNdApproveMapper.save(nodeApproverModel);
				}
			}
		}
	}

	/**
	 * 审批流程节点删除
	 *
	 * @param approvalNodeDeleteVO
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public void approvalNodeDelete(ApprovalNodeDeleteVO approvalNodeDeleteVO) {

		ToolKits.isParamNull(approvalNodeDeleteVO, "审批流程节点不为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "没有操作权限！");
		Long approvalId = approvalNodeDeleteVO.getApprovalId();
		Long approvalNodeId = approvalNodeDeleteVO.getNodeId();
		// 流程在使用中的判断
		Criteria criteria = Criteria.forClass(TmsApprovalBusinessModel.class);
		Restriction r1 = Restrictions.eq("approvalId", approvalId);
		Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		Restriction r3 = Restrictions.lt("status", DataDictionaryConstant.APPROVAL_BUSINESS_STATUS_INVALID);

		criteria.setRestriction(Restrictions.and(r1, r2, r3));
		List<TmsApprovalBusinessModel> tmsApprovalBussinessModels = tmsApprovalBussinessMapper.findByCriteria(criteria);
		Assert.isTrue(tmsApprovalBussinessModels == null || tmsApprovalBussinessModels.size() == 0, "流程【" + approvalId + "】在审核中，请先审核完成");

		// 流程审批节点表删除
		Criteria criteriaNode = Criteria.forClass(TmsApprovalNodeModel.class);
		Restriction r7 = Restrictions.eq("approvalId", approvalId);
		Restriction r8 = Restrictions.eq("nodeId", approvalNodeId);
		Restriction r9 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		criteriaNode.setRestriction(Restrictions.and(r7, r8, r9));
		tmsApprovalNodeMapper.deleteByCriteria(criteriaNode);

		// 节审批流程点审批者表中该节点对应的所有审批者都删除
		Criteria criteriaNodeApprover = Criteria.forClass(TmsApprovalNdApproverModel.class);
		Restriction r10 = Restrictions.eq("approvalId", approvalId);
		Restriction r11 = Restrictions.eq("approvalNodeId", approvalNodeId);
		Restriction r12 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		criteriaNodeApprover.setRestriction(Restrictions.and(r10, r11, r12));
		tmsApprovalNodeMapper.deleteByCriteria(criteriaNodeApprover);
	}

	/**
	 * 审批流程节点查询
	 *
	 * @param approvalId
	 * @return
	 */
	public ApprovalNodeDTO approvalNodeQuery(String approvalId) {
		ToolKits.isParamNull(approvalId, "审批节点查询请求不为空");

		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		// 响应集合
		List<ApprovalNodeQueryDTO> approvalNodeQueryDTOs = new ArrayList<>();
		ApprovalNodeDTO approvalNodeDTO = new ApprovalNodeDTO();
		// 节点状态名称
		List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.NODE_STATUS, null, null, null);
		// 多人审批方式名称
		List<Map<String, Object>> restMessage2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.NODE_APPROVAL_TYPE, null, null, null);

		Criteria criteria = Criteria.forClass(TmsApprovalNodeModel.class);
		Restriction r1 = Restrictions.eq("approvalId", approvalId);
		Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		criteria.setRestriction(Restrictions.and(r1, r2));
		criteria.setOrder(Order.newInstance().asc(new String[] { "nodeOrder" }));

		List<TmsApprovalNodeModel> tmsApprovalNodeModels = tmsApprovalNodeMapper.findByCriteria(criteria);
		for (TmsApprovalNodeModel nodeModel : tmsApprovalNodeModels) {
			ApprovalNodeQueryDTO dto = new ApprovalNodeQueryDTO();
			BeanUtils.copyProperties(nodeModel, dto);
			dto.setStatusName(PublicMethods.change(restMessage1, String.valueOf(nodeModel.getStatus())));
			dto.setNodeApprovalTypeName(PublicMethods.change(restMessage2, String.valueOf(nodeModel.getNodeApprovalType())));

			// 审批节点的角色对象集合
			List<ApprovalNodeRoleQueryVO> approvalNodeRoleVOs = new ArrayList<ApprovalNodeRoleQueryVO>();

			// 审批节点的用户对象集合
			List<ApprovalNodeUserQueryVO> ApprovalNodeUserVOs = new ArrayList<ApprovalNodeUserQueryVO>();

			Criteria criteriaNodeApproverModel = Criteria.forClass(TmsApprovalNdApproverModel.class);
			Restriction r3 = Restrictions.eq("approvalId", approvalId);
			Restriction r4 = Restrictions.eq("approvalNodeId", nodeModel.getNodeId());
			Restriction r5 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
			criteriaNodeApproverModel.setRestriction(Restrictions.and(r3, r4, r5));
			List<TmsApprovalNdApproverModel> nodeApproverModels = tmsApprovalNdApproveMapper.findByCriteria(criteriaNodeApproverModel);
			StringBuffer userId = new StringBuffer();
			StringBuffer userName = new StringBuffer();
			StringBuffer roleId = new StringBuffer();
			StringBuffer roleName = new StringBuffer();
			for (TmsApprovalNdApproverModel approverModel : nodeApproverModels) {
				if (nodeModel.getNodeApproverType() == DataDictionaryConstant.NODE_APPROVER_TYPE_ROLE) {
					roleId.append(approverModel.getApproverRoleId());
					roleName.append(approverModel.getApproverRoleName());
					roleId.append(",");
					roleName.append(",");

					// 审批节点的角色对象
					ApprovalNodeRoleQueryVO approvalNodeRoleQueryVO = new ApprovalNodeRoleQueryVO();
					approvalNodeRoleQueryVO.setApproverRoleId(approverModel.getApproverRoleId());
					approvalNodeRoleQueryVO.setApproverRoleName(approverModel.getApproverRoleName());
					approvalNodeRoleVOs.add(approvalNodeRoleQueryVO);
				} else if (nodeModel.getNodeApproverType() == DataDictionaryConstant.NODE_APPROVER_TYPE_USER) {
					userId.append(approverModel.getApproverUserId());
					userName.append(approverModel.getApproverUserName());
					userId.append(",");
					userName.append(",");

					// 审批节点的用户对象
					ApprovalNodeUserQueryVO approvalNodeUserQueryVO = new ApprovalNodeUserQueryVO();
					approvalNodeUserQueryVO.setApproverUserId(approverModel.getApproverUserId());
					approvalNodeUserQueryVO.setApproverUserName(approverModel.getApproverUserName());
					ApprovalNodeUserVOs.add(approvalNodeUserQueryVO);
				}
			}

			if (ToolKits.isNotEmpty(userId.toString())) {
				dto.setUserIds(userId.toString().substring(0, userId.toString().length() - 1));
			}
			if (ToolKits.isNotEmpty(userName.toString())) {
				dto.setUserNames(userName.toString().substring(0, userName.toString().length() - 1));
			}
			if (ToolKits.isNotEmpty(roleId.toString())) {
				dto.setRoleIds(roleId.toString().substring(0, roleId.toString().length() - 1));
			}
			if (ToolKits.isNotEmpty(roleName.toString())) {
				dto.setRoleNames(roleName.toString().substring(0, roleName.toString().length() - 1));
			}

			dto.setApprovalNodeRoleVOs(approvalNodeRoleVOs);
			dto.setApprovalNodeUserVOs(ApprovalNodeUserVOs);
			approvalNodeQueryDTOs.add(dto);
		}
		approvalNodeDTO.setApprovalNodeQueryDTOS(approvalNodeQueryDTOs);

		// 流程在使用中的判断
		Criteria criteria1 = Criteria.forClass(TmsApprovalBusinessModel.class);
		Restriction r3 = Restrictions.eq("approvalId", approvalId);
		Restriction r4 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		Restriction r5 = Restrictions.lt("status", DataDictionaryConstant.APPROVAL_BUSINESS_STATUS_INVALID);

		criteria1.setRestriction(Restrictions.and(r3, r4, r5));
		List<TmsApprovalBusinessModel> tmsApprovalBussinessModels = tmsApprovalBussinessMapper.findByCriteria(criteria1);
		if (ToolKits.isEmpty(tmsApprovalBussinessModels) || tmsApprovalBussinessModels.size() == 0) {
			approvalNodeDTO.setUpdateFlg(1);
		} else {
			approvalNodeDTO.setUpdateFlg(2);
		}

		return approvalNodeDTO;
	}
}
