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

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.prolog.framework.core.exception.BizException;
import com.prolog.rdc.tms.app.dao.mapper.*;
import com.prolog.rdc.tms.app.model.entity.*;
import com.prolog.rdc.tms.app.service.business.LoadingBillService;
import com.prolog.rdc.tms.app.util.MessageUtil;
import com.prolog.rdc.tms.model.dto.message.SendMessageDTO;
import com.prolog.rdc.tms.model.entity.SysParamConfigModel;
import com.prolog.rdc.tms.model.enums.MessageOrderTypeEnum;
import com.prolog.rdc.tms.model.enums.MessageTypeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
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.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.model.dto.BranchAppointmentInfoDTO;
import com.prolog.rdc.tms.app.model.dto.business.AppLoadingPackageDTO;
import com.prolog.rdc.tms.app.model.dto.business.AppointmentQueryDTO;
import com.prolog.rdc.tms.app.model.dto.business.AppointmentTimesDTO;
import com.prolog.rdc.tms.app.model.dto.business.AppointmentWeekDTO;
import com.prolog.rdc.tms.app.model.dto.business.PickUpAppointmentDTO;
import com.prolog.rdc.tms.app.model.dto.business.ShipBillDetailDTO;
import com.prolog.rdc.tms.app.model.vo.AppointmentHeadQueryVO;
import com.prolog.rdc.tms.app.model.vo.QueryMaxReserveNumberVO;
import com.prolog.rdc.tms.app.model.vo.business.AppointmentShipbillQueryVO;
import com.prolog.rdc.tms.app.model.vo.business.BusinessAppointmentQueryVO;
import com.prolog.rdc.tms.app.model.vo.business.PickUpAppointmentConfirmVO;
import com.prolog.rdc.tms.app.model.vo.business.PickUpAppointmentShipbillVO;
import com.prolog.rdc.tms.app.model.vo.business.PickUpAppointmentVO;
import com.prolog.rdc.tms.app.model.vo.business.ShipbillOperateLogSaveVO;
import com.prolog.rdc.tms.app.service.business.AppointmentService;
import com.prolog.rdc.tms.app.service.business.ShipbillOperateLogService;
import com.prolog.rdc.tms.model.dto.basicData.TmsBaseBranchApTimeDTO;
import com.prolog.rdc.tms.model.dto.basicData.TmsBaseBranchDTO;
import com.prolog.rdc.tms.rmi.feign.MaindataFeign;

import cn.hutool.core.date.DateUtil;

/**
 * 
 *
 * 待预约实现层
 *
 * @className :AppointmentServiceImpl
 * @author :
 * @creationTime :2022/08/10
 * @description :
 *
 * @modifier :
 * @modifyTime :2022/08/10
 * @reviseRemarks:
 *
 * @version :1.0.0
 *
 */
@Service
public class AppointmentServiceImpl implements AppointmentService {

	@Autowired
	private TmsLoadingBillDetailMapper tmsLoadingBillDetailMapper;

	@Autowired
	private TmsLoadingBillHeaderMapper tmsLoadingBillHeaderMapper;

	@Autowired
	private TmsShipbillDetailMapper tmsShipbillDetailMapper;

	@Autowired
	private MaindataFeign maindataTmsResource;

	@Autowired
	private TmsAppointmentHeaderMapper tmsAppointmentHeaderMapper;

	@Autowired
	private TmsAppointmentDetailMapper tmsAppointmentDetailMapper;

	@Autowired
	private TmsShipbillTransportLogMapper tmsShipbillTransportLogMapper;

	@Autowired
	private TmsShipbillHeaderMapper tmsShipbillHeaderMapper;

	@Autowired
	private ShipbillOperateLogService shipbillOperateLogService;

	@Autowired
	private TmsShipbillPackageMapper tmsShipbillPackageMapper;

	@Autowired
	private MaindataFeign maindataFeign;

	@Autowired
	private LoadingBillService loadingBillService;

	/**
	 * 待预约运单模式查询
	 *
	 * @param appointmentQueryVO
	 * @return
	 */
	@SuppressWarnings("resource")
	@Override
	public Page<AppointmentQueryDTO> queryAppointmentShipbill(BusinessAppointmentQueryVO appointmentQueryVO) {
		ToolKits.isParamNull(appointmentQueryVO, "待预约分页查询请求不为空");
		ToolKits.isParamNull(appointmentQueryVO.getPageNum(), "当前页码不为空");
		ToolKits.isParamNull(appointmentQueryVO.getPageSize(), "每页条数不为空");

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

		appointmentQueryVO.setUserType(user.getUserType());
		appointmentQueryVO.setEnterpriseId(user.getEnterpriseId());
		if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
			// 判断是否为部门权限
			if (user.getOwnedAllDataAuthFlag().equals(BussinessConstant.USER_DEPARTMENT_AUTH_Y)) {
				appointmentQueryVO.setDepts(user.getDepts().stream().toArray(String[]::new));
				appointmentQueryVO.setIsDept(StatusConstant.IS_DEPT_YES);
			} else {
				appointmentQueryVO.setDepts(user.getDepts().stream().toArray(String[]::new));
				appointmentQueryVO.setIsDept(StatusConstant.IS_DEPT_NO);
				// 货主
				appointmentQueryVO.setConsignors(user.getConsignors().stream().toArray(Long[]::new));
				// 客户
				appointmentQueryVO.setCustomers(user.getCustomers().stream().toArray(Long[]::new));
				// 供应商
				appointmentQueryVO.setSuppliers(user.getSuppliers().stream().toArray(Long[]::new));
				// 仓库
				appointmentQueryVO.setWsarehouses(user.getWarehouses().stream().toArray(Long[]::new));
			}
		} else {
			appointmentQueryVO.setUnitId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
		}
		PageUtils.startPage(appointmentQueryVO.getPageNum(), appointmentQueryVO.getPageSize());
		List<AppointmentQueryDTO> appointmentQueryDTOS = tmsLoadingBillDetailMapper.queryAppointmentShipbill(appointmentQueryVO);

		// 行号
		int id = 1;
		for (AppointmentQueryDTO appointmentQueryDTO : appointmentQueryDTOS) {
			appointmentQueryDTO.setId(id);
			id++;
			StringBuffer consigneeProvinceCityDistrict = new StringBuffer();
			// 目的地
			consigneeProvinceCityDistrict.append(appointmentQueryDTO.getConsigneeProvinceName());
			consigneeProvinceCityDistrict.append(appointmentQueryDTO.getConsigneeCityName());
			consigneeProvinceCityDistrict.append(appointmentQueryDTO.getConsigneeDistrictName());
			appointmentQueryDTO.setConsigneeProvinceCityDistrict(consigneeProvinceCityDistrict.toString());
			// 始发地
			StringBuffer shipperProvinceCityDistrict = new StringBuffer();
			shipperProvinceCityDistrict.append(appointmentQueryDTO.getShipperProvinceName());
			shipperProvinceCityDistrict.append(appointmentQueryDTO.getShipperCityName());
			shipperProvinceCityDistrict.append(appointmentQueryDTO.getShipperDistrictName());
			appointmentQueryDTO.setShipperProvinceCityDistrict(shipperProvinceCityDistrict.toString());

			// 仓库信息
			appointmentQueryDTO.setBranchId(appointmentQueryDTO.getShipperId());
			appointmentQueryDTO.setBranchCode(appointmentQueryDTO.getShipperCode());
			appointmentQueryDTO.setBranchName(appointmentQueryDTO.getShipperName());

			// 收货方电话
			StringBuffer tel = new StringBuffer();
			if (ToolKits.isNotEmpty(appointmentQueryDTO.getConsigneePhoneNumber())) {
				tel.append(appointmentQueryDTO.getConsigneePhoneNumber());
			} else if (ToolKits.isNotEmpty(appointmentQueryDTO.getConsigneeLandlineNumber())) {
				tel.append(appointmentQueryDTO.getConsigneeLandlineNumber());
			}
			if (ToolKits.isNotEmpty(tel.toString())) {
				appointmentQueryDTO.setConsigneeTel(tel.toString());
			}
			// 收货方类型
			if (DataDictionaryConstant.CONSIGNEE_TYPE_KH.equals(appointmentQueryDTO.getConsigneeType())) {
				// 收货方名称
				appointmentQueryDTO.setConsigneeName(appointmentQueryDTO.getConsigneeUnitName() + DataDictionaryConstant.Line_SYMBOL + appointmentQueryDTO.getConsigneeName());
			} else if (DataDictionaryConstant.CONSIGNEE_TYPE_GYS.equals(appointmentQueryDTO.getConsigneeType())) {
				// 收货方名称
				appointmentQueryDTO.setConsigneeName(appointmentQueryDTO.getConsigneeName() + DataDictionaryConstant.Line_SYMBOL + appointmentQueryDTO.getShipperName());
			}

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

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

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

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

				List<ShipBillDetailDTO> detailDTOList = Lists.newArrayList();
				for (TmsShipbillDetailModel detailModel : tmsShipbillDetailModels) {
					ShipBillDetailDTO detailDTO = new ShipBillDetailDTO();
					BeanUtils.copyProperties(detailModel, detailDTO);
					detailDTOList.add(detailDTO);
				}
				// 商品信息
				appointmentQueryDTO.setShipBillDetailDTOS(detailDTOList);
			}
		}

		// 分页重组
		Page<AppointmentQueryDTO> page = PageUtils.getPage(appointmentQueryDTOS);
		if (appointmentQueryDTOS instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<AppointmentQueryDTO> p0 = (com.github.pagehelper.Page<AppointmentQueryDTO>) appointmentQueryDTOS;
			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 appointmentQueryVO
	 * @return
	 */
	@Override
	public Page<AppointmentQueryDTO> queryAppointmentLoadBill(BusinessAppointmentQueryVO appointmentQueryVO) {
		ToolKits.isParamNull(appointmentQueryVO, "待预约派车单模式查询请求不为空");
		ToolKits.isParamNull(appointmentQueryVO.getPageNum(), "当前页码不为空");
		ToolKits.isParamNull(appointmentQueryVO.getPageSize(), "每页条数不为空");
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		appointmentQueryVO.setUserType(user.getUserType());
		appointmentQueryVO.setEnterpriseId(user.getEnterpriseId());
		if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
			// 判断是否为部门权限
			if (user.getOwnedAllDataAuthFlag().equals(BussinessConstant.USER_DEPARTMENT_AUTH_Y)) {
				appointmentQueryVO.setDepts(user.getDepts().stream().toArray(String[]::new));
				appointmentQueryVO.setIsDept(StatusConstant.IS_DEPT_YES);
			} else {
				appointmentQueryVO.setDepts(user.getDepts().stream().toArray(String[]::new));
				appointmentQueryVO.setIsDept(StatusConstant.IS_DEPT_NO);
				// 货主
				appointmentQueryVO.setConsignors(user.getConsignors().stream().toArray(Long[]::new));
				// 客户
				appointmentQueryVO.setCustomers(user.getCustomers().stream().toArray(Long[]::new));
				// 供应商
				appointmentQueryVO.setSuppliers(user.getSuppliers().stream().toArray(Long[]::new));
				// 仓库
				appointmentQueryVO.setWsarehouses(user.getWarehouses().stream().toArray(Long[]::new));
			}
		} else {
			appointmentQueryVO.setUnitId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
		}
		PageUtils.startPage(appointmentQueryVO.getPageNum(), appointmentQueryVO.getPageSize());
		List<AppointmentQueryDTO> appointmentQueryDTOS = tmsLoadingBillDetailMapper.queryAppointmentLoadBill(appointmentQueryVO);
		// 行号
		int id = 1;
		for (AppointmentQueryDTO appointmentQueryDTO : appointmentQueryDTOS) {
			appointmentQueryDTO.setId(id);
			id++;
			StringBuffer consigneeProvinceCityDistrict = new StringBuffer();
			// 目的地
			consigneeProvinceCityDistrict.append(appointmentQueryDTO.getConsigneeProvinceName());
			consigneeProvinceCityDistrict.append(appointmentQueryDTO.getConsigneeCityName());
			consigneeProvinceCityDistrict.append(appointmentQueryDTO.getConsigneeDistrictName());
			appointmentQueryDTO.setConsigneeProvinceCityDistrict(consigneeProvinceCityDistrict.toString());
			// 始发地
			StringBuffer shipperProvinceCityDistrict = new StringBuffer();
			shipperProvinceCityDistrict.append(appointmentQueryDTO.getShipperProvinceName());
			shipperProvinceCityDistrict.append(appointmentQueryDTO.getShipperCityName());
			shipperProvinceCityDistrict.append(appointmentQueryDTO.getShipperDistrictName());
			appointmentQueryDTO.setShipperProvinceCityDistrict(shipperProvinceCityDistrict.toString());
			// 仓库信息
			appointmentQueryDTO.setBranchId(appointmentQueryDTO.getShipperId());
			appointmentQueryDTO.setBranchCode(appointmentQueryDTO.getShipperCode());
			appointmentQueryDTO.setBranchName(appointmentQueryDTO.getShipperName());
			// 收货方电话
			StringBuffer tel = new StringBuffer();
			if (ToolKits.isNotEmpty(appointmentQueryDTO.getConsigneePhoneNumber())) {
				tel.append(appointmentQueryDTO.getConsigneePhoneNumber());
			} else if (ToolKits.isNotEmpty(appointmentQueryDTO.getConsigneeLandlineNumber())) {
				tel.append(appointmentQueryDTO.getConsigneeLandlineNumber());
			}
			if (ToolKits.isNotEmpty(tel.toString())) {
				appointmentQueryDTO.setConsigneeTel(tel.toString());
			}
			// 收货方类型
			if (DataDictionaryConstant.CONSIGNEE_TYPE_KH.equals(appointmentQueryDTO.getConsigneeType())) {
				// 收货方名称
				appointmentQueryDTO.setConsigneeName(appointmentQueryDTO.getConsigneeUnitName() + DataDictionaryConstant.Line_SYMBOL + appointmentQueryDTO.getConsigneeName());
			} else if (DataDictionaryConstant.CONSIGNEE_TYPE_GYS.equals(appointmentQueryDTO.getConsigneeType())) {
				// 收货方名称
				appointmentQueryDTO.setConsigneeName(appointmentQueryDTO.getConsigneeName() + DataDictionaryConstant.Line_SYMBOL + appointmentQueryDTO.getShipperName());
			}
			// 获取包裹信息
			Criteria criteriaPkg = Criteria.forClass(TmsShipbillPackageModel.class);
			Restriction r1 = Restrictions.in(TmsShipbillPackageModel::getShipbillId, appointmentQueryDTO.getShipbillId().split(","));
			Restriction r2 = Restrictions.eq(TmsShipbillPackageModel::getEnterpriseId, user.getEnterpriseId());
			criteriaPkg.setRestriction(Restrictions.and(r1, r2));
			criteriaPkg.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));
			List<TmsShipbillPackageModel> tmsShipbillPackageModels = tmsShipbillPackageMapper.findByCriteria(criteriaPkg);
			List<AppLoadingPackageDTO> loadingPackageDTOList = Lists.newArrayList();
			for (TmsShipbillPackageModel packageModel : tmsShipbillPackageModels) {
				AppLoadingPackageDTO packageDTO = new AppLoadingPackageDTO();
				BeanUtils.copyProperties(packageModel, packageDTO);
				loadingPackageDTOList.add(packageDTO);
			}
			appointmentQueryDTO.setAppLoadingPackageDTOS(loadingPackageDTOList);
			if (loadingPackageDTOList.size() == 0) {
				// 获取商品信息
				Criteria criteriaDetail = Criteria.forClass(TmsShipbillDetailModel.class);
				criteriaDetail.setRestriction(Restrictions.and(r1, r2));
				criteriaDetail.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));
				List<TmsShipbillDetailModel> tmsShipbillDetailModels = tmsShipbillDetailMapper.findByCriteria(criteriaDetail);
				List<ShipBillDetailDTO> detailDTOList = Lists.newArrayList();
				for (TmsShipbillDetailModel detailModel : tmsShipbillDetailModels) {
					ShipBillDetailDTO detailDTO = new ShipBillDetailDTO();
					BeanUtils.copyProperties(detailModel, detailDTO);
					detailDTOList.add(detailDTO);
				}
				// 商品信息
				appointmentQueryDTO.setShipBillDetailDTOS(detailDTOList);
			}
		}
		return PageUtils.getPage(appointmentQueryDTOS);
	}

	/**
	 * 提货预约
	 *
	 * @param appointmentVO
	 * @return
	 */
	@Override
	public PickUpAppointmentDTO pickUpAppointmentQuery(PickUpAppointmentVO appointmentVO) throws Exception {

		ToolKits.isParamNull(appointmentVO, "提货预约查询请求不为空");
		ToolKits.isParamNull(appointmentVO.getBranchId(), "仓库ID不为空");
		ToolKits.isParamNull(appointmentVO.getPickUpAppointmentShipbillList(), "请先勾选运单");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		// 运单验证
		List<PickUpAppointmentShipbillVO> appointmentShipbillVOS = appointmentVO.getPickUpAppointmentShipbillList();

		int addressCnt = appointmentShipbillVOS.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(PickUpAppointmentShipbillVO::getShipperAddress))), ArrayList::new)).size();
		if (addressCnt > 1) {
			throw new PrologException("请勾选相同的发货地址的运单");
		}
		int driverNameCnt = appointmentShipbillVOS.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(PickUpAppointmentShipbillVO::getDriverName))), ArrayList::new)).size();

		int plateNumCnt = appointmentShipbillVOS.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(PickUpAppointmentShipbillVO::getVehiclePlateNumber))), ArrayList::new)).size();
		if (driverNameCnt > 1 || plateNumCnt > 1) {
			throw new PrologException("请勾选相同司机、车辆的运单");
		}

		List<PickUpAppointmentShipbillVO> appointmentShipbillVOList = appointmentShipbillVOS.stream().filter(o -> ToolKits.isNotEmpty(o.getEstimatedPickupStartTime())).collect(Collectors.toList());
		if (appointmentShipbillVOList.size() == appointmentShipbillVOS.size()) {
			Set<String> set1 = appointmentShipbillVOS.stream().map(vo -> DateUtil.format(vo.getEstimatedPickupStartTime(), "yyyy-MM-dd")).collect(Collectors.toSet());
			if (set1.size() > 1) {
				throw new PrologException("请勾选相同的提货时间的运单");
			}
		}
		List<String> shipBillIds = Lists.newArrayList();
		shipBillIds.addAll(appointmentShipbillVOS.stream().map(PickUpAppointmentShipbillVO::getShipbillId).distinct().collect(Collectors.toList()));
		List<TmsShipbillHeaderModel> shipbillHeaderModels = tmsShipbillHeaderMapper.findByIds(TmsShipbillHeaderModel.class,shipBillIds.stream().toArray(), null);
		if (ToolKits.isEmpty(shipbillHeaderModels)) {
			throw new PrologException(StrUtil.format("运单不存在"));
		}
		List<TmsShipbillHeaderModel> noTakeAndCallShipbillHeaderModels = shipbillHeaderModels.stream().filter(h->!h.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_APPOINTMENT_TN_CN)).collect(Collectors.toList());
		if (ToolKits.isNotEmpty(noTakeAndCallShipbillHeaderModels) && noTakeAndCallShipbillHeaderModels.size() != shipBillIds.size()) {
			throw new PrologException("请勾选相同预约流程的运单");
		}
		List<TmsShipbillHeaderModel> hasTakeAndCallShipbillHeaderModels = shipbillHeaderModels.stream().filter(h->h.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_APPOINTMENT_TN_CN)).collect(Collectors.toList());
		if (ToolKits.isNotEmpty(hasTakeAndCallShipbillHeaderModels) && hasTakeAndCallShipbillHeaderModels.size() != shipBillIds.size()) {
			throw new PrologException("请勾选相同预约流程的运单");
		}

		TmsBaseBranchDTO tmsBaseBranchDTO = new TmsBaseBranchDTO();
		PickUpAppointmentDTO pickUpAppointmentDTO = new PickUpAppointmentDTO();
		BeanUtils.copyProperties(appointmentVO, pickUpAppointmentDTO);
		BeanUtils.copyProperties(appointmentShipbillVOS.get(0), pickUpAppointmentDTO);
		RestMessage<TmsBaseBranchDTO> restMessageData = maindataTmsResource.viewBranch(appointmentVO.getBranchId());
		if (!restMessageData.isSuccess()) {
			throw new RuntimeException("获取仓库的预约信息失败!");
		} else {
			tmsBaseBranchDTO = restMessageData.getData();
		}
		if (ObjectUtil.isNull(tmsBaseBranchDTO.getAptNum())) {
			throw new BizException("仓库【"+tmsBaseBranchDTO.getName()+"】没有设置班次允许预约数");
		}
		List<Date> aptDateList = Lists.newArrayList();
		Date nonAptSpecStartDate = tmsBaseBranchDTO.getNonAptSpecStartDate();
		Date nonAptSpecEndDate = tmsBaseBranchDTO.getNonAptSpecEndDate();

		String nonAptWeek = null;
		String nonAptMonth = null;
		if (DataDictionaryConstant.NON_ABL_DT_WK.equals(tmsBaseBranchDTO.getNonAptDt())) {
			// 不可预约日期 按周
			nonAptWeek = tmsBaseBranchDTO.getNonAptDura();
		} else if (DataDictionaryConstant.NON_ABL_DT_MT.equals(tmsBaseBranchDTO.getNonAptDt())) {
			// 不可预约日期 按月
			nonAptMonth = tmsBaseBranchDTO.getNonAptDura();
		}

		// 一周内可预约的日期
		Date currentDt = DateUtil.date();
		while (aptDateList.size() < 7) {
			if (ToolKits.isNotEmpty(nonAptSpecStartDate) && ToolKits.isNotEmpty(nonAptSpecEndDate) && DateUtil.compare(currentDt, nonAptSpecStartDate) >= 0 && DateUtil.compare(currentDt, nonAptSpecEndDate) < 0) {
				currentDt = DateUtil.offsetDay(nonAptSpecEndDate, 1);
				continue;

			}
			if (ToolKits.isNotEmpty(nonAptMonth) && nonAptMonth.contains(DateUtil.format(currentDt, "dd"))) {
				currentDt = DateUtil.offsetDay(currentDt, 1);
				continue;
			}
			if (ToolKits.isNotEmpty(nonAptWeek) && nonAptWeek.contains(String.valueOf(DateUtil.dayOfWeek(currentDt)))) {
				currentDt = DateUtil.offsetDay(currentDt, 1);
				continue;
			}
			aptDateList.add(currentDt);
			currentDt = DateUtil.offsetDay(currentDt, 1);
		}
		// 已经预约次数取得
		AppointmentHeadQueryVO queryVO = new AppointmentHeadQueryVO();
		queryVO.setBranchId(appointmentVO.getBranchId());
		queryVO.setAppointmentType(DataDictionaryConstant.APPOINTMENT_TYPE_TH);
		List<BranchAppointmentInfoDTO> appointmentInfoDTOS = tmsAppointmentHeaderMapper.queryBranchAppointmentInfo(queryVO);

		Map<String, Integer> appInfoMap = Maps.newHashMap();
		for (BranchAppointmentInfoDTO infoDTO : appointmentInfoDTOS) {
			String appedDt = DateUtil.format(infoDTO.getAppointmentDate(), "yyyy-MM-dd");
			appInfoMap.put(appedDt + infoDTO.getAppointmentTime(), infoDTO.getAppointmentCnt());
		}

		// 一周的预约信息
		List<AppointmentWeekDTO> weekDTOS = Lists.newArrayList();
		// STD-DEVELOP20220823 lhb JC_CK_001仓库预约时间段可以输入分钟的需求 20220823 start
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		// STD-DEVELOP20220823 lhb JC_CK_001仓库预约时间段可以输入分钟的需求 20220823 end
		for (Date dt : aptDateList) {
			AppointmentWeekDTO weekDTO = new AppointmentWeekDTO();
			weekDTO.setAptWeek(DateUtil.dayOfWeekEnum(dt).toChinese().replace("星期", "周"));
			String aliAppDt = DateUtil.format(dt, "yyyy-MM-dd");
			weekDTO.setAptDate(aliAppDt);

			// 可预约时间段 可预约次数
			List<AppointmentTimesDTO> appointmentTimesDTOS = Lists.newArrayList();
			for (TmsBaseBranchApTimeDTO apTimeDTO : tmsBaseBranchDTO.getApTimeDTOList()) {
				// 预约时间段是否过去时间
				// STD-DEVELOP20220823 lhb JC_CK_001仓库预约时间段可以输入分钟的需求 20220823 start
				String currentDtStr = DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm");
				// STD-DEVELOP20220823 lhb JC_CK_001仓库预约时间段可以输入分钟的需求 20220823 end
				Date currentDate1 = sdf.parse(currentDtStr);
				// STD-DEVELOP20220823 lhb JC_CK_001仓库预约时间段可以输入分钟的需求 20220823 start
				Date lastDt = sdf.parse(aliAppDt + " " + apTimeDTO.getEndTime());
				// STD-DEVELOP20220823 lhb JC_CK_001仓库预约时间段可以输入分钟的需求 20220823 end
				if (lastDt.before(currentDate1)) {
					continue;
				}

				AppointmentTimesDTO timesDTO = new AppointmentTimesDTO();
				String appDura = apTimeDTO.getStartTime() + "-" + apTimeDTO.getEndTime();
				timesDTO.setAppDura(appDura);
				if (ToolKits.isNotEmpty(appointmentInfoDTOS)) {
					Integer appedCnt = appInfoMap.get(aliAppDt + appDura);
					if (ToolKits.isNotEmpty(appedCnt)) {
						int aliCnt = 0;
						if (tmsBaseBranchDTO.getAptNum().intValue() - appedCnt.intValue() > 0) {
							aliCnt = tmsBaseBranchDTO.getAptNum().intValue() - appedCnt.intValue();
						}
						timesDTO.setAppAliCnt(aliCnt);
						timesDTO.setAppedCnt(appedCnt);
					} else {
						timesDTO.setAppAliCnt(tmsBaseBranchDTO.getAptNum());
						timesDTO.setAppedCnt(0);
					}
				} else {
					timesDTO.setAppAliCnt(tmsBaseBranchDTO.getAptNum());
					timesDTO.setAppedCnt(0);
				}
				appointmentTimesDTOS.add(timesDTO);
			}
			weekDTO.setAppointmentTimes(appointmentTimesDTOS);

			weekDTOS.add(weekDTO);
		}
		pickUpAppointmentDTO.setAppointmentWeeks(weekDTOS);

		Integer totalPcs = 0;

		List<String> shipbillIds = Lists.newArrayList();
		for (PickUpAppointmentShipbillVO vo : appointmentShipbillVOS) {
			totalPcs = totalPcs + (ToolKits.isEmpty(vo.getTotalPcs()) ? 0 : vo.getTotalPcs().intValue());
			shipbillIds.add(vo.getShipbillId());
		}
		pickUpAppointmentDTO.setTotalPcs(new BigDecimal(totalPcs.intValue()));
		pickUpAppointmentDTO.setShipbillQuantity(appointmentShipbillVOS.size());
		pickUpAppointmentDTO.setShipbillIds(shipbillIds.stream().collect(Collectors.joining(",")));
		pickUpAppointmentDTO.setLoadingBillId(loadingBillService.getLoadingBillIdsByShipBillIds(shipbillIds).stream().collect(Collectors.joining(",")));
		pickUpAppointmentDTO.setIsWeigh(0);
		if (ToolKits.isNotEmpty(pickUpAppointmentDTO.getLoadingBillId())) {
			List<TmsLoadingBillHeaderModel> loadingBillHeaders = tmsLoadingBillHeaderMapper.findByIds(TmsLoadingBillHeaderModel.class, pickUpAppointmentDTO.getLoadingBillId().split(","),null);
			if (ToolKits.isNotEmpty(loadingBillHeaders) && loadingBillHeaders.stream().anyMatch(h->DataDictionaryConstant.WHETHER_YES.equals(h.getIsWeigh()))) {
				pickUpAppointmentDTO.setIsWeigh(1);
			}
		}
		return pickUpAppointmentDTO;
	}

	/**
	 * 提货预约确认
	 *
	 * @param confirmVO
	 * @return
	 */
	@Override
	public void pickUpAppointmentConfirm(PickUpAppointmentConfirmVO confirmVO) throws Exception {
		ToolKits.isParamNull(confirmVO, "提货预约确认请求不为空");
		ToolKits.isParamNull(confirmVO.getBranchId(), "仓库ID不为空");
		ToolKits.isParamNull(confirmVO.getAppointmentDate(), "预约日期不为空");
		ToolKits.isParamNull(confirmVO.getAppointmentTime(), "预约时间段不为空");
		ToolKits.isParamNull(confirmVO.getShipperAddress(), "预约提货地址不为空");
		ToolKits.isParamNull(confirmVO.getShipbillIds(), "预约运单ID不为空");

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

		Date date = DateUtil.date();
		// 预约时间校验
		TmsBaseBranchDTO tmsBaseBranchDTO = new TmsBaseBranchDTO();
		RestMessage<TmsBaseBranchDTO> restMessageData = maindataTmsResource.viewBranch(confirmVO.getBranchId());
		if (!restMessageData.isSuccess()) {
			throw new RuntimeException("获取仓库的预约信息失败!");
		} else {
			tmsBaseBranchDTO = restMessageData.getData();
		}
		// 运输记录表数据查询
		Criteria criteriaTransLog = Criteria.forClass(TmsShipbillTransLogModel.class);
		Restriction r1 = Restrictions.eq(TmsShipbillTransLogModel::getEnterpriseId, user.getEnterpriseId());
		Restriction r2 = null;
		Integer aptTimeType = tmsBaseBranchDTO.getAptTime();
		Integer aptTimeUnit = tmsBaseBranchDTO.getAptUnit();

		Date appDt = confirmVO.getAppointmentDate();
		String appTime = confirmVO.getAppointmentTime();
		// 可预约的时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date aliAppDtStart = null;
		Date aliAppDtEnd = null;

		String appDtStr = DateUtil.format(appDt, "yyyy-MM-dd");

		Date appTimeStart = sdf.parse(appDtStr + " " + appTime.substring(0, 5));
		Date appTimeEnd = sdf.parse(appDtStr + " " + appTime.substring(6));

		int jiaJiCnt = 0;
		List<TmsShipbillHeaderModel> headerModelList = Lists.newArrayList();
		for (String shipbillId : confirmVO.getShipbillIds().split(",")) {
			r2 = Restrictions.eq(TmsShipbillTransLogModel::getShipbillId, shipbillId);

			criteriaTransLog.setRestriction(Restrictions.and(r1, r2));
			List<TmsShipbillTransLogModel> tmsShipbillTransLogModels = tmsShipbillTransportLogMapper.findByCriteria(criteriaTransLog);

			if (ToolKits.isEmpty(tmsShipbillTransLogModels)) {
				throw new PrologException("预约时间不在仓库【" + confirmVO.getBranchName() + "】的可预约时间段内");
			} else {
				TmsShipbillTransLogModel logModel = tmsShipbillTransLogModels.get(0);
				if (DataDictionaryConstant.AVAILABLE_TIME_PICK_UP.equals(aptTimeType)) {
					aliAppDtStart = logModel.getEstimatedPickupStartTime();
				} else if (DataDictionaryConstant.AVAILABLE_TIME_ORDER.equals(aptTimeType)) {
					aliAppDtStart = logModel.getOrderDt();
				} else if (DataDictionaryConstant.AVAILABLE_TIME_COMMIT.equals(aptTimeType)) {
					aliAppDtStart = logModel.getCommitDt();
				} else if (DataDictionaryConstant.AVAILABLE_TIME_REVIEW.equals(aptTimeType)) {
					aliAppDtStart = logModel.getReviewDt();
				} else if (DataDictionaryConstant.AVAILABLE_TIME_DISPATCH.equals(aptTimeType)) {
					aliAppDtStart = logModel.getDisDt();
				} else if (DataDictionaryConstant.AVAILABLE_TIME_DISPATCH_CHECK.equals(aptTimeType)) {
					aliAppDtStart = logModel.getDisCheckDt();
				}
				if (ToolKits.isNotEmpty(aliAppDtStart)) {
					if (ToolKits.isNotEmpty(aptTimeUnit) && DataDictionaryConstant.AVAILABLE_UNIT_HOUR.equals(aptTimeUnit)) {
						aliAppDtEnd = DateUtil.offsetHour(aliAppDtStart, tmsBaseBranchDTO.getAptTimeDura().intValue());
					} else if (ToolKits.isNotEmpty(aptTimeUnit) && DataDictionaryConstant.AVAILABLE_UNIT_DAY.equals(aptTimeUnit)) {
						aliAppDtEnd = DateUtil.offsetDay(aliAppDtStart, tmsBaseBranchDTO.getAptTimeDura().intValue());
					}

					// 预约的结束时间段 < 可预约的开始时间,或者，预约的开始时间段 > 可预约的结束时间
					if (appTimeEnd.before(aliAppDtStart) || appTimeStart.after(aliAppDtEnd)) {
						throw new PrologException("预约时间不在仓库【" + confirmVO.getBranchName() + "】的可预约时间段内");
					}
				}
			}

			TmsShipbillHeaderModel headerModel = tmsShipbillHeaderMapper.findById(shipbillId, TmsShipbillHeaderModel.class);
			if (ToolKits.isEmpty(headerModel)) {
				throw new PrologException("运单【" + shipbillId + "】不存在");
			}
			if (!headerModel.getStatus().equals(DataDictionaryConstant.SHIPBILL_STATUS_PENDING_APP)) {
				throw new PrologException("运单不是待预约状态，不能预约");
			}

			if (headerModel.getOrderType().intValue() > DataDictionaryConstant.ORDER_TYPE_P.intValue()) {
				jiaJiCnt++;
			}
			headerModelList.add(headerModel);
		}
		StringBuffer newNum = new StringBuffer();
		QueryMaxReserveNumberVO numberVO = new QueryMaxReserveNumberVO();
		// 预约号生成
		if (jiaJiCnt > 0) {
			numberVO.setIsJiaJi("1");
			newNum.append(DataDictionaryConstant.RESERVE_NUMBER);
		}
		String appDtStrNum = DateUtil.format(appDt, "yyyyMMdd");
		newNum.append(appDtStrNum);
		newNum.append(appTime.substring(0, 2));
		newNum.append(appTime.substring(6, 8));
		numberVO.setAppointmentDate(appDt);
		numberVO.setAppointmentTime(appTime);
		numberVO.setBranchId(String.valueOf(confirmVO.getBranchId()));
		numberVO.setAppointmentType(DataDictionaryConstant.APPOINTMENT_TYPE_TH);
		String maxReserveNumber = tmsAppointmentHeaderMapper.queryMaxReserveNumber(numberVO);

		if (ToolKits.isNotEmpty(maxReserveNumber)) {
			String oldNum = maxReserveNumber.substring(maxReserveNumber.length() - 3);
			String pattern = "[1-9]+";
			Pattern r = Pattern.compile(pattern);
			Matcher m = r.matcher(oldNum);
			if (m.find()) {
				int num = Integer.valueOf(m.group(0)).intValue() + 1;
				newNum.append(String.format("%03d", num));
			} else {
				newNum.append("001");
			}
		} else {
			newNum.append("001");
		}
		// 最大预约次数取得
		AppointmentHeadQueryVO queryVO = new AppointmentHeadQueryVO();
		queryVO.setBranchId(confirmVO.getBranchId());
		queryVO.setAppointmentDate(appDt);
		queryVO.setAppointmentType(DataDictionaryConstant.APPOINTMENT_TYPE_TH);
		queryVO.setAppointmentTime(appTime);
		List<BranchAppointmentInfoDTO> appointmentInfoDTOS = tmsAppointmentHeaderMapper.queryBranchAppointmentInfo(queryVO);
		if (ToolKits.isNotEmpty(appointmentInfoDTOS) && appointmentInfoDTOS.get(0).getAppointmentCnt().intValue() >= tmsBaseBranchDTO.getAptNum().intValue()) {
			throw new PrologException("仓库【" + confirmVO.getBranchName() + "】的预约时间段" + appDtStrNum + appTime + "已约满");
		}

		// 预约主表作成
		TmsAppointmentHeaderModel appointmentHeaderModel = new TmsAppointmentHeaderModel();
		BeanUtils.copyProperties(confirmVO, appointmentHeaderModel);

		// 获取预约主表ID
		RestMessage<String> restMessageId = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_APPOINTMENT_HEADER_ID, "L");
		if (!restMessageId.isSuccess()) {
			throw new RuntimeException("生成预约主表ID失败");
		}
		String id = restMessageId.getData();
		appointmentHeaderModel.setAppointmentId(id);
		appointmentHeaderModel.setAppointmentNo(id);
		appointmentHeaderModel.setAppointmentType(DataDictionaryConstant.APPOINTMENT_TYPE_TH);
		appointmentHeaderModel.setStatus(DataDictionaryConstant.APPOINTMENT_STATUS_DSH);
		appointmentHeaderModel.setReserveNumber(newNum.toString());
		appointmentHeaderModel.setReserveNumberTime(date);
		appointmentHeaderModel.setUrgentQuantity(jiaJiCnt);

		appointmentHeaderModel.setEnterpriseId(user.getEnterpriseId());
		appointmentHeaderModel.setEnterpriseName(user.getEnterpriseName());
		appointmentHeaderModel.setCreateperson(user.getNickname());
		appointmentHeaderModel.setCreatetime(date);
		appointmentHeaderModel.setBranchAddress(confirmVO.getShipperAddress());

		// 预约明细表
		for (TmsShipbillHeaderModel shipbillHeaderModel : headerModelList) {
			TmsAppointmentDetailModel appointmentDetailModel = new TmsAppointmentDetailModel();

			BeanUtils.copyProperties(shipbillHeaderModel, appointmentDetailModel);

			// 获取预约明细表ID
			RestMessage<String> restMessageDetailId = maindataTmsResource.getCodeNumberByCode(SeriaNnumberConstant.TMS_APPOINTMENT_DETAIL_ID, "L");
			if (!restMessageDetailId.isSuccess()) {
				throw new RuntimeException("生成预约明细表ID失败");
			}
			String detailId = restMessageDetailId.getData();
			appointmentDetailModel.setId(detailId);
			appointmentDetailModel.setAppointmentId(id);
			appointmentDetailModel.setAppointmentNo(id);
			appointmentDetailModel.setStatus(DataDictionaryConstant.SHIPBILL_STATUS_APP_ING);

			appointmentDetailModel.setEnterpriseId(user.getEnterpriseId());
			appointmentDetailModel.setEnterpriseName(user.getEnterpriseName());
			appointmentDetailModel.setCreateperson(user.getNickname());
			appointmentDetailModel.setCreatetime(date);


			// 更新运单状态 为预约中
			Map<String, Object> mapUpdate = Maps.newHashMap();
			mapUpdate.put("status", DataDictionaryConstant.SHIPBILL_STATUS_APP_ING);
			mapUpdate.put("updateperson", user.getNickname());
			mapUpdate.put("updatetime", date);
			tmsShipbillHeaderMapper.updateMapById(shipbillHeaderModel.getShipbillId(), mapUpdate, TmsShipbillHeaderModel.class);

			// 更新装车单明细状态 为预约中
			Criteria criteriaLoadingBillDetail = Criteria.forClass(TmsLoadingBillDetailModel.class);
			Restriction r4 = Restrictions.eq(TmsLoadingBillDetailModel::getEnterpriseId, user.getEnterpriseId());
			Restriction r5 = Restrictions.eq(TmsLoadingBillDetailModel::getShipbillId, shipbillHeaderModel.getShipbillId());
			Restriction r6 = Restrictions.eq(TmsLoadingBillDetailModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_PENDING_APP);
			criteriaLoadingBillDetail.setRestriction(Restrictions.and(r4, r5, r6));
			criteriaLoadingBillDetail.setOrder(Order.newInstance().desc(new String[] { "createtime" }));
			List<TmsLoadingBillDetailModel> tmsLoadingBillDetails = tmsLoadingBillDetailMapper.findByCriteria(criteriaLoadingBillDetail);
			if (ToolKits.isEmpty(tmsLoadingBillDetails)) {
				throw new PrologException("装车单明细【" + shipbillHeaderModel.getShipbillId() + "】查询失败");
			}
			TmsLoadingBillDetailModel tmsLoadingBillDetail = tmsLoadingBillDetails.get(0);
			appointmentDetailModel.setLoadingBillId(tmsLoadingBillDetail.getLoadingBillId());
			tmsAppointmentDetailMapper.save(appointmentDetailModel);
			tmsLoadingBillDetailMapper.updateMapById(tmsLoadingBillDetail.getId(), mapUpdate, TmsLoadingBillDetailModel.class);

			// 日志表
			ShipbillOperateLogSaveVO shipbillOperateLogSaveVO = new ShipbillOperateLogSaveVO();
			shipbillOperateLogSaveVO.setShipbillId(shipbillHeaderModel.getShipbillId());
			shipbillOperateLogSaveVO.setShipbillNo(shipbillHeaderModel.getShipbillId());
			shipbillOperateLogSaveVO.setOperateEvent(DataDictionaryConstant.SHIPBILL_STATUSNAME_YYQR);
			shipbillOperateLogSaveVO.setOldStatus(DataDictionaryConstant.SHIPBILL_STATUS_DISPATCH_CHECK);
			shipbillOperateLogSaveVO.setNewStatus(DataDictionaryConstant.SHIPBILL_STATUS_APP_ING);
			shipbillOperateLogService.addShipbillOperateLogData(shipbillOperateLogSaveVO);
		}

		appointmentHeaderModel.setTallyStatus(DataDictionaryConstant.TALLY_STATUS_WLH);
		appointmentHeaderModel.setCreateMode(getQueryType());
		tmsAppointmentHeaderMapper.save(appointmentHeaderModel);
		MessageUtil.addMessage(new SendMessageDTO(MessageOrderTypeEnum.SHIP_NO.getCode(), MessageTypeEnum.APPOINTMENT.getCode(), Lists.newArrayList(confirmVO.getShipbillIds().split(","))));
	}

	private String getQueryType() {
		RestMessage<SysParamConfigModel> restMessage = maindataFeign.getValue(DataDictionaryConstant.APPOINTMENT_SHOW);
		if (!restMessage.isSuccess()) {
			throw new BizException("查询系统参数【"+DataDictionaryConstant.APPOINTMENT_SHOW+"】错误，" + restMessage.getMessage());
		}
		if (ObjectUtil.isNull(restMessage.getData())) {
			throw new BizException("查询系统参数【"+DataDictionaryConstant.APPOINTMENT_SHOW+"】为空");
		}
		return restMessage.getData().getValue();
	}

	// STD-DEVELOP20220823 lhb 预约运单详情 20220831 start
	/**
	 * 预约运单详情查询
	 *
	 * @param appointmentQueryVO
	 * @return
	 */
	@Override
	public Page<AppointmentQueryDTO> queryShipbillInfo(AppointmentShipbillQueryVO appointmentQueryVO) {
		ToolKits.isParamNull(appointmentQueryVO, "预约运单查询请求不为空");
		ToolKits.isParamNull(appointmentQueryVO.getPageNum(), "当前页码不为空");
		ToolKits.isParamNull(appointmentQueryVO.getPageSize(), "每页条数不为空");
		ToolKits.isParamNull(appointmentQueryVO.getShipbillIds(), "运单ID不为空");

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

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

		// 添加
		PageUtils.startPage(appointmentQueryVO.getPageNum(), appointmentQueryVO.getPageSize());
		List<TmsShipbillHeaderModel> tmsShipbillHeaderModels = tmsShipbillHeaderMapper.findByIds(TmsShipbillHeaderModel.class, appointmentQueryVO.getShipbillIds().split(","), null);

		// 响应对象集合
		List<AppointmentQueryDTO> appointmentShipbills = Lists.newArrayList();

		for (TmsShipbillHeaderModel tmsShipbillHeaderModel : tmsShipbillHeaderModels) {
			AppointmentQueryDTO appointmentShipbillDTO = new AppointmentQueryDTO();
			BeanUtils.copyProperties(tmsShipbillHeaderModel, appointmentShipbillDTO);
			appointmentShipbillDTO.setLoadingBillId(loadingBillService.getLoadingBillIdByShipBillId(tmsShipbillHeaderModel.getShipbillId()));

			StringBuffer consigneeProvinceCityDistrict = new StringBuffer();
			// 目的地
			consigneeProvinceCityDistrict.append(ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeProvinceName()) ? "" : tmsShipbillHeaderModel.getConsigneeProvinceName());
			consigneeProvinceCityDistrict.append(ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeCityName()) ? "" : tmsShipbillHeaderModel.getConsigneeCityName());
			consigneeProvinceCityDistrict.append(ToolKits.isEmpty(tmsShipbillHeaderModel.getConsigneeDistrictName()) ? "" : tmsShipbillHeaderModel.getConsigneeDistrictName());
			appointmentShipbillDTO.setConsigneeProvinceCityDistrict(consigneeProvinceCityDistrict.toString());
			// 始发地
			StringBuffer shipperProvinceCityDistrict = new StringBuffer();
			shipperProvinceCityDistrict.append(ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperProvinceName()) ? "" : tmsShipbillHeaderModel.getShipperProvinceName());
			shipperProvinceCityDistrict.append(ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperCityName()) ? "" : tmsShipbillHeaderModel.getShipperCityName());
			shipperProvinceCityDistrict.append(ToolKits.isEmpty(tmsShipbillHeaderModel.getShipperDistrictName()) ? "" : tmsShipbillHeaderModel.getShipperDistrictName());
			appointmentShipbillDTO.setShipperProvinceCityDistrict(shipperProvinceCityDistrict.toString());

			// 发货方类型
			if (DataDictionaryConstant.SHIPPER_TYPE_KH.equals(appointmentShipbillDTO.getShipperType())) {
				// 发货方名称
				appointmentShipbillDTO.setShipperName(appointmentShipbillDTO.getShipperUnitName() + DataDictionaryConstant.Line_SYMBOL + appointmentShipbillDTO.getShipperName());
			}

			// 收货方电话
			StringBuffer tel = new StringBuffer();
			if (ToolKits.isNotEmpty(appointmentShipbillDTO.getConsigneeLandlineNumber()) && ToolKits.isNotEmpty(appointmentShipbillDTO.getConsigneePhoneNumber())) {
				tel.append(appointmentShipbillDTO.getConsigneeLandlineNumber());
				tel.append(DataDictionaryConstant.Line_SYMBOL);
				tel.append(appointmentShipbillDTO.getConsigneePhoneNumber());
			} else if (ToolKits.isNotEmpty(appointmentShipbillDTO.getConsigneeLandlineNumber())) {
				tel.append(appointmentShipbillDTO.getConsigneeLandlineNumber());
			} else if (ToolKits.isNotEmpty(appointmentShipbillDTO.getConsigneePhoneNumber())) {
				tel.append(appointmentShipbillDTO.getConsigneePhoneNumber());
			}
			if (ToolKits.isNotEmpty(tel.toString())) {
				appointmentShipbillDTO.setConsigneeTel(tel.toString());
			}

			// 收货方类型
			if (DataDictionaryConstant.CONSIGNEE_TYPE_KH.equals(appointmentShipbillDTO.getConsigneeType())) {
				// 收货方名称
				appointmentShipbillDTO.setConsigneeName(appointmentShipbillDTO.getConsigneeUnitName() + DataDictionaryConstant.Line_SYMBOL + appointmentShipbillDTO.getConsigneeName());
			} else if (DataDictionaryConstant.CONSIGNEE_TYPE_GYS.equals(appointmentShipbillDTO.getConsigneeType())) {
				// 收货方名称
				appointmentShipbillDTO.setConsigneeName(appointmentShipbillDTO.getConsigneeName() + DataDictionaryConstant.Line_SYMBOL + appointmentShipbillDTO.getShipperName());
			}

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

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

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

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

				List<ShipBillDetailDTO> detailDTOList = Lists.newArrayList();
				for (TmsShipbillDetailModel detailModel : tmsShipbillDetailModels) {
					ShipBillDetailDTO detailDTO = new ShipBillDetailDTO();
					BeanUtils.copyProperties(detailModel, detailDTO);
					detailDTOList.add(detailDTO);
				}
				// 商品信息
				appointmentShipbillDTO.setShipBillDetailDTOS(detailDTOList);
			}
			appointmentShipbills.add(appointmentShipbillDTO);
		}
		// 分页重组
		Page<AppointmentQueryDTO> page = PageUtils.getPage(appointmentShipbills);
		if (tmsShipbillHeaderModels instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<TmsShipbillHeaderModel> p0 = (com.github.pagehelper.Page<TmsShipbillHeaderModel>) tmsShipbillHeaderModels;
			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;
	}
	// STD-DEVELOP20220823 lhb 预约运单详情 20220831 end
}
