package com.prolog.rdc.tms.app.service.business.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.prolog.rdc.tms.app.model.dto.business.DeliveryShipbillQueryDTO;
import com.prolog.rdc.tms.app.model.vo.ShipbillDetailQueryVO;
import com.prolog.rdc.tms.app.model.vo.SignInItemVO;
import com.prolog.rdc.tms.app.model.vo.business.ShipBillReceiptPhotoVO;
import com.prolog.rdc.tms.app.service.business.*;
import com.prolog.rdc.tms.app.dao.mapper.TmsShipbillContainerTempMapper;
import com.prolog.rdc.tms.app.model.entity.TmsShipbillContainerTemp;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
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.BizException;
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.app.constant.BussinessConstant;
import com.prolog.rdc.tms.app.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.app.constant.SeriaNnumberConstant;
import com.prolog.rdc.tms.app.constant.StatusConstant;
import com.prolog.rdc.tms.app.constant.enums.ShipBillReturnTypeEnum;
import com.prolog.rdc.tms.app.dao.mapper.TmsLoadingBillDetailMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsLoadingBillHeaderMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsShipbillAbnormalMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsShipbillDetailMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsShipbillHeaderMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsShipbillPackageMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsShipbillTransportLogMapper;
import com.prolog.rdc.tms.app.model.dto.WaitDeliveredPackageDetailDTO;
import com.prolog.rdc.tms.app.model.dto.business.PendingDisPackageDTO;
import com.prolog.rdc.tms.app.model.dto.business.WaitDeliveredItemDTO;
import com.prolog.rdc.tms.app.model.dto.business.WaitDeliveredPageDTO;
import com.prolog.rdc.tms.app.model.entity.TmsLoadingBillDetailModel;
import com.prolog.rdc.tms.app.model.entity.TmsLoadingBillHeaderModel;
import com.prolog.rdc.tms.app.model.entity.TmsShipbillAbnormalModel;
import com.prolog.rdc.tms.app.model.entity.TmsShipbillDetailModel;
import com.prolog.rdc.tms.app.model.entity.TmsShipbillHeaderModel;
import com.prolog.rdc.tms.app.model.entity.TmsShipbillPackageModel;
import com.prolog.rdc.tms.app.model.entity.TmsShipbillTransLogModel;
import com.prolog.rdc.tms.app.model.vo.WaitDeliveredDeliveredConfirmVO;
import com.prolog.rdc.tms.app.model.vo.WaitDeliveredPackageDetailVO;
import com.prolog.rdc.tms.app.model.vo.business.ShipbillNodeTrackingSaveNewVO;
import com.prolog.rdc.tms.app.model.vo.business.ShipbillOperateLogSaveNewVO;
import com.prolog.rdc.tms.app.model.vo.business.SignInShipBillVO;
import com.prolog.rdc.tms.app.model.vo.business.WaitDeliveredAbnormalVO;
import com.prolog.rdc.tms.app.model.vo.business.WaitDeliveredItemQueryVO;
import com.prolog.rdc.tms.app.model.vo.business.WaitDeliveredQueryVO;
import com.prolog.rdc.tms.app.model.vo.business.WaitDeliveredSignVO;
import com.prolog.rdc.tms.app.util.AutoSignJudge;
import com.prolog.rdc.tms.app.util.DistanceUtil;
import com.prolog.rdc.tms.app.util.MessageUtil;
import com.prolog.rdc.tms.app.util.PublicMethods;
import com.prolog.rdc.tms.model.constant.RedisConstant;
import com.prolog.rdc.tms.model.dto.DeviceByOneDTO;
import com.prolog.rdc.tms.model.dto.message.SendMessageDTO;
import com.prolog.rdc.tms.model.enums.MessageOrderTypeEnum;
import com.prolog.rdc.tms.model.enums.MessageTypeEnum;
import com.prolog.rdc.tms.rmi.feign.MaindataFeign;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 待送达实现层
 *
 * @author xiaoyf
 * @since 2022/6/15 9:47
 */
@Slf4j
@Service
public class WaitDeliveredServiceImpl implements WaitDeliveredService {

	@Autowired
	private TmsLoadingBillDetailMapper tmsLoadingBillDetailMapper;

	@Autowired
	private TmsLoadingBillHeaderMapper tmsLoadingBillHeaderMapper;

	@Autowired
	private TmsShipbillHeaderMapper tmsShipbillHeaderMapper;

	@Autowired
	private TmsShipbillDetailMapper tmsShipbillDetailMapper;

	@Autowired
	private TmsShipbillPackageMapper tmsShipbillPackageMapper;

	@Autowired
	private ShipbillOperateLogService shipbillOperateLogService;

	@Autowired
	private ShipbillNodeTrackingService shipbillNodeTrackingService;

	@Autowired
	private TmsShipbillTransportLogMapper tmsShipbillTransportLogMapper;

	@Autowired
	private MaindataFeign maindataTmsResource;

	@Autowired
	private TmsShipbillAbnormalMapper tmsShipbillAbnormalMapper;

	@Autowired
	private ShipbillService shipbillService;

	@Autowired
	private AutoSignJudge autoSignJudge;

	@Autowired
	private ShipbillCommonService shipbillCommonService;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private TmsShipbillContainerTempMapper shipbillContainerTempMapper;

	/**
	 * 运单列表分页查询
	 *
	 *
	 */
	@SuppressWarnings("resource")
	@Override
	public Page<WaitDeliveredPageDTO> queryPage(WaitDeliveredQueryVO vo) throws Exception {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		if (ObjectUtil.notEqual(user.getUserType(), BussinessConstant.USER_TYPE_ZY) && ObjectUtil.notEqual(user.getUserType(), BussinessConstant.USER_TYPE_CYS)) {
			ToolKits.isParamNull(user, "当前人员没有操作权限");
		}

		vo.setEnterpriseId(user.getEnterpriseId());
		vo.setUserType(user.getUserType());
		// 自有账号
		if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {
			vo.setDepts(user.getDepts().stream().toArray(String[]::new));
			// 部门权限
			if (BussinessConstant.USER_DEPARTMENT_AUTH_Y.equals(user.getOwnedAllDataAuthFlag())) {
				vo.setIsDept(StatusConstant.IS_DEPT_YES);
			}
			// 业务员权限
			else {
				vo.setIsDept(StatusConstant.IS_DEPT_NO);
				vo.setCustomers(user.getCustomers().stream().toArray(Long[]::new));
				vo.setSuppliers(user.getSuppliers().stream().toArray(Long[]::new));
				vo.setWsarehouses(user.getWarehouses().stream().toArray(Long[]::new));
				vo.setConsignors(user.getConsignors().stream().toArray(Long[]::new));
			}
		}
		if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_CYS)) {
			vo.setCarrierId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
		}

//		Criteria criteria = Criteria.forClass(TmsLoadingBillDetailModel.class);
//		Restriction r1 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
//		Restriction r2 = null;
//		Restriction r3 = null;
//		Restriction r4 = null;
//		Restriction r5 = null;
//		Restriction r6 = null;
//		Restriction r7 = null;
//		Restriction r8 = null;
//		Restriction r29 = null;
//		if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {// 自有账号
//			// 拆单状态 0未拆单
//			Restriction r30 = Restrictions.eq("splitOrderStatus", DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
//			// 承运商拆单类型 1未拆单
//			Restriction r31 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);
//			Restriction r32 = Restrictions.and(r30, r31);
//			// 承运商拆单类型 2拆分主单
//			Restriction r33 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_SPLIT_MASTER);
//			// 承运商拆单类型 2中转主单
//			Restriction r34 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_TRANSIT_MASTER);
//			r29 = Restrictions.or(r32, r33, r34);
//
//			r2 = ToolKits.isEmpty(user.getDepts()) ? null : Restrictions.in("departmentId", user.getDepts().stream().toArray(String[]::new));
//			if (BussinessConstant.USER_DEPARTMENT_AUTH_Y.equals(user.getOwnedAllDataAuthFlag())) {// 部门权限
//
//			} else {// 业务员权限
//				r3 = ToolKits.isEmpty(user.getSuppliers()) ? null : Restrictions.in("consigneeUnitId", user.getSuppliers().stream().toArray(Long[]::new));
//				r4 = ToolKits.isEmpty(user.getCustomers()) ? null : Restrictions.in("consigneeUnitId", user.getCustomers().stream().toArray(Long[]::new));
//				r5 = ToolKits.isEmpty(user.getWarehouses()) ? null : Restrictions.in("consigneeUnitId", user.getWarehouses().stream().toArray(Long[]::new));
//
//				Restriction r13 = ToolKits.isEmpty(user.getSuppliers()) ? null : Restrictions.in(TmsLoadingBillDetailModel::getShipperUnitId, user.getSuppliers().stream().toArray(Long[]::new));
//				Restriction r14 = ToolKits.isEmpty(user.getCustomers()) ? null : Restrictions.in(TmsLoadingBillDetailModel::getShipperUnitId, user.getCustomers().stream().toArray(Long[]::new));
//				Restriction r15 = ToolKits.isEmpty(user.getWarehouses()) ? null : Restrictions.in(TmsLoadingBillDetailModel::getShipperUnitId, user.getWarehouses().stream().toArray(Long[]::new));
//
//				r6 = Restrictions.or(r3, r4, r5,r13, r14, r15);
//				r7 = ToolKits.isEmpty(user.getConsignors()) ? null : Restrictions.in("cargoOwnerId", user.getConsignors().stream().toArray(Long[]::new));
//			}
//		}
//		if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_CYS)) {// 承运商账号
//			r29 = Restrictions.eq("carrierSplitOrderStatus", DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);
//			r8 = Restrictions.eq("carrierId", Long.valueOf(user.getLoginUserCompanyInfo().getId()));
//		}
//		// STD-DEVELOP20220823 lhb 自动签到 20220907 start
//		Restriction r9 = Restrictions.in(TmsLoadingBillDetailModel::getStatus, new Integer[] { DataDictionaryConstant.SHIPBILL_STATUS_SD, DataDictionaryConstant.SHIPBILL_STATUS_SDQD });
//		// STD-DEVELOP20220823 lhb 自动签到 20220907 end
//		Restriction r10 = ToolKits.isEmpty(vo.getStartTime()) ? null : Restrictions.le("createtime", vo.getStartTime());
//		Restriction r11 = ToolKits.isEmpty(vo.getEndTime()) ? null : Restrictions.ge("createtime", vo.getEndTime());
//
//		criteria.setRestriction(Restrictions.and(r1, r2, r6, r7, r8, r9, r29, r10, r11));
//		criteria.setOrder(Order.newInstance().asc(new String[] { "loadingBillId", "shippingOrder" }));
		PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
		// STD-DEVELOP20220823 lhb 自动签到 20220907 start
//		List<TmsLoadingBillDetailModel> list = tmsLoadingBillDetailMapper.findByCriteria(criteria);
		List<TmsLoadingBillDetailModel> list = tmsLoadingBillDetailMapper.queryWaitDelivered(vo);

		List<WaitDeliveredPageDTO> dtos = Lists.newArrayList();
		for (TmsLoadingBillDetailModel model : list) {
			// STD-DEVELOP20220823 lhb 自动签到 20220907 end
			WaitDeliveredPageDTO dto = new WaitDeliveredPageDTO();
			BeanUtils.copyProperties(model, dto);

			TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(model.getShipbillId(), TmsShipbillHeaderModel.class);
			dto.setShipbillType(tmsShipbillHeaderModel.getShipbillType());
			dto.setShipToConsignee(model.getConsigneeContact());

			if (ObjectUtil.equal(model.getShipperType(), DataDictionaryConstant.SHIPPER_TYPE_KH) || ObjectUtil.equal(model.getShipperType(), DataDictionaryConstant.SHIPPER_TYPE_GYS)) {
				dto.setShipperName(model.getShipperUnitName() + "/" + model.getShipperName());
			}

			if (ObjectUtil.equal(model.getShipperType(), DataDictionaryConstant.CONSIGNEE_TYPE_KH) || ObjectUtil.equal(model.getShipperType(), DataDictionaryConstant.CONSIGNEE_TYPE_GYS)) {
				dto.setConsigneeName(model.getConsigneeUnitName() + "/" + model.getConsigneeName());
			}

			StringBuffer tel = new StringBuffer();
			// STD-DEVELOP20220823 lhb 20220823 小程序电话显示修改的需求新增 start
			if (ToolKits.isNotEmpty(model.getConsigneePhoneNumber())) {
				tel.append(model.getConsigneePhoneNumber());
			} else if (ToolKits.isNotEmpty(model.getConsigneeLandlineNumber())) {
				tel.append(model.getConsigneeLandlineNumber());
			}
			// STD-DEVELOP20220823 lhb 20220823 小程序电话显示修改的需求新增 end
			if (ToolKits.isNotEmpty(tel.toString())) {
				dto.setContact(tel.toString());
			}

			if (ObjectUtil.equal(DataDictionaryConstant.SHIPBILL_STATUS_SD, model.getStatus())) {
				dto.setIsSign("1");// 是否签到前端判断标识
			} else {
				dto.setIsSign("0");
			}

			// 获取包裹信息
			Criteria criteriaPkg = Criteria.forClass(TmsShipbillPackageModel.class);
			Restriction rr1 = Restrictions.eq(TmsShipbillPackageModel::getShipbillId, dto.getShipbillId());
			Restriction rr2 = Restrictions.eq(TmsShipbillPackageModel::getEnterpriseId, user.getEnterpriseId());
			criteriaPkg.setRestriction(Restrictions.and(rr1, rr2));
			criteriaPkg.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));

			List<TmsShipbillPackageModel> tmsShipbillPackageModels = tmsShipbillPackageMapper.findByCriteria(criteriaPkg);

			List<PendingDisPackageDTO> loadingPackageDTOList = Lists.newArrayList();
			for (TmsShipbillPackageModel packageModel : tmsShipbillPackageModels) {
				PendingDisPackageDTO packageDTO = new PendingDisPackageDTO();
				BeanUtils.copyProperties(packageModel, packageDTO);
				loadingPackageDTOList.add(packageDTO);
			}
			dto.setPackageDetail(loadingPackageDTOList);

			if (loadingPackageDTOList.size() == 0) {
				// 获取商品信息
				Criteria criteriaDetail = Criteria.forClass(TmsShipbillDetailModel.class);
				Restriction ri1 = Restrictions.eq(TmsShipbillDetailModel::getShipbillId, dto.getShipbillId());
				criteriaDetail.setRestriction(Restrictions.and(ri1));
				criteriaDetail.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));
				List<TmsShipbillDetailModel> tmsShipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteriaDetail);

				List<WaitDeliveredItemDTO> detailDTOList = Lists.newArrayList();
				for (TmsShipbillDetailModel detailModel : tmsShipbillDetailModels) {
					WaitDeliveredItemDTO detailDTO = new WaitDeliveredItemDTO();
					BeanUtils.copyProperties(detailModel, detailDTO);
					// STD-BUG20220823 xiaoyf 29729字段显示修复 start
					detailDTO.setQty(ToolKits.isEmpty(detailModel.getPcs()) ? 0 : detailModel.getPcs().intValue());
					// STD-BUG20220823 xiaoyf 29729字段显示修复 end
					detailDTO.setScratchArea(ToolKits.isEmpty(detailModel.getStagingLocation()) ? "" : detailModel.getStagingLocation());
					detailDTOList.add(detailDTO);
				}
				// 商品信息
				dto.setItemDetail(detailDTOList);
			}
			// STD-DEVELOP20220823 lhb 自动签到 20220907 start
			if (ToolKits.isNotEmpty(vo.getDriverLongitude()) && ToolKits.isNotEmpty(vo.getDriverLatitude())) {
				if (ToolKits.isNotEmpty(model.getConsigneeDeliveryRail()) && model.getConsigneeDeliveryRail().doubleValue() > 0 && model.getStatus().intValue() == DataDictionaryConstant.SHIPBILL_STATUS_SD.intValue() && ToolKits.isNotEmpty(model.getConsigneeLongitude()) && ToolKits.isNotEmpty(model.getConsigneeLatitude()) && ToolKits.isNotEmpty(model.getConsigneeDeliverySign()) && ToolKits.isNotEmpty(model.getConsigneeAutoDeliverySign()) && model.getConsigneeDeliverySign().intValue() > 0 && model.getConsigneeAutoDeliverySign().intValue() > 0) {
					// 司机和仓库之间的距离
					double pos = DistanceUtil.getDistance(vo.getDriverLongitude().doubleValue(), vo.getDriverLatitude().doubleValue(), model.getConsigneeLongitude().doubleValue(), model.getConsigneeLatitude().doubleValue());
					if (Double.compare(pos, model.getConsigneeDeliveryRail().doubleValue()) <= 0 && autoSignJudge.autoSignJudge(model.getShipbillId(), "2")) {
						WaitDeliveredSignVO deliveredSignVO = new WaitDeliveredSignVO();
						deliveredSignVO.setShipbillId(model.getShipbillId());
						deliveredSignVO.setId(model.getId());
						// 调用自动签到
						sign(deliveredSignVO);
						dto.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_SDQD);
					}
				}
			}
			// STD-DEVELOP20220823 lhb 自动签到 20220907 end
			dtos.add(dto);
		}

		Page<WaitDeliveredPageDTO> page = PageUtils.getPage(dtos);
		if (list instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<TmsLoadingBillDetailModel> p0 = (com.github.pagehelper.Page<TmsLoadingBillDetailModel>) list;
			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;
	}

	@Override
	public Page<WaitDeliveredPageDTO> queryPageGroupByConsignee(WaitDeliveredQueryVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		if (ObjectUtil.notEqual(user.getUserType(), BussinessConstant.USER_TYPE_ZY) && ObjectUtil.notEqual(user.getUserType(), BussinessConstant.USER_TYPE_CYS)) {
			ToolKits.isParamNull(user, "当前人员没有操作权限");
		}
		vo.setEnterpriseId(user.getEnterpriseId());
		vo.setUserType(user.getUserType());
		// 自有账号
		if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {
			vo.setDepts(user.getDepts().stream().toArray(String[]::new));
			// 部门权限
			if (BussinessConstant.USER_DEPARTMENT_AUTH_Y.equals(user.getOwnedAllDataAuthFlag())) {
				vo.setIsDept(StatusConstant.IS_DEPT_YES);
			}
			// 业务员权限
			else {
				vo.setIsDept(StatusConstant.IS_DEPT_NO);
				vo.setCustomers(user.getCustomers().stream().toArray(Long[]::new));
				vo.setSuppliers(user.getSuppliers().stream().toArray(Long[]::new));
				vo.setWsarehouses(user.getWarehouses().stream().toArray(Long[]::new));
				vo.setConsignors(user.getConsignors().stream().toArray(Long[]::new));
			}
		}
		if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_CYS)) {
			vo.setCarrierId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
		}
		PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
		// STD-DEVELOP20220823 lhb 自动签到 20220907 start
		List<TmsLoadingBillDetailModel> list = tmsLoadingBillDetailMapper.queryWaitDeliveredGroupByConsignee(vo);
		List<WaitDeliveredPageDTO> dtos = Lists.newArrayList();
		for (TmsLoadingBillDetailModel model : list) {
			// STD-DEVELOP20220823 lhb 自动签到 20220907 end
			WaitDeliveredPageDTO dto = new WaitDeliveredPageDTO();
			BeanUtils.copyProperties(model, dto);
			dto.setShipToConsignee(model.getConsigneeContact());
//			if (ObjectUtil.equal(model.getShipperType(), DataDictionaryConstant.SHIPPER_TYPE_KH) || ObjectUtil.equal(model.getShipperType(), DataDictionaryConstant.SHIPPER_TYPE_GYS)) {
//				dto.setShipperName(model.getShipperUnitName() + "/" + model.getShipperName());
//			}
//			if (ObjectUtil.equal(model.getShipperType(), DataDictionaryConstant.CONSIGNEE_TYPE_KH) || ObjectUtil.equal(model.getShipperType(), DataDictionaryConstant.CONSIGNEE_TYPE_GYS)) {
//				dto.setConsigneeName(model.getConsigneeUnitName() + "/" + model.getConsigneeName());
//			}
			StringBuffer tel = new StringBuffer();
			// STD-DEVELOP20220823 lhb 20220823 小程序电话显示修改的需求新增 start
			if (ToolKits.isNotEmpty(model.getConsigneePhoneNumber())) {
				tel.append(model.getConsigneePhoneNumber());
			} else if (ToolKits.isNotEmpty(model.getConsigneeLandlineNumber())) {
				tel.append(model.getConsigneeLandlineNumber());
			}
			// STD-DEVELOP20220823 lhb 20220823 小程序电话显示修改的需求新增 end
			if (ToolKits.isNotEmpty(tel.toString())) {
				dto.setContact(tel.toString());
			}
			if (ObjectUtil.equal(DataDictionaryConstant.SHIPBILL_STATUS_SD, model.getStatus())) {
				dto.setIsSign("1");// 是否签到前端判断标识
			} else {
				dto.setIsSign("0");
			}
			// 获取包裹信息
//			Criteria criteriaPkg = Criteria.forClass(TmsShipbillPackageModel.class);
//			Restriction rr1 = Restrictions.in(TmsShipbillPackageModel::getShipbillId, dto.getShipbillId().split(","));
//			Restriction rr2 = Restrictions.eq(TmsShipbillPackageModel::getEnterpriseId, user.getEnterpriseId());
//			criteriaPkg.setRestriction(Restrictions.and(rr1, rr2));
//			criteriaPkg.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));
//			List<TmsShipbillPackageModel> tmsShipbillPackageModels = tmsShipbillPackageMapper.findByCriteria(criteriaPkg);
//			List<PendingDisPackageDTO> loadingPackageDTOList = Lists.newArrayList();
//			for (TmsShipbillPackageModel packageModel : tmsShipbillPackageModels) {
//				PendingDisPackageDTO packageDTO = new PendingDisPackageDTO();
//				BeanUtils.copyProperties(packageModel, packageDTO);
//				loadingPackageDTOList.add(packageDTO);
//			}
//			dto.setPackageDetail(loadingPackageDTOList);
//			if (loadingPackageDTOList.size() == 0) {
//				// 获取商品信息
//				Criteria criteriaDetail = Criteria.forClass(TmsShipbillDetailModel.class);
//				Restriction ri1 = Restrictions.in(TmsShipbillDetailModel::getShipbillId, dto.getShipbillId().split(","));
//				criteriaDetail.setRestriction(Restrictions.and(ri1));
//				criteriaDetail.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));
//				List<TmsShipbillDetailModel> tmsShipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteriaDetail);
//				List<WaitDeliveredItemDTO> detailDTOList = Lists.newArrayList();
//				for (TmsShipbillDetailModel detailModel : tmsShipbillDetailModels) {
//					WaitDeliveredItemDTO detailDTO = new WaitDeliveredItemDTO();
//					BeanUtils.copyProperties(detailModel, detailDTO);
//					detailDTO.setQty(ToolKits.isEmpty(detailModel.getPcs()) ? 0 : detailModel.getPcs().intValue());
//					detailDTO.setScratchArea(ToolKits.isEmpty(detailModel.getStagingLocation()) ? "" : detailModel.getStagingLocation());
//					detailDTOList.add(detailDTO);
//				}
//				// 商品信息
//				dto.setItemDetail(detailDTOList);
//			}
			List<String> shipBillIdList = Arrays.stream(dto.getShipbillId().split(",")).distinct().collect(Collectors.toList());
			dto.setShipBillNums(shipBillIdList.size());
			List<TmsShipbillHeaderModel> tmsShipbillHeaderModelList = tmsShipbillHeaderMapper.findByIds(TmsShipbillHeaderModel.class, shipBillIdList.toArray(), null);
			if (CollectionUtil.isNotEmpty(tmsShipbillHeaderModelList)) {
				List<TmsShipbillHeaderModel> filterContainer = tmsShipbillHeaderModelList.stream().filter(tmsShipbillHeaderModel -> StrUtil.isNotBlank(tmsShipbillHeaderModel.getContainerId())).collect(Collectors.toList());
				dto.setContainerId(filterContainer.stream().flatMap(tmsShipbillHeaderModel -> Arrays.stream(tmsShipbillHeaderModel.getContainerId().split(","))).distinct().collect(Collectors.joining(",")));
				dto.setContainerCode(filterContainer.stream().flatMap(tmsShipbillHeaderModel -> Arrays.stream(tmsShipbillHeaderModel.getContainerCode().split(","))).distinct().collect(Collectors.joining(",")));
				dto.setContainerName(filterContainer.stream().flatMap(tmsShipbillHeaderModel -> Arrays.stream(tmsShipbillHeaderModel.getContainerName().split(","))).distinct().collect(Collectors.joining(",")));
				List<TmsShipbillHeaderModel> filterVehicleDevice = tmsShipbillHeaderModelList.stream().filter(tmsShipbillHeaderModel -> StrUtil.isNotBlank(tmsShipbillHeaderModel.getVehicleDeviceId())).collect(Collectors.toList());
				dto.setVehicleDeviceId(filterVehicleDevice.stream().flatMap(tmsShipbillHeaderModel -> Arrays.stream(tmsShipbillHeaderModel.getVehicleDeviceId().split(","))).distinct().collect(Collectors.joining(",")));
				dto.setVehicleDeviceCode(filterVehicleDevice.stream().flatMap(tmsShipbillHeaderModel -> Arrays.stream(tmsShipbillHeaderModel.getVehicleDeviceCode().split(","))).distinct().collect(Collectors.joining(",")));
				dto.setVehicleDeviceName(filterVehicleDevice.stream().flatMap(tmsShipbillHeaderModel -> Arrays.stream(tmsShipbillHeaderModel.getVehicleDeviceName().split(","))).distinct().collect(Collectors.joining(",")));
				dto.setShipbillType(tmsShipbillHeaderModelList.stream().map(TmsShipbillHeaderModel::getShipbillType).filter(StrUtil::isNotBlank).distinct().collect(Collectors.joining(",")));
			}
			List<DeliveryShipbillQueryDTO> shipbillQueryDTOList = shipBillIdList.stream().map(shipBillId -> {
				ShipbillDetailQueryVO shipbillDetailQueryVO = new ShipbillDetailQueryVO();
				shipbillDetailQueryVO.setEnterpriseId(user.getEnterpriseId().toString());
				shipbillDetailQueryVO.setShipbillId(shipBillId);
				DeliveryShipbillQueryDTO shipbillQueryDTO = new DeliveryShipbillQueryDTO();
				shipbillQueryDTO.setShipbillId(shipBillId);
				shipbillQueryDTO.setItemDetail(tmsShipbillHeaderMapper.shipbillItemDetailQuery(shipbillDetailQueryVO));
				return shipbillQueryDTO;
			}).collect(Collectors.toList());
			dto.setShipbillDTOList(shipbillQueryDTOList);
			dto.setItemDetail(shipbillQueryDTOList.stream().filter(
					shipbillQueryDTO -> CollectionUtil.isNotEmpty(shipbillQueryDTO.getItemDetail())).flatMap(
					shipbillQueryDTO -> shipbillQueryDTO.getItemDetail().stream().map(itemDetail -> BeanUtil.copyProperties(itemDetail, WaitDeliveredItemDTO.class))).collect(Collectors.toList()));
			// STD-DEVELOP20220823 lhb 自动签到 20220907 start
			if (ToolKits.isNotEmpty(vo.getDriverLongitude()) && ToolKits.isNotEmpty(vo.getDriverLatitude())) {
				if (ToolKits.isNotEmpty(model.getConsigneeDeliveryRail()) && model.getConsigneeDeliveryRail().doubleValue() > 0 && model.getStatus().intValue() == DataDictionaryConstant.SHIPBILL_STATUS_SD.intValue() && ToolKits.isNotEmpty(model.getConsigneeLongitude()) && ToolKits.isNotEmpty(model.getConsigneeLatitude()) && ToolKits.isNotEmpty(model.getConsigneeDeliverySign()) && ToolKits.isNotEmpty(model.getConsigneeAutoDeliverySign()) && model.getConsigneeDeliverySign().intValue() > 0 && model.getConsigneeAutoDeliverySign().intValue() > 0) {
					// 司机和仓库之间的距离
					double pos = DistanceUtil.getDistance(vo.getDriverLongitude().doubleValue(), vo.getDriverLatitude().doubleValue(), model.getConsigneeLongitude().doubleValue(), model.getConsigneeLatitude().doubleValue());
					Arrays.stream(model.getShipbillId().split(",")).distinct().forEach(shipbillId -> {
						if (Double.compare(pos, model.getConsigneeDeliveryRail().doubleValue()) <= 0 && autoSignJudge.autoSignJudge(model.getShipbillId(), "2")) {
							WaitDeliveredSignVO deliveredSignVO = new WaitDeliveredSignVO();
							deliveredSignVO.setShipbillId(model.getShipbillId());
							deliveredSignVO.setId(model.getId());
							// 调用自动签到
							sign(deliveredSignVO);
							dto.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_SDQD);
						}
					});
				}
			}
			// STD-DEVELOP20220823 lhb 自动签到 20220907 end
			dtos.add(dto);
		}
		Page<WaitDeliveredPageDTO> page = PageUtils.getPage(dtos);
		if (list instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<TmsLoadingBillDetailModel> p0 = (com.github.pagehelper.Page<TmsLoadingBillDetailModel>) list;
			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;
	}

	/**
	 * 运单商品查询
	 *
	 *
	 */
	@Override
	public List<WaitDeliveredItemDTO> queryItem(WaitDeliveredItemQueryVO vo) throws Exception {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		Criteria criteria = Criteria.forClass(TmsShipbillDetailModel.class);
		Restriction r1 = Restrictions.eq("shipbillId", vo.getShipbillId());
		Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		criteria.setRestriction(Restrictions.and(r1, r2));
		criteria.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));
		List<TmsShipbillDetailModel> list = tmsShipbillDetailMapper.findByCriteria(criteria);

		List<WaitDeliveredItemDTO> dtos = Lists.newArrayList();
		for (TmsShipbillDetailModel model : list) {
			WaitDeliveredItemDTO dto = new WaitDeliveredItemDTO();
			BeanUtils.copyProperties(model, dto);
			dtos.add(dto);
		}

		return dtos;
	}

	/**
	 * 配载包裹查询
	 *
	 * @param waitDeliveredPackageDetailVO
	 * @return
	 */
	@Override
	public List<WaitDeliveredPackageDetailDTO> queryPack(WaitDeliveredPackageDetailVO waitDeliveredPackageDetailVO) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		Criteria criteria = Criteria.forClass(TmsShipbillPackageModel.class);
		Restriction r1 = Restrictions.eq("shipbillId", waitDeliveredPackageDetailVO.getShipbillId());
		criteria.setRestriction(r1);
		List<TmsShipbillPackageModel> tmsShipbillPackageModels = tmsShipbillPackageMapper.findByCriteria(criteria);

		// 返回数据集
		List<WaitDeliveredPackageDetailDTO> dtos = Lists.newArrayList();

		for (TmsShipbillPackageModel tmsShipbillPackageModel : tmsShipbillPackageModels) {
			WaitDeliveredPackageDetailDTO dto = new WaitDeliveredPackageDetailDTO();
			BeanUtils.copyProperties(tmsShipbillPackageModel, dto);
			dtos.add(dto);
		}

		return dtos;
	}

	/**
	 * 签到
	 *
	 * @param
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void sign(WaitDeliveredSignVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		// STD-DEVELOP20220823 lhb 自动签到 20220901 start
		Date date = DateUtil.date();

		Criteria criteria = Criteria.forClass(TmsLoadingBillDetailModel.class);
		Restriction r1 = Restrictions.in(TmsLoadingBillDetailModel::getShipbillId, vo.getShipbillId().split(","));
		Restriction r2 = Restrictions.eq(TmsLoadingBillDetailModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_SD);
		Restriction r3 = Restrictions.eq(TmsLoadingBillDetailModel::getEnterpriseId, user.getEnterpriseId());
		criteria.setRestriction(Restrictions.and(r1, r2, r3));
		List<TmsLoadingBillDetailModel> tmsLoadingBillDetailModels = tmsLoadingBillDetailMapper.findByCriteria(criteria);
		Assert.isTrue(tmsLoadingBillDetailModels.size() != 0, "待签到运单不存在");
		for (TmsLoadingBillDetailModel tmsLoadingBillDetailModel : tmsLoadingBillDetailModels) {
			// 原状态
			Integer oldStatus = tmsLoadingBillDetailModel.getStatus();
			tmsLoadingBillDetailModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_SDQD);
			tmsLoadingBillDetailModel.setUpdateperson(user.getNickname());
			tmsLoadingBillDetailModel.setUpdatetime(date);
			tmsLoadingBillDetailMapper.update(tmsLoadingBillDetailModel);

			ShipbillOperateLogSaveNewVO shipbillOperateLogSaveNewVO = new ShipbillOperateLogSaveNewVO();
			shipbillOperateLogSaveNewVO.setShipbillId(tmsLoadingBillDetailModel.getShipbillId());
			shipbillOperateLogSaveNewVO.setShipbillNo(tmsLoadingBillDetailModel.getShipbillId());
			shipbillOperateLogSaveNewVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_SDQD);
			shipbillOperateLogSaveNewVO.setOldStatus(oldStatus);
			shipbillOperateLogSaveNewVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_SDQD);
			shipbillOperateLogSaveNewVO.setOperateDate(DateUtil.date());
			shipbillOperateLogSaveNewVO.setEnterpriseId(user.getEnterpriseId());
			shipbillOperateLogSaveNewVO.setEnterpriseName(user.getEnterpriseName());
			shipbillOperateLogSaveNewVO.setUserId(user.getUserid());
			shipbillOperateLogSaveNewVO.setUserName(user.getNickname());
			shipbillOperateLogService.addShipbillOperateLogNewData(shipbillOperateLogSaveNewVO);

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

			// 更新运输记录表
			Criteria criteriaTransportLog = Criteria.forClass(TmsShipbillTransLogModel.class);
			Restriction r4 = Restrictions.eq(TmsShipbillTransLogModel::getEnterpriseId, tmsLoadingBillDetailModel.getEnterpriseId());
			Restriction r5 = Restrictions.eq(TmsShipbillTransLogModel::getShipbillId, tmsLoadingBillDetailModel.getShipbillId());
			criteriaTransportLog.setRestriction(Restrictions.and(r4, r5));
			tmsShipbillTransportLogMapper.updateMapByCriteria(mapUpdate, criteriaTransportLog);
		}
	}

	/**
	 * 送达确认
	 *
	 * @param
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deliveredConfirmData(WaitDeliveredDeliveredConfirmVO vo) throws Exception {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		List<TmsShipbillHeaderModel> tmsShipbillHeaderModelList = tmsShipbillHeaderMapper.findByIds(TmsShipbillHeaderModel.class, vo.getShipbillId().split(","), null);

//		if (!DataDictionaryConstant.TEMPERATURE_REQUIREMENT_CW.equals(tmsShipbillHeader.getTemperatureRequirement())) {
//			if (Boolean.TRUE.equals(vo.getShowDeliveryTemperature()) && ObjectUtil.isNull(vo.getDeliveryTemperature())) {
//				throw new BizException("送达温度不能为空");
//			}
//		}
		tmsShipbillHeaderModelList.forEach(tmsShipbillHeader -> {
			if (ObjectUtil.equal(StatusConstant.WHETHER_YES, tmsShipbillHeader.getConsigneeDeliveryPicture()) && ToolKits.isEmpty(vo.getGoodsPhoto())) {
				throw new PrologException("送货图片不能为空");
			}
		});

		Map<String, String> receiptPicUrlMap = Maps.newHashMap();
		List<ShipBillReceiptPhotoVO> receiptPhotoVOList = vo.getReceiptPhotoVOList();
		if (StrUtil.isNotBlank(vo.getReceiptPhoto())) {
			receiptPhotoVOList = Lists.newArrayList(new ShipBillReceiptPhotoVO(vo.getShipbillId(), vo.getReceiptPhoto()));
		}
		if (CollectionUtil.isNotEmpty(receiptPhotoVOList)) {
			receiptPicUrlMap = receiptPhotoVOList.stream().collect(Collectors.toMap(ShipBillReceiptPhotoVO::getShipbillId, ShipBillReceiptPhotoVO::getReceiptPicUrl));
		}
		Map<String, String> finalReceiptPicUrlMap = receiptPicUrlMap;

		tmsShipbillHeaderModelList.forEach(tmsShipbillHeader -> {

			// STD-DEVELOP20220823 lhb 自动签到 20220907 start
			if (ToolKits.isNotEmpty(tmsShipbillHeader) && ObjectUtil.equal(StatusConstant.WHETHER_YES, tmsShipbillHeader.getConsigneeDeliveryPicture()) && ToolKits.isEmpty(vo.getGoodsPhoto())) {
				throw new PrologException("送货图片不能为空");
			}

			if (Boolean.TRUE.equals(vo.getShowContainerTemperature())) {
				if (CollectionUtil.isEmpty(vo.getTemperatureVOList())) {
					throw new BizException("容器温度集合不存在");
				}
				vo.getTemperatureVOList().forEach(temperatureVO -> {
					if (ObjectUtil.isNull(temperatureVO.getTemperature())) {
						throw new BizException("容器" + temperatureVO.getName() + "温度为空");
					}
				});
				Map<Long, BigDecimal> deliveryTempMap = vo.getTemperatureVOList().stream().collect(Collectors.toMap(
						t1 -> t1.getId(), t2 -> t2.getTemperature(), (t1, t2) -> t2));
				Criteria criteria = Criteria.forClass(TmsShipbillContainerTemp.class);
				Restriction r1 = Restrictions.eq(TmsShipbillContainerTemp::getEnterpriseId, user.getEnterpriseId());
				Restriction r2 = Restrictions.eq(TmsShipbillContainerTemp::getShipbillId, tmsShipbillHeader.getShipbillId());
				criteria.setRestriction(Restrictions.and(r1, r2));
				List<TmsShipbillContainerTemp> tempList = shipbillContainerTempMapper.findByCriteria(criteria);
				if (CollectionUtil.isNotEmpty(tempList)) {
					tempList.forEach(temp -> {
						temp.setDeliveryTemp(deliveryTempMap.getOrDefault(temp.getContainerId(), BigDecimal.ZERO));
						temp.setDeliveryTempTime(DateUtil.date());
						temp.setUpdatetime(DateUtil.date());
						temp.setUpdateperson(user.getNickname());
						shipbillContainerTempMapper.update(temp);
					});
				}
			}

			// STD-DEVELOP20220823 lhb 自动签到 20220907 end
			// 当前时间
			Date date = DateUtils.nowDate();
			// 签到时间是否为空
			boolean deliverySignTime = false;
			// 货物图片
			String goodsPhoto = vo.getGoodsPhoto();
			// 回单图片
			String receiptPhoto = finalReceiptPicUrlMap.get(tmsShipbillHeader.getShipbillId());

			// 节点内容
			StringBuffer nodeEvent = new StringBuffer();
			nodeEvent.append("送达确认 送达签收人:");
			nodeEvent.append(ToolKits.isEmpty(vo.getDeliverySignPerson()) ? "" : vo.getDeliverySignPerson());
			nodeEvent.append(" 送达备注:");
			nodeEvent.append(ToolKits.isEmpty(vo.getDeliveryMemo()) ? "" : vo.getDeliveryMemo());

			if (ObjectUtil.equal(StatusConstant.WHETHER_YES, tmsShipbillHeader.getConsigneeDeliveryPicture()) && ObjectUtil.isEmpty(vo.getGoodsPhoto())) {
				throw new PrologException("货物图片不能为空");
			}

			Criteria criteriaTransport = Criteria.forClass(TmsShipbillTransLogModel.class);
			Map<String, Object> mapTransportLogUpdate = Maps.newHashMap();
			mapTransportLogUpdate.put("updateperson", user.getNickname());
			mapTransportLogUpdate.put("updatetime", date);
			// 送达时间
			mapTransportLogUpdate.put("deliveryTime", DateUtils.nowDate());
			// 配送状态
			mapTransportLogUpdate.put("deliveryStatus", tmsShipbillHeader.getDeliveryStatus());

			// 备注
			if (ToolKits.isNotEmpty(vo.getDeliveryMemo())) {
				mapTransportLogUpdate.put("deliveryMemo", vo.getDeliveryMemo());
			}

			int status = DataDictionaryConstant.SHIPBILL_STATUS_END;
			Map<String, Object> mapDetailUpdate = Maps.newHashMap();
			// 修改运单
			tmsShipbillHeader.setTransportStatus(DataDictionaryConstant.TRANSPORT_STATUS_ARRIVED);
			tmsShipbillHeader.setUpdateperson(user.getNickname());
			tmsShipbillHeader.setUpdatetime(date);

			Restriction r1 = Restrictions.eq("shipbillId", tmsShipbillHeader.getShipbillId());
			criteriaTransport.setRestriction(r1);
			// 更新订单运输记录表
			tmsShipbillTransportLogMapper.updateMapByCriteria(mapTransportLogUpdate, criteriaTransport);

			// 运单节点信息
			ShipbillNodeTrackingSaveNewVO shipbillNodeTrackingSaveNewVO = new ShipbillNodeTrackingSaveNewVO();
			shipbillNodeTrackingSaveNewVO.setNodeDate(date);
			shipbillNodeTrackingSaveNewVO.setShipbillId(tmsShipbillHeader.getShipbillId());
			shipbillNodeTrackingSaveNewVO.setShipbillNo(tmsShipbillHeader.getShipbillId());
			shipbillNodeTrackingSaveNewVO.setUserId(user.getUserid());
			shipbillNodeTrackingSaveNewVO.setUserName(user.getNickname());
			shipbillNodeTrackingSaveNewVO.setEnterpriseId(user.getEnterpriseId());
			shipbillNodeTrackingSaveNewVO.setEnterpriseName(user.getEnterpriseName());

			// 运单日志信息
			ShipbillOperateLogSaveNewVO shipbillOperateLogSaveNewVO = new ShipbillOperateLogSaveNewVO();
			shipbillOperateLogSaveNewVO.setShipbillId(tmsShipbillHeader.getShipbillId());
			shipbillOperateLogSaveNewVO.setShipbillNo(tmsShipbillHeader.getShipbillId());
			shipbillOperateLogSaveNewVO.setOperateDate(date);
			shipbillOperateLogSaveNewVO.setEnterpriseId(user.getEnterpriseId());
			shipbillOperateLogSaveNewVO.setEnterpriseName(user.getEnterpriseName());
			shipbillOperateLogSaveNewVO.setUserId(user.getUserid());
			shipbillOperateLogSaveNewVO.setUserName(user.getNickname());

			// 运单节点保存
			shipbillNodeTrackingSaveNewVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_SD);
			shipbillNodeTrackingSaveNewVO.setNodeEvent(nodeEvent.toString());
			shipbillNodeTrackingSaveNewVO.setPicUrl(goodsPhoto);
			shipbillNodeTrackingService.addShipbillNodeTrackingNewData(shipbillNodeTrackingSaveNewVO);

			// 运单日志保存
			shipbillOperateLogSaveNewVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_SD);
			shipbillOperateLogSaveNewVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_QY);
			shipbillOperateLogSaveNewVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_SD);
			shipbillOperateLogService.addShipbillOperateLogNewData(shipbillOperateLogSaveNewVO);

			if (ToolKits.isNotEmpty(receiptPhoto)) {
				if (DataDictionaryConstant.WHETHER_YES.equals(tmsShipbillHeader.getReturnOrderFlag())) {
					status = DataDictionaryConstant.SHIPBILL_STATUS_HD_ZB;
				}
				// 运单节点保存
				shipbillNodeTrackingSaveNewVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_HD_PIC);
				shipbillNodeTrackingSaveNewVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_HD_PIC);
				shipbillNodeTrackingSaveNewVO.setPicUrl(receiptPhoto);
				shipbillNodeTrackingService.addShipbillNodeTrackingNewData(shipbillNodeTrackingSaveNewVO);

				// 运单日志保存
				shipbillOperateLogSaveNewVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_HD_PIC);
				shipbillOperateLogSaveNewVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_QY);
				shipbillOperateLogSaveNewVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_HD_PIC);
				shipbillOperateLogService.addShipbillOperateLogNewData(shipbillOperateLogSaveNewVO);

				mapDetailUpdate.put("status", status);
			} else {
				if (DataDictionaryConstant.WHETHER_YES.equals(tmsShipbillHeader.getConsigneeReturnOrderPicture())) {
					status = DataDictionaryConstant.SHIPBILL_STATUS_HD_PIC;
				} else if (DataDictionaryConstant.WHETHER_YES.equals(tmsShipbillHeader.getReturnOrderFlag())) {
					status = DataDictionaryConstant.SHIPBILL_STATUS_HD_ZB;
				}
				mapDetailUpdate.put("status", status);
			}

			// 运单修改操作
			tmsShipbillHeader.setStatus(status);
			tmsShipbillHeader.setDeliveryTime(new Date());
			tmsShipbillHeader.setDeliveryTemperature(vo.getDeliveryTemperature());

			TmsShipbillHeaderModel headerModel = tmsShipbillHeaderMapper.findById(tmsShipbillHeader.getShipbillId(),TmsShipbillHeaderModel.class);
			if (DataDictionaryConstant.SHIPBILL_STATUS_SD.intValue() < headerModel.getStatus().intValue()) {
				throw new PrologException(StrUtil.format("运单{}已送达确认",tmsShipbillHeader.getShipbillNo()));
			}
			tmsShipbillHeaderMapper.update(tmsShipbillHeader);

			// 修改派车单明细
			Criteria criteriaDetail = Criteria.forClass(TmsLoadingBillDetailModel.class);
			r1 = Restrictions.eq("shipbillId", tmsShipbillHeader.getShipbillId());
			Restriction r3 = Restrictions.eq(TmsLoadingBillDetailModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_SDQD);
			Restriction r4 = Restrictions.eq(TmsLoadingBillDetailModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_SD);
			Restriction r5 = Restrictions.or(r3, r4);
			criteriaDetail.setRestriction(Restrictions.and(r1, r5));
			List<TmsLoadingBillDetailModel> loadingBillDetailModels = tmsLoadingBillDetailMapper.findByCriteria(criteriaDetail);
			if (ToolKits.isEmpty(loadingBillDetailModels)) {
				throw new PrologException("运单【" + tmsShipbillHeader.getShipbillId() + "】调度明细不存在");
			}
			mapDetailUpdate.put("transportStatus", DataDictionaryConstant.TRANSPORT_STATUS_ARRIVED);
			mapDetailUpdate.put("updateperson", user.getNickname());
			mapDetailUpdate.put("updatetime", date);
			mapDetailUpdate.put("deliveryTemperature", vo.getDeliveryTemperature());
			tmsLoadingBillDetailMapper.updateMapByCriteria(mapDetailUpdate, criteriaDetail);

			// 父运单的同步送达
			String fatherShipbillId = tmsShipbillHeader.getShipbillId();
			while (ToolKits.isNotEmpty(fatherShipbillId)) {
				fatherShipbillId = fatherDeliveredConfirm(fatherShipbillId, status, date, user, deliverySignTime, goodsPhoto, receiptPhoto, nodeEvent.toString(), mapTransportLogUpdate);
				deliverySignTime = false;
			}

			// STD-BUG20220823 lhb 4649启运登记、送达确认 需要同步回写 派车单的状态 20220915 start
			TmsLoadingBillDetailModel tmsLoadingBillDetail = loadingBillDetailModels.get(0);
			// 更新调度单状态
			r4 = Restrictions.eq("loadingBillId", tmsLoadingBillDetail.getLoadingBillId());
			r5 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
			criteriaDetail.setRestriction(Restrictions.and(r4, r5));
			List<TmsLoadingBillDetailModel> tmsLoadingBillDetailModels = tmsLoadingBillDetailMapper.findByCriteria(criteriaDetail);
			int cnt = 0;
			if (ToolKits.isNotEmpty(tmsLoadingBillDetailModels)) {
				TmsLoadingBillHeaderModel secondLoadingBillHeaderModel = tmsLoadingBillHeaderMapper.findById(tmsLoadingBillDetail.getLoadingBillId(), TmsLoadingBillHeaderModel.class);

				// 运单，第一次调度，调度给承运商，第二次调度，承运商调度给司机或者承运商时，根据第二调度单，查询第一次的调度单
				criteriaDetail = Criteria.forClass(TmsLoadingBillDetailModel.class);
				r3 = Restrictions.eq(TmsLoadingBillDetailModel::getShipbillId, tmsLoadingBillDetail.getShipbillId());
				r4 = Restrictions.eq(TmsLoadingBillDetailModel::getEnterpriseId, user.getEnterpriseId());
				r5 = Restrictions.ne(TmsLoadingBillDetailModel::getLoadingBillId, tmsLoadingBillDetail.getLoadingBillId());
				criteriaDetail.setRestriction(Restrictions.and(r3, r4, r5));
				List<TmsLoadingBillDetailModel> firstLoadingBillDetails = tmsLoadingBillDetailMapper.findByCriteria(criteriaDetail);
				cnt = tmsLoadingBillDetailModels.stream().filter(t -> t.getStatus().intValue() < DataDictionaryConstant.SHIPBILL_STATUS_HD_PIC.intValue()).collect(Collectors.toList()).size();
				if (cnt == 0) {
					// 更新状态为送达确认
					secondLoadingBillHeaderModel.setStatus(DataDictionaryConstant.LOADING_BILL_STATUS_SD);
					tmsLoadingBillHeaderMapper.update(secondLoadingBillHeaderModel);
					// 第一次调度单状态更新
					if (ToolKits.isNotEmpty(firstLoadingBillDetails)) {
						TmsLoadingBillHeaderModel firstLoadingBillHeaderModel = tmsLoadingBillHeaderMapper.findById(firstLoadingBillDetails.get(0).getLoadingBillId(), TmsLoadingBillHeaderModel.class);
						firstLoadingBillHeaderModel.setStatus(DataDictionaryConstant.LOADING_BILL_STATUS_SD);
						tmsLoadingBillHeaderMapper.update(firstLoadingBillHeaderModel);
					}
				} else {
					// 更新状态为部分送达确认
					if (!secondLoadingBillHeaderModel.getStatus().equals(DataDictionaryConstant.LOADING_BILL_STATUS_SD_PART)) {
						secondLoadingBillHeaderModel.setStatus(DataDictionaryConstant.LOADING_BILL_STATUS_SD_PART);
						tmsLoadingBillHeaderMapper.update(secondLoadingBillHeaderModel);
						// 第一次调度单状态更新
						if (ToolKits.isNotEmpty(firstLoadingBillDetails)) {
							TmsLoadingBillHeaderModel firstLoadingBillHeaderModel = tmsLoadingBillHeaderMapper.findById(firstLoadingBillDetails.get(0).getLoadingBillId(), TmsLoadingBillHeaderModel.class);
							firstLoadingBillHeaderModel.setStatus(DataDictionaryConstant.LOADING_BILL_STATUS_SD_PART);
							tmsLoadingBillHeaderMapper.update(firstLoadingBillHeaderModel);
						}
					}
				}
			}
			// STD-BUG20220823 lhb 4649启运登记、送达确认 需要同步回写 派车单的状态 20220915 end
			if (CollectionUtil.isNotEmpty(vo.getItemVOList())) {
				Criteria detailCriteria = Criteria.forClass(TmsShipbillDetailModel.class);
				Restriction detailR1 = Restrictions.eq(TmsShipbillDetailModel::getEnterpriseId, tmsShipbillHeader.getEnterpriseId());
				Restriction detailR2 = Restrictions.eq(TmsShipbillDetailModel::getShipbillId, tmsShipbillHeader.getShipbillId());
				detailCriteria.setRestriction(Restrictions.and(detailR1, detailR2));
				List<TmsShipbillDetailModel> detailModelList = tmsShipbillDetailMapper.findByCriteria(detailCriteria);
				if (CollectionUtil.isNotEmpty(detailModelList)) {
					List<String> detailIdList = detailModelList.stream().map(TmsShipbillDetailModel::getId).collect(Collectors.toList());
					List<SignInItemVO> filterVOList = vo.getItemVOList().stream().filter(signInItemVO -> detailIdList.contains(signInItemVO.getId())).collect(Collectors.toList());
					if (CollectionUtil.isNotEmpty(filterVOList)) {
						String flowConfig = tmsShipbillHeader.getFlowConfig();
						// 没有签收流程，更新签收数量，自动退
						if (!flowConfig.contains(DataDictionaryConstant.FLOW_CONFIG_SIGN_IN)) {
							SignInShipBillVO signInShipBillVO = new SignInShipBillVO();
							signInShipBillVO.setShipBillId(tmsShipbillHeader.getShipbillId());
							signInShipBillVO.setItemVOList(filterVOList);
							signInShipBillVO.setReturnType(ShipBillReturnTypeEnum.S.getCode());
							shipbillService.updateSignInPcs(signInShipBillVO);
							shipbillService.createReturnShipBill(signInShipBillVO);
						}
					}
				}
			}

			TmsLoadingBillHeaderModel tmsLoadingBillHeaderModel = tmsLoadingBillHeaderMapper.findById(tmsLoadingBillDetail.getLoadingBillId(), TmsLoadingBillHeaderModel.class);
			if (StrUtil.isNotBlank(tmsLoadingBillHeaderModel.getVehicleDeviceId()) && StrUtil.isNotBlank(tmsLoadingBillHeaderModel.getVehicleDeviceCode())) {
				Criteria criteria = Criteria.forClass(TmsLoadingBillHeaderModel.class);
				Restriction restriction1 = Restrictions.eq(TmsLoadingBillHeaderModel::getVehicleDeviceCode, tmsLoadingBillHeaderModel.getVehicleDeviceCode());
				Restriction restriction2 = Restrictions.between(TmsLoadingBillHeaderModel::getStatus, DataDictionaryConstant.LOADING_BILL_STATUS_QY_PART, DataDictionaryConstant.LOADING_BILL_STATUS_SD_PART);
				criteria.setRestriction(Restrictions.and(restriction1, restriction2));
				if (tmsLoadingBillHeaderMapper.findCountByCriteria(criteria) == 0) {
					String deviceId = tmsLoadingBillHeaderModel.getVehicleDeviceId().split(",")[0];
					try {
						RestMessage<DeviceByOneDTO> restMessage = maindataTmsResource.deviceGetOne(Long.valueOf(deviceId));
						DeviceByOneDTO deviceByOneDTO = restMessage.getData();
						if (BussinessConstant.E6.equals(deviceByOneDTO.getCompanyName())) {
							redisTemplate.opsForSet().remove(RedisConstant.PULL_GPS_DEVICE_E6_KEY, tmsLoadingBillHeaderModel.getVehicleDeviceCode());
							log.info("易流 remove loadingBillId={},vehicle={},deviceCode={}", tmsLoadingBillDetail.getLoadingBillId(), tmsLoadingBillHeaderModel.getVehiclePlateNumber(), deviceByOneDTO.getCode());
						} else if (BussinessConstant.G7.equals(deviceByOneDTO.getCompanyName())) {
							redisTemplate.opsForSet().remove(RedisConstant.PULL_GPS_DEVICE_G7_KEY, tmsLoadingBillHeaderModel.getVehicleDeviceCode());
							log.info("g7 remove loadingBillId={},vehicle={},deviceCode={}", tmsLoadingBillDetail.getLoadingBillId(), tmsLoadingBillHeaderModel.getVehiclePlateNumber(), deviceByOneDTO.getCode());
						}
					} catch (Exception e) {
						log.error("移除redis队列错误", e);
					}
				}
			}

			// 运单同步BMS
			List<String> loadingDetailIds = Lists.newArrayList();
			if (DataDictionaryConstant.SHIPBILL_STATUS_END.equals(Integer.valueOf(status))
			&& !DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS.equals(tmsShipbillHeader.getAbnormalStatus())) {
				loadingDetailIds.add(tmsLoadingBillDetail.getId());
				shipbillCommonService.pushShipbillBmsData(loadingDetailIds);
			}
			MessageUtil.addMessage(new SendMessageDTO(MessageOrderTypeEnum.SHIP_NO.getCode(), MessageTypeEnum.DELIVERY.getCode(), Lists.newArrayList(tmsShipbillHeader.getShipbillId())));
		});
	}

	/**
	 * 递归父运单送达确认
	 */
	private String fatherDeliveredConfirm(String shipbillId, int status, Date date, UserEntity user, boolean deliverySignTime, String goodsPhoto, String receiptPhoto, String nodeEvent, Map<String, Object> mapTransportLogUpdate) {
		// 查询运单
		TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(shipbillId, TmsShipbillHeaderModel.class);

		// 判断是否为原始单号
		if (ToolKits.isNotEmpty(tmsShipbillHeaderModel.getFatherShipbillId()) && !tmsShipbillHeaderModel.getFatherShipbillId().equals(shipbillId)) {
			// 查找父级单号
			TmsShipbillHeaderModel fatherShipbillHeaderModel = tmsShipbillHeaderMapper.findById(tmsShipbillHeaderModel.getFatherShipbillId(), TmsShipbillHeaderModel.class);

			// 查找同级的所有子单
			Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
			Restriction r1 = Restrictions.eq("fatherShipbillId", tmsShipbillHeaderModel.getFatherShipbillId());
			criteria.setRestriction(r1);
			List<TmsShipbillHeaderModel> tmsShipbillHeaderModelList = tmsShipbillHeaderMapper.findByCriteria(criteria);

			// 查找是否还有未完成的运单
			List<TmsShipbillHeaderModel> tmsShipbillHeaderModels = tmsShipbillHeaderModelList.stream().filter(o -> o.getStatus().intValue() <= DataDictionaryConstant.SHIPBILL_STATUS_SD.intValue()).collect(Collectors.toList());

			// 判断子单是否全部完成
			if (ToolKits.isEmpty(tmsShipbillHeaderModels)) {
				// 修改父级运单状态
				fatherShipbillHeaderModel.setStatus(status);
				fatherShipbillHeaderModel.setTransportStatus(DataDictionaryConstant.TRANSPORT_STATUS_ARRIVED);
				fatherShipbillHeaderModel.setUpdatetime(date);
				fatherShipbillHeaderModel.setUpdateperson(user.getNickname());
				fatherShipbillHeaderModel.setDeliveryTime(date);

				// 修改父级运单运输记录表
				Criteria criteriaTransport = Criteria.forClass(TmsShipbillTransLogModel.class);
				r1 = Restrictions.eq("shipbillId", fatherShipbillHeaderModel.getShipbillId());
				criteriaTransport.setRestriction(r1);
				// 更新订单运输记录表
				tmsShipbillTransportLogMapper.updateMapByCriteria(mapTransportLogUpdate, criteriaTransport);

				// 运单节点信息
				ShipbillNodeTrackingSaveNewVO shipbillNodeTrackingSaveNewVO = new ShipbillNodeTrackingSaveNewVO();
				shipbillNodeTrackingSaveNewVO.setNodeDate(date);
				shipbillNodeTrackingSaveNewVO.setShipbillId(fatherShipbillHeaderModel.getShipbillId());
				shipbillNodeTrackingSaveNewVO.setShipbillNo(fatherShipbillHeaderModel.getShipbillId());
				shipbillNodeTrackingSaveNewVO.setUserId(user.getUserid());
				shipbillNodeTrackingSaveNewVO.setUserName(user.getNickname());
				shipbillNodeTrackingSaveNewVO.setEnterpriseId(user.getEnterpriseId());
				shipbillNodeTrackingSaveNewVO.setEnterpriseName(user.getEnterpriseName());

				// 运单日志信息
				ShipbillOperateLogSaveNewVO shipbillOperateLogSaveNewVO = new ShipbillOperateLogSaveNewVO();
				shipbillOperateLogSaveNewVO.setShipbillId(fatherShipbillHeaderModel.getShipbillId());
				shipbillOperateLogSaveNewVO.setShipbillNo(fatherShipbillHeaderModel.getShipbillId());
				shipbillOperateLogSaveNewVO.setOperateDate(date);
				shipbillOperateLogSaveNewVO.setEnterpriseId(user.getEnterpriseId());
				shipbillOperateLogSaveNewVO.setEnterpriseName(user.getEnterpriseName());
				shipbillOperateLogSaveNewVO.setUserId(user.getUserid());
				shipbillOperateLogSaveNewVO.setUserName(user.getNickname());

				// 判断第一个子单是否有签到时间
				if (deliverySignTime) {
					// 运单节点保存
					shipbillNodeTrackingSaveNewVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_SD);
					shipbillNodeTrackingSaveNewVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_SDQD);
					shipbillNodeTrackingService.addShipbillNodeTrackingNewData(shipbillNodeTrackingSaveNewVO);

					// 运单日志保存
					shipbillOperateLogSaveNewVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_SDQD);
					shipbillOperateLogSaveNewVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_QY);
					shipbillOperateLogSaveNewVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_SD);
					shipbillOperateLogService.addShipbillOperateLogNewData(shipbillOperateLogSaveNewVO);
				}

				// 运单节点保存
				shipbillNodeTrackingSaveNewVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_SD);
				shipbillNodeTrackingSaveNewVO.setNodeEvent(nodeEvent);
				shipbillNodeTrackingSaveNewVO.setPicUrl(goodsPhoto);
				shipbillNodeTrackingService.addShipbillNodeTrackingNewData(shipbillNodeTrackingSaveNewVO);

				// 运单日志保存
				shipbillOperateLogSaveNewVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_SD);
				shipbillOperateLogSaveNewVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_QY);
				shipbillOperateLogSaveNewVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_SD);
				shipbillOperateLogService.addShipbillOperateLogNewData(shipbillOperateLogSaveNewVO);

				// 回单日志
				if (ToolKits.isNotEmpty(receiptPhoto)) {
					// 运单节点保存
					shipbillNodeTrackingSaveNewVO.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_HD_PIC);
					shipbillNodeTrackingSaveNewVO.setNodeEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_HD_PIC);
					shipbillNodeTrackingSaveNewVO.setPicUrl(receiptPhoto);
					shipbillNodeTrackingService.addShipbillNodeTrackingNewData(shipbillNodeTrackingSaveNewVO);

					// 运单日志保存
					shipbillOperateLogSaveNewVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_HD_PIC);
					shipbillOperateLogSaveNewVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_SD);
					shipbillOperateLogSaveNewVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_HD_PIC);
					shipbillOperateLogService.addShipbillOperateLogNewData(shipbillOperateLogSaveNewVO);

					fatherShipbillHeaderModel.setStatus(DataDictionaryConstant.LOADING_BILL_STATUS_HD_ZB);
				}

				tmsShipbillHeaderMapper.update(fatherShipbillHeaderModel);
				return fatherShipbillHeaderModel.getShipbillId();
			}
		}
		return null;
	}

	/**
	 * 异常上报
	 *
	 * @param
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void abnormalSend(WaitDeliveredAbnormalVO vo) throws Exception {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		Date date = DateUtil.date();

		// 数据字典翻译数据集合
		List<Map<String, Object>> data1 = Lists.newArrayList();
		List<Map<String, Object>> data2 = Lists.newArrayList();

		// 异常类型
		RestMessage<List<Map<String, Object>>> restMessage1 = maindataTmsResource.getDropDownById(DataDictionaryConstant.ABNORMAL_TYPE, null, null, null);
		if (!restMessage1.isSuccess()) {
			throw new RuntimeException("已派车状态翻译失败!");
		} else {
			data1 = restMessage1.getData();
		}

		// 异常事件
		RestMessage<List<Map<String, Object>>> restMessage2 = maindataTmsResource.getDropDownById(DataDictionaryConstant.ABNORMAL_EVENT, null, null, null);
		if (!restMessage2.isSuccess()) {
			throw new RuntimeException("已派车状态翻译失败!");
		} else {
			data2 = restMessage2.getData();
		}

		StringBuffer nodeEvent = new StringBuffer(DataDictionaryConstant.SHIPBILL_NODE_ABNORMAL_REGISTER);
		nodeEvent.append("异常类型为:");
		nodeEvent.append(PublicMethods.change(data1, String.valueOf(vo.getAbnormalType())));
		nodeEvent.append(",异常事件为:");
		nodeEvent.append(PublicMethods.change(data2, String.valueOf(vo.getAbnormalCase())));
		nodeEvent.append(",客户是否投诉为:");
		nodeEvent.append(ObjectUtil.equal(1, vo.getCustomerComplain()) ? "是" : "否");
		if (ToolKits.isNotEmpty(vo.getContent())) {
			nodeEvent.append(",异常内容为:");
			nodeEvent.append(vo.getContent());
		}

		// 更新运单异常状态为【异常】
		List<TmsShipbillHeaderModel> tmsShipbillHeaderList = tmsShipbillHeaderMapper.findByIds(TmsShipbillHeaderModel.class, vo.getShipbillId().split(","), null);
		tmsShipbillHeaderList.forEach(tmsShipbillHeader -> {

			if (ToolKits.isNotEmpty(tmsShipbillHeader)) {
				tmsShipbillHeader.setAbnormalStatus(DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS);
				tmsShipbillHeader.setUpdateperson(user.getNickname());
				tmsShipbillHeader.setUpdatetime(date);
				tmsShipbillHeaderMapper.update(tmsShipbillHeader);
			}

			// 更新运单运输记录
			Map<String, Object> queryMap = Maps.newHashMap();
			queryMap.put("shipbillId", tmsShipbillHeader.getShipbillId());
			List<TmsShipbillTransLogModel> tmsShipbillTransportLogs = tmsShipbillTransportLogMapper.findByMap(queryMap, TmsShipbillTransLogModel.class);
			if (ToolKits.isNotEmpty(tmsShipbillTransportLogs) && tmsShipbillTransportLogs.size() > 0) {
				TmsShipbillTransLogModel tmsShipbillTransportLog = tmsShipbillTransportLogs.get(0);
				tmsShipbillTransportLog.setAbnormalType(vo.getAbnormalType());
				tmsShipbillTransportLog.setAbnormalEvent(vo.getAbnormalCase());
				tmsShipbillTransportLog.setAbnormalComplain(vo.getCustomerComplain());
				tmsShipbillTransportLog.setAbnormalContent(vo.getContent());
				tmsShipbillTransportLog.setAbnormalTime(date);
				tmsShipbillTransportLogMapper.update(tmsShipbillTransportLog);
			}

			// 运单节点保存
			ShipbillNodeTrackingSaveNewVO nodeTrackingVO = new ShipbillNodeTrackingSaveNewVO();
			nodeTrackingVO.setNodeDate(date);
			nodeTrackingVO.setShipbillId(tmsShipbillHeader.getShipbillId());
			nodeTrackingVO.setShipbillNo(tmsShipbillHeader.getShipbillId());
			nodeTrackingVO.setStatus(tmsShipbillHeader.getStatus());
			nodeTrackingVO.setNodeEvent(nodeEvent.toString());
			nodeTrackingVO.setUserId(user.getUserid());
			nodeTrackingVO.setUserName(user.getNickname());
			nodeTrackingVO.setEnterpriseId(user.getEnterpriseId());
			nodeTrackingVO.setEnterpriseName(user.getEnterpriseName());
			nodeTrackingVO.setPicUrl(vo.getPictureUrl());
			shipbillNodeTrackingService.addShipbillNodeTrackingNewData(nodeTrackingVO);

			// 运单日志保存
			ShipbillOperateLogSaveNewVO operateLogVO = new ShipbillOperateLogSaveNewVO();
			operateLogVO.setShipbillId(tmsShipbillHeader.getShipbillId());
			operateLogVO.setShipbillNo(tmsShipbillHeader.getShipbillId());
			operateLogVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_YCDJ);
			operateLogVO.setOldStatus(tmsShipbillHeader.getStatus());
			operateLogVO.setNewStatus(tmsShipbillHeader.getStatus());
			operateLogVO.setOperateDate(date);
			operateLogVO.setEnterpriseId(user.getEnterpriseId());
			operateLogVO.setEnterpriseName(user.getEnterpriseName());
			operateLogVO.setUserId(user.getUserid());
			operateLogVO.setUserName(user.getNickname());
			shipbillOperateLogService.addShipbillOperateLogNewData(operateLogVO);

			// 如果有对应装车单明细,也要更新异常状态为【异常】
			Map<String, Object> queryMap2 = Maps.newHashMap();
			queryMap2.put("shipbillId", tmsShipbillHeader.getShipbillId());
			List<TmsLoadingBillDetailModel> tmsLoadingBillDetails = tmsLoadingBillDetailMapper.findByMap(queryMap2, TmsLoadingBillDetailModel.class);
			if (ToolKits.isNotEmpty(tmsLoadingBillDetails) && tmsLoadingBillDetails.size() > 0) {
				for (TmsLoadingBillDetailModel tmsLoadingBillDetail : tmsLoadingBillDetails) {
					tmsLoadingBillDetail.setAbnormalStatus(DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS);
					tmsLoadingBillDetail.setUpdateperson(user.getNickname());
					tmsLoadingBillDetail.setUpdatetime(date);
					tmsLoadingBillDetailMapper.update(tmsLoadingBillDetail);
				}
			}

			// STD-DEVELOP20220823 lhb 异常登记 20220914 start
			// 获取运单异常表ID
			RestMessage<String> restMessageDetailId = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_ABNORMAL_ID, "L");
			if (!restMessageDetailId.isSuccess()) {
				throw new RuntimeException("生成运单异常表ID失败:" + restMessageDetailId.getMessage());
			}
			TmsShipbillAbnormalModel abnormalModel = new TmsShipbillAbnormalModel();
			abnormalModel.setId(restMessageDetailId.getData());
			abnormalModel.setShipbillId(tmsShipbillHeader.getShipbillId());
			abnormalModel.setShipbillNo(tmsShipbillHeader.getShipbillId());
			abnormalModel.setAbnormalTime(date);
			abnormalModel.setAbnormalType(vo.getAbnormalType());
			abnormalModel.setAbnormalEvent(vo.getAbnormalCase());
			abnormalModel.setAbnormalComplain(vo.getCustomerComplain());
			abnormalModel.setAbnormalContent(vo.getContent());
			abnormalModel.setAbnormalPhoto(vo.getPictureUrl());
			abnormalModel.setAbnormalStatus(DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS);
			abnormalModel.setEnterpriseId(user.getEnterpriseId());
			abnormalModel.setEnterpriseName(user.getEnterpriseName());
			abnormalModel.setCreateperson(user.getNickname());
			abnormalModel.setCreatetime(date);
			tmsShipbillAbnormalMapper.save(abnormalModel);
			// STD-DEVELOP20220823 lhb 异常登记 20220914 end

			// 递归对上级运单进行异常上报
			String fatherShipbillId = tmsShipbillHeader.getFatherShipbillId();
			while (ToolKits.isNotEmpty(fatherShipbillId)) {
				fatherShipbillId = abnormalSendFather(fatherShipbillId, nodeTrackingVO, operateLogVO, vo, date, user);
			}
		});

	}

	/**
	 * 递归对上级运单进行异常上报
	 *
	 */
	private String abnormalSendFather(String shipbillId, ShipbillNodeTrackingSaveNewVO nodeTrackingVO, ShipbillOperateLogSaveNewVO operateLogVO, WaitDeliveredAbnormalVO vo, Date date, UserEntity user) {
		TmsShipbillHeaderModel fatherShipbill = tmsShipbillHeaderMapper.findById(shipbillId, TmsShipbillHeaderModel.class);
		if (ToolKits.isNotEmpty(fatherShipbill.getFatherShipbillId()) && !fatherShipbill.getFatherShipbillId().equals(shipbillId)) {
			// 更新运单异常状态为【异常】
			fatherShipbill.setAbnormalStatus(DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS);
			fatherShipbill.setUpdateperson(nodeTrackingVO.getUserName());
			fatherShipbill.setUpdatetime(date);
			tmsShipbillHeaderMapper.update(fatherShipbill);

			// 更新运单运输记录
			Map<String, Object> queryMap = Maps.newHashMap();
			queryMap.put("shipbillId", fatherShipbill.getShipbillId());
			List<TmsShipbillTransLogModel> tmsShipbillTransportLogs = tmsShipbillTransportLogMapper.findByMap(queryMap, TmsShipbillTransLogModel.class);
			if (ToolKits.isNotEmpty(tmsShipbillTransportLogs) && tmsShipbillTransportLogs.size() > 0) {
				TmsShipbillTransLogModel tmsShipbillTransportLog = tmsShipbillTransportLogs.get(0);
				tmsShipbillTransportLog.setAbnormalType(vo.getAbnormalType());
				tmsShipbillTransportLog.setAbnormalEvent(vo.getAbnormalCase());
				tmsShipbillTransportLog.setAbnormalComplain(vo.getCustomerComplain());
				tmsShipbillTransportLog.setAbnormalContent(vo.getContent());
				tmsShipbillTransportLog.setAbnormalTime(date);
				tmsShipbillTransportLogMapper.update(tmsShipbillTransportLog);
			}

			// 运单节点保存
			nodeTrackingVO.setNodeDate(DateUtil.date());
			nodeTrackingVO.setShipbillId(fatherShipbill.getShipbillId());
			nodeTrackingVO.setShipbillNo(fatherShipbill.getShipbillId());
			shipbillNodeTrackingService.addShipbillNodeTrackingNewData(nodeTrackingVO);

			// 运单日志保存
			operateLogVO.setOperateDate(DateUtil.date());
			operateLogVO.setShipbillId(fatherShipbill.getShipbillId());
			operateLogVO.setShipbillNo(fatherShipbill.getShipbillId());
			shipbillOperateLogService.addShipbillOperateLogNewData(operateLogVO);

			// STD-DEVELOP20220823 lhb 异常登记 20220914 start
			// 获取运单异常表ID
			RestMessage<String> restMessageDetailId = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_SHIPBILL_ABNORMAL_ID, "L");
			if (!restMessageDetailId.isSuccess()) {
				throw new RuntimeException("生成运单异常表ID失败:" + restMessageDetailId.getMessage());
			}
			TmsShipbillAbnormalModel abnormalModel = new TmsShipbillAbnormalModel();
			abnormalModel.setId(restMessageDetailId.getData());
			abnormalModel.setShipbillId(fatherShipbill.getShipbillId());
			abnormalModel.setShipbillNo(fatherShipbill.getShipbillId());
			abnormalModel.setAbnormalTime(date);
			abnormalModel.setAbnormalType(vo.getAbnormalType());
			abnormalModel.setAbnormalEvent(vo.getAbnormalCase());
			abnormalModel.setAbnormalComplain(vo.getCustomerComplain());
			abnormalModel.setAbnormalContent(vo.getContent());
			abnormalModel.setAbnormalPhoto(vo.getPictureUrl());
			abnormalModel.setAbnormalStatus(DataDictionaryConstant.SHIPBILL_ABNORMAL_STATUS);
			abnormalModel.setEnterpriseId(user.getEnterpriseId());
			abnormalModel.setEnterpriseName(user.getEnterpriseName());
			abnormalModel.setCreateperson(user.getNickname());
			abnormalModel.setCreatetime(DateUtil.date());
			tmsShipbillAbnormalMapper.save(abnormalModel);
			// STD-DEVELOP20220823 lhb 异常登记 20220914 end

			return fatherShipbill.getFatherShipbillId();
		}
		return null;
	}

}
