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

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.prolog.rdc.tms.model.dto.basicData.*;
import com.prolog.rdc.tms.util.ConvertorUtil;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.multipart.MultipartFile;

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.cs.platform.power.model.Organization;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.BizException;
import com.prolog.framework.core.exception.ParameterException;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Order;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.framework.dao.util.PageUtils;
import com.prolog.product.core.framework.entity.UserEntity;
import com.prolog.product.core.framework.util.PlgFxUsrUtils;
import com.prolog.rdc.tms.constant.BussinessConstant;
import com.prolog.rdc.tms.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.constant.RabbitMQConstant;
import com.prolog.rdc.tms.constant.SeriaNnumberConstant;
import com.prolog.rdc.tms.constant.StatusConstant;
import com.prolog.rdc.tms.dao.mapper.LmsTmsZoneMapper;
import com.prolog.rdc.tms.dao.mapper.TmsBaseBranchMapper;
import com.prolog.rdc.tms.dao.mapper.TmsBaseCarriersMapper;
import com.prolog.rdc.tms.dao.mapper.TmsBaseCustomerMapper;
import com.prolog.rdc.tms.dao.mapper.TmsBaseDriverMapper;
import com.prolog.rdc.tms.dao.mapper.TmsBaseTranslineMapper;
import com.prolog.rdc.tms.dao.mapper.TmsBaseVehicleMapper;
import com.prolog.rdc.tms.dao.mapper.TmsCustomerConsigneeMapper;
import com.prolog.rdc.tms.dao.mapper.TmsLineCarrierLinkMapper;
import com.prolog.rdc.tms.dao.mapper.TmsLineConsigneeLinkMapper;
import com.prolog.rdc.tms.dao.mapper.TmsLineShipperLinkMapper;
import com.prolog.rdc.tms.model.dto.basicConfigure.StandardTemplateDetailsListDTO;
import com.prolog.rdc.tms.model.entity.LmsTmsZoneModel;
import com.prolog.rdc.tms.model.entity.line.TmsBaseBranchModel;
import com.prolog.rdc.tms.model.entity.line.TmsBaseCarriersModel;
import com.prolog.rdc.tms.model.entity.line.TmsBaseCustomerModel;
import com.prolog.rdc.tms.model.entity.line.TmsBaseDriverModel;
import com.prolog.rdc.tms.model.entity.line.TmsBaseLineModel;
import com.prolog.rdc.tms.model.entity.line.TmsBaseVehicleModel;
import com.prolog.rdc.tms.model.entity.line.TmsCustomerConsignee;
import com.prolog.rdc.tms.model.entity.line.TmsLineCarrierLinkModel;
import com.prolog.rdc.tms.model.entity.line.TmsLineConsigneeLinkModel;
import com.prolog.rdc.tms.model.entity.line.TmsLineShipperLinkModel;
import com.prolog.rdc.tms.model.vo.basicConfigure.ImportLogAddVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ImportPageVO;
import com.prolog.rdc.tms.model.vo.basicData.LineByCustomerQueryVO;
import com.prolog.rdc.tms.model.vo.basicData.LineMoveQueryVO;
import com.prolog.rdc.tms.model.vo.basicData.ShipbillMatchLineQueryVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsArriverRemoveVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsArriverVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsBaseCustomerReceiverQueryVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsBaseTranslineByCalculateVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsBaseTranslineByDateVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsBaseTranslineByIdsVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsBaseTranslineByQueryVo;
import com.prolog.rdc.tms.model.vo.basicData.TmsBaseTranslineBySaveVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsBaseTranslineMapDetailsVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsBaseTranslineMapVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsBaseTranslinePopVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsBaseTranslineVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsBaselineVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsCarrierVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsCarrierViewVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsLineMapSaveVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsLineMapSiteSaveVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsLineMoveSiteVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsLineMoveVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsLineShipperQueryVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsLineShipperVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsShipperRemoveVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsShipperVO;
import com.prolog.rdc.tms.model.vo.xlsimport.LineCarrierImportStdVO;
import com.prolog.rdc.tms.model.vo.xlsimport.LineConsigneeImportStdVO;
import com.prolog.rdc.tms.model.vo.xlsimport.LineShipperImportStdVO;
import com.prolog.rdc.tms.model.vo.xlsimport.TranslineImportStdVO;
import com.prolog.rdc.tms.rmi.feign.UserFeign;
import com.prolog.rdc.tms.service.SysCodeengineService;
import com.prolog.rdc.tms.service.SysRefdatadService;
import com.prolog.rdc.tms.service.basicConfigure.ImportLogService;
import com.prolog.rdc.tms.service.basicConfigure.SysImportTemplethService;
import com.prolog.rdc.tms.service.basicData.TranslineService;
import com.prolog.rdc.tms.util.FileUtils;
import com.prolog.rdc.tms.util.ImportUtils;
import com.prolog.rdc.tms.util.PublicMethods;
import com.prolog.wms.base.util.ExcelUtils;
import com.prolog.wms.base.util.JsonMapper;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 基础数据-线路管理实现层
 *
 * @author :fanzw
 * @version :1.0.0
 * @className :TranslineServiceImpl
 * @creationTime :2022/03/31
 * @description :
 * @modifier :fanzw
 * @modifyTime :2022/03/31
 * @reviseRemarks:
 */
@Slf4j
@Service
public class TranslineServiceImpl implements TranslineService {

    @Autowired
    private TmsBaseTranslineMapper tmsBaseTranslineMapper;

    @Autowired
    PlatformTransactionManager transactionManager;

    @Autowired
    private SysCodeengineService sysCodeengineService;

    @Autowired
    private TmsCustomerConsigneeMapper tmsCustomerConsigneeMapper;

    @Autowired
    private TmsBaseBranchMapper tmsBaseBranchMapper;

    @Autowired
    private SysImportTemplethService sysImportTemplethService;

    @Autowired
    private ImportLogService importLogService;

    @Autowired
    private SysRefdatadService sysRefdatadService;

    @Autowired
    private TmsBaseCustomerMapper tmsBaseCustomerMapper;

    @Autowired
    private TmsLineConsigneeLinkMapper tmsLineConsigneeLinkMapper;

    @Autowired
    private TmsLineCarrierLinkMapper tmsLineCarrierLinkMapper;

    @Autowired
    private TmsBaseCarriersMapper tmsBaseCarriersMapper;

    @Autowired
    private TmsBaseDriverMapper tmsBaseDriverMapper;

    @Autowired
    private TmsBaseVehicleMapper tmsBaseVehicleMapper;

    @Autowired
    private UserFeign userTmsResource;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private TmsLineShipperLinkMapper tmsLineShipperLinkMapper;

    @Autowired
    private LmsTmsZoneMapper lmsTmsZoneMapper;

    /**
     * 分页查询
     *
     * @param vo
     * @return
     */
    @SuppressWarnings("resource")
    @Override
    public Page<TmsBaseTranslineDTO> query(TmsBaseTranslineByQueryVo vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");

        ToolKits.isParamNull(vo, "参数不能为空！");
        ToolKits.isParamNull(vo.getPageNum(), "当前页码不能为空");
        ToolKits.isParamNull(vo.getPageSize(), "每页条数不能为空");

        // 翻译字典
        List<String> params = Lists.newArrayList(DataDictionaryConstant.MAINDATA_STATUS, // 线路状态
                DataDictionaryConstant.LINE_TYPE, // 线路类型
                DataDictionaryConstant.DISTINGUISH_TYPE, // 划分类型
                DataDictionaryConstant.LINE_DIRECTION, //线路方向
                DataDictionaryConstant.LINE_BASIS, // 限制依据
                DataDictionaryConstant.MILEAGE_MANAGEMENT, // 是否承运方份额限制
                DataDictionaryConstant.LINE_CARRIER_TYPE,// 承运方类型
                DataDictionaryConstant.START_LINE_TYPE); // 线路起点类型
        Map<String, Object> dicData = ConvertorUtil.listDropDownData(sysRefdatadService, params);

        vo.setEnterpriseId(user.getEnterpriseId());
        // 权限控制
        // 判断账号类型
        if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
            vo.setIsDept("Y");
            // 自有账号
            vo.setDepartmentIds(user.getDepts().stream().toArray(String[]::new));
        } else {
            throw new BizException("当前人员没有操作权限！");
        }
        PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
        List<TmsBaseTranslineDTO> tmsBaseTranslineModels = tmsBaseTranslineMapper.query(vo);

        List<TmsBaseTranslineDTO> dtoList = Lists.newArrayList();
        for (TmsBaseTranslineDTO model : tmsBaseTranslineModels) {
            TmsBaseTranslineDTO dto = new TmsBaseTranslineDTO();
            BeanUtils.copyProperties(model, dto);

            dto.setStatusName(ConvertorUtil.getName(dicData, DataDictionaryConstant.MAINDATA_STATUS, String.valueOf(model.getStatus())));
            dto.setLineTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.LINE_TYPE, String.valueOf(model.getLineType())));
            dto.setDistinguishTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.DISTINGUISH_TYPE, String.valueOf(model.getDistinguishType())));
            dto.setBasisName(ConvertorUtil.getName(dicData, DataDictionaryConstant.LINE_BASIS, String.valueOf(model.getBasis())));
            dto.setCarrierTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.LINE_CARRIER_TYPE, String.valueOf(model.getCarrierType())));
            dto.setStartLineTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.START_LINE_TYPE, String.valueOf(model.getStartLineType())));
            dto.setLineDirectionName(ConvertorUtil.getName(dicData, DataDictionaryConstant.LINE_DIRECTION, String.valueOf(model.getLineDirection())));
            dto.setLimitName(ConvertorUtil.getName(dicData, DataDictionaryConstant.MILEAGE_MANAGEMENT, String.valueOf(model.getLimit())));

            // 线路收货方经纬度及送货顺序对象集
            List<AddressDTO> addressDTOList = Lists.newArrayList();

            // 获取线路收货方
            Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
            Restriction r5 = Restrictions.eq("lineId", model.getLineId());
            Restriction r6 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            criteria.setRestriction(Restrictions.and(r5, r6));
            List<TmsLineConsigneeLinkModel> TmsLineConsigneeLinkModels = tmsLineConsigneeLinkMapper.findByCriteria(criteria);

            if (ToolKits.isNotEmpty(TmsLineConsigneeLinkModels)) {
                // 客户收货方查询
                criteria = Criteria.forClass(TmsCustomerConsignee.class);
                Restriction r7 = Restrictions.in("id", (TmsLineConsigneeLinkModels.stream().map(TmsLineConsigneeLinkModel::getConsigneeId).distinct().collect(Collectors.toList())).stream().toArray(Long[]::new));
                Restriction r8 = Restrictions.in("customerId", (TmsLineConsigneeLinkModels.stream().map(TmsLineConsigneeLinkModel::getCustomerId).distinct().collect(Collectors.toList())).stream().toArray(Long[]::new));
                Restriction r9 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                criteria.setRestriction(Restrictions.and(r7, r8, r9));
                List<TmsCustomerConsignee> tmsCustomerConsignees = tmsCustomerConsigneeMapper.findByCriteria(criteria);
                for (TmsCustomerConsignee tmsCustomerConsignee : tmsCustomerConsignees) {
                    AddressDTO addressDTO = new AddressDTO();

                    // 根据客户ID与收货方ID筛选线路收货方对象
                    List<TmsLineConsigneeLinkModel> collect = TmsLineConsigneeLinkModels.stream().filter(tmsLineConsigneeLinkModel -> tmsLineConsigneeLinkModel.getCustomerId().longValue() == tmsCustomerConsignee.getCustomerId().longValue() && tmsLineConsigneeLinkModel.getConsigneeId().longValue() == tmsCustomerConsignee.getId().longValue()).collect(Collectors.toList());
                    if (collect.size() > 1) {
                        throw new ParameterException("线路收货方维护重复");
                    }
                    addressDTO.setLongitude(tmsCustomerConsignee.getLongitude());
                    addressDTO.setLatitude(tmsCustomerConsignee.getLatitude());

                    if (ToolKits.isEmpty(collect.get(0).getDeliveryOrder())) {
                        throw new PrologException("ID为【" + collect.get(0).getId() + "】的线路收货方关联数据的配送顺序为空,请先维护");
                    }

                    addressDTO.setIndex(collect.get(0).getDeliveryOrder());
                    addressDTOList.add(addressDTO);
                }
            }

            // 判断是否有起点
            if (ToolKits.isNotEmpty(model.getStartLineId())) {
                criteria = Criteria.forClass(TmsBaseBranchModel.class);
                Restriction r10 = Restrictions.eq("id", model.getStartLineId());
                Restriction r11 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                criteria.setRestriction(Restrictions.and(r10, r11));
                List<TmsBaseBranchModel> tmsBaseBranchModels = tmsBaseBranchMapper.findByCriteria(criteria);
                if (ToolKits.isNotEmpty(tmsBaseBranchModels)) {
                    TmsBaseBranchModel tmsBaseBranchModel = tmsBaseBranchModels.get(0);
                    AddressDTO addressDTO = new AddressDTO();
                    addressDTO.setIndex(0);
                    addressDTO.setLongitude(tmsBaseBranchModel.getLongitude());
                    addressDTO.setLatitude(tmsBaseBranchModel.getLatitude());
                    addressDTOList.add(addressDTO);
                }
            }

            // 判断是否有终点
            if (ToolKits.isNotEmpty(model.getEndLineId())) {
                criteria = Criteria.forClass(TmsBaseBranchModel.class);
                Restriction r12 = Restrictions.eq("id", model.getEndLineId());
                Restriction r13 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                criteria.setRestriction(Restrictions.and(r12, r13));
                List<TmsBaseBranchModel> tmsBaseBranchModels = tmsBaseBranchMapper.findByCriteria(criteria);
                if (ToolKits.isNotEmpty(tmsBaseBranchModels)) {
                    TmsBaseBranchModel tmsBaseBranchModel = tmsBaseBranchModels.get(0);
                    AddressDTO addressDTO = new AddressDTO();

                    if (ToolKits.isEmpty(addressDTOList)) {
                        addressDTO.setIndex(1);
                    } else {
                        // 获取线路收货方最大的配送顺序+1
                        addressDTO.setIndex(addressDTOList.stream().mapToInt(AddressDTO::getIndex).max().getAsInt() + 1);
                    }

                    addressDTO.setLongitude(tmsBaseBranchModel.getLongitude());
                    addressDTO.setLatitude(tmsBaseBranchModel.getLatitude());
                    addressDTOList.add(addressDTO);
                }
            }

            Collections.sort(addressDTOList, new Comparator<AddressDTO>() {
                @Override
                public int compare(AddressDTO o1, AddressDTO o2) {
                    // 升序
                    return o1.getIndex().compareTo(o2.getIndex());
                }
            });

            dto.setCoordinates(addressDTOList);

            // 获取线路发货方
            TmsBaselineVO shipperVo = new TmsBaselineVO();
            shipperVo.setEnterpriseId(user.getEnterpriseId());
            shipperVo.setLineId(model.getLineId());
            List<TmsShipperDTO> shippers = tmsLineShipperLinkMapper.queryLineShipper(shipperVo);
            List<AddressDTO> shipperCoordinates = Lists.newArrayList();
            if (ToolKits.isNotEmpty(shippers)) {
                for (TmsShipperDTO shipperDTO : shippers) {
                    AddressDTO addressDTO = new AddressDTO();
                    addressDTO.setIndex(ToolKits.isEmpty(shipperDTO.getPickupOrder()) ? Integer.valueOf(1) : shipperDTO.getPickupOrder());
                    addressDTO.setLatitude(shipperDTO.getLatitude());
                    addressDTO.setLongitude(shipperDTO.getLongitude());
                    shipperCoordinates.add(addressDTO);
                }
                shipperCoordinates = shipperCoordinates.stream().sorted(Comparator.comparing(AddressDTO::getIndex)).collect(Collectors.toList());
            }
            dto.setShipperCoordinates(shipperCoordinates);
            dtoList.add(dto);
        }

        Page<TmsBaseTranslineDTO> page = PageUtils.getPage(dtoList);
        if (tmsBaseTranslineModels instanceof com.github.pagehelper.Page) {
            com.github.pagehelper.Page<TmsBaseTranslineDTO> p0 = (com.github.pagehelper.Page<TmsBaseTranslineDTO>) tmsBaseTranslineModels;
            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 lineMoveQueryVO
     * @return
     */
    @SuppressWarnings("resource")
    public Page<TmsBaseTranslineDTO> moveTargetLineQuery(LineMoveQueryVO lineMoveQueryVO) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(lineMoveQueryVO, "参数不能为空！");
        ToolKits.isParamNull(lineMoveQueryVO.getLineIds(), "选择的线路不为空！");

        // 线路类型
        List<Map<String, Object>> restMessage2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.LINE_TYPE, null, null, null);
        // 划分类型
        List<Map<String, Object>> restMessage3 = sysRefdatadService.getDropDownById(DataDictionaryConstant.DISTINGUISH_TYPE, null, null, null);
        // 承运方类型
        List<Map<String, Object>> restMessage5 = sysRefdatadService.getDropDownById(DataDictionaryConstant.LINE_CARRIER_TYPE, null, null, null);
        // 线路起点类型
        List<Map<String, Object>> restMessage6 = sysRefdatadService.getDropDownById(DataDictionaryConstant.START_LINE_TYPE, null, null, null);

        // 修改现有发货方
        Criteria criteria = Criteria.forClass(TmsBaseLineModel.class);
        Restriction r1 = Restrictions.in(TmsLineShipperLinkModel::getLineId, lineMoveQueryVO.getLineIds().stream().toArray(Long[]::new));
        Restriction r2 = ToolKits.isEmpty(lineMoveQueryVO.getLineCode()) ? null : Restrictions.like(TmsLineShipperLinkModel::getLineCode, "%" + lineMoveQueryVO.getLineCode() + "%");
        Restriction r3 = ToolKits.isEmpty(lineMoveQueryVO.getLineName()) ? null : Restrictions.like(TmsLineShipperLinkModel::getLineName, "%" + lineMoveQueryVO.getLineName() + "%");
        Restriction r4 = Restrictions.eq(TmsLineShipperLinkModel::getEnterpriseId, user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2, r3, r4));

        PageUtils.startPage(lineMoveQueryVO.getPageNum(), lineMoveQueryVO.getPageSize());
        List<TmsBaseLineModel> tmsLineShipperLinkModels = tmsBaseTranslineMapper.findByCriteria(criteria);

        List<TmsBaseTranslineDTO> dtoList = Lists.newArrayList();
        for (TmsBaseLineModel model : tmsLineShipperLinkModels) {
            TmsBaseTranslineDTO lineDTO = new TmsBaseTranslineDTO();
            BeanUtils.copyProperties(model, lineDTO);

            lineDTO.setLineTypeName(PublicMethods.change(restMessage2, String.valueOf(lineDTO.getLineType())));
            lineDTO.setDistinguishTypeName(PublicMethods.change(restMessage3, String.valueOf(lineDTO.getDistinguishType())));
            lineDTO.setCarrierTypeName(PublicMethods.change(restMessage5, String.valueOf(lineDTO.getCarrierType())));
            lineDTO.setStartLineTypeName(PublicMethods.change(restMessage6, String.valueOf(lineDTO.getStartLineType())));
            dtoList.add(lineDTO);
        }

        Page<TmsBaseTranslineDTO> page = PageUtils.getPage(dtoList);
        if (tmsLineShipperLinkModels instanceof com.github.pagehelper.Page) {
            com.github.pagehelper.Page<TmsBaseLineModel> p0 = (com.github.pagehelper.Page<TmsBaseLineModel>) tmsLineShipperLinkModels;
            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 vo
     * @return
     */
    @Override
    public TmsBaseTranslineViewDTO view(TmsBaseTranslineVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(vo.getLineId(), "参数不能为空！");

        Long lineId = vo.getLineId();

        List<String> params = Lists.newArrayList(DataDictionaryConstant.MAINDATA_STATUS, // 线路状态
                DataDictionaryConstant.LINE_TYPE, // 线路类型
                DataDictionaryConstant.DISTINGUISH_TYPE, // 划分类型
                DataDictionaryConstant.LINE_DIRECTION, //线路方向
                DataDictionaryConstant.LINE_BASIS, // 限制依据
                DataDictionaryConstant.LINE_CARRIER_TYPE,// 承运方类型
                DataDictionaryConstant.START_LINE_TYPE); // 线路起点类型
        Map<String, Object> dicData = ConvertorUtil.listDropDownData(sysRefdatadService, params);

        TmsBaseLineModel tmsBaseTranslineModel = tmsBaseTranslineMapper.findById(lineId, TmsBaseLineModel.class);
        ToolKits.isParamNull(tmsBaseTranslineModel, "线路ID[" + vo.getLineId() + "]有误,查询为空！");

        TmsBaseTranslineViewDTO dto = new TmsBaseTranslineViewDTO();
        BeanUtils.copyProperties(tmsBaseTranslineModel, dto);

        Criteria criteria = Criteria.forClass(TmsBaseBranchModel.class);
        List<TmsBaseBranchModel> list = tmsBaseBranchMapper.findByCriteria(criteria);

        // 判断是否有起点
        if (ToolKits.isNotEmpty(tmsBaseTranslineModel.getStartLineCode())) {
            List<TmsBaseBranchModel> collect = list.stream().filter(o -> o.getCode().equals(tmsBaseTranslineModel.getStartLineCode())).collect(Collectors.toList());
            if (ToolKits.isNotEmpty(collect) && collect.size() > 0) {
                TmsBaseBranchModel tmsBaseBranchModel = collect.get(0);
                dto.setStartLineLongitude(ToolKits.isEmpty(tmsBaseBranchModel.getLongitude()) ? 0 : tmsBaseBranchModel.getLongitude().doubleValue());
                dto.setStartLineLatitude(ToolKits.isEmpty(tmsBaseBranchModel.getLatitude()) ? 0 : tmsBaseBranchModel.getLatitude().doubleValue());
            }
        }

        // 判断是否有终点
        if (ToolKits.isNotEmpty(tmsBaseTranslineModel.getEndLineCode())) {
            List<TmsBaseBranchModel> collect = list.stream().filter(o -> o.getCode().equals(tmsBaseTranslineModel.getEndLineCode())).collect(Collectors.toList());
            TmsBaseBranchModel tmsBaseBranchModel = collect.get(0);
            dto.setEndLineLongitude(ToolKits.isEmpty(tmsBaseBranchModel.getLongitude()) ? 0 : tmsBaseBranchModel.getLongitude().doubleValue());
            dto.setEndLineLatitude(ToolKits.isEmpty(tmsBaseBranchModel.getLatitude()) ? 0 : tmsBaseBranchModel.getLatitude().doubleValue());
        }

        // 获取收货方集合
        TmsBaseCustomerReceiverQueryVO tmsBaseCustomerReceiverQueryVO = new TmsBaseCustomerReceiverQueryVO();
        List<TmsBaseCustomerReceiverDTO> tmsBaseCustomerReceiverDTOS = tmsCustomerConsigneeMapper.queryTmsBaseCustomerReceiver(tmsBaseCustomerReceiverQueryVO, null);
        criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
        Restriction r1 = Restrictions.eq("lineId", lineId);
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        criteria.setOrder(Order.newInstance().asc(new String[]{"deliveryOrder"}));
        List<TmsLineConsigneeLinkModel> TmsLineConsigneeLinkModels = tmsLineConsigneeLinkMapper.findByCriteria(criteria);
        List<TmsArriverDTO> tmsArriverDTOs = Lists.newArrayList();
        for (TmsLineConsigneeLinkModel tmsLineConsigneeLinkModel : TmsLineConsigneeLinkModels) {
            TmsArriverDTO tmsArriverDTO = new TmsArriverDTO();
            BeanUtils.copyProperties(tmsLineConsigneeLinkModel, tmsArriverDTO);
            if (DataDictionaryConstant.DISTINGUISH_TYPE_SHF.equals(tmsBaseTranslineModel.getDistinguishType())) {
                // STD-BUG20220823 xiaoyf bug【24008】修复 start
                List<TmsBaseCustomerReceiverDTO> collect = tmsBaseCustomerReceiverDTOS.stream().filter(o -> tmsLineConsigneeLinkModel.getConsigneeId().equals(o.getId()) && tmsLineConsigneeLinkModel.getCustomerId().equals(o.getCustomerId())).collect(Collectors.toList());
                // STD-BUG20220823 xiaoyf bug【24008】修复 end
                if (ToolKits.isNotEmpty(collect)) {
                    TmsBaseCustomerReceiverDTO tmsBaseCustomerReceiverDTO = collect.get(0);
                    tmsArriverDTO.setLongitude(tmsBaseCustomerReceiverDTO.getLongitude());
                    tmsArriverDTO.setLatitude(tmsBaseCustomerReceiverDTO.getLatitude());
                }
            }
            tmsArriverDTOs.add(tmsArriverDTO);
        }

        // 获取承运方集合
        Criteria criteria2 = Criteria.forClass(TmsLineCarrierLinkModel.class);
        Restriction r3 = Restrictions.eq("lineId", lineId);

        criteria2.setRestriction(Restrictions.and(r3));
        List<TmsLineCarrierLinkModel> TmsLineCarrierLinkModels = tmsLineCarrierLinkMapper.findByCriteria(criteria2);
        List<TmsCarrierDTO> tmsCarrierDTOs = Lists.newArrayList();
        for (TmsLineCarrierLinkModel tmsLineCarrierLinkModel : TmsLineCarrierLinkModels) {
            TmsCarrierDTO tmsCarrierDTO = new TmsCarrierDTO();
            BeanUtils.copyProperties(tmsLineCarrierLinkModel, tmsCarrierDTO);
            tmsCarrierDTOs.add(tmsCarrierDTO);
        }

        dto.setTmsArriverDTOs(tmsArriverDTOs);
        dto.setTmsCarrierDTOs(tmsCarrierDTOs);

        dto.setStatusName(ConvertorUtil.getName(dicData, DataDictionaryConstant.MAINDATA_STATUS, String.valueOf(dto.getStatus())));
        dto.setLineTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.LINE_TYPE, String.valueOf(dto.getLineType())));
        dto.setDistinguishTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.DISTINGUISH_TYPE, String.valueOf(dto.getDistinguishType())));
        dto.setBasisName(ConvertorUtil.getName(dicData, DataDictionaryConstant.LINE_BASIS, String.valueOf(dto.getBasis())));
        dto.setCarrierTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.LINE_CARRIER_TYPE, String.valueOf(dto.getCarrierType())));
        dto.setStartLineTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.START_LINE_TYPE, String.valueOf(dto.getStartLineType())));
        dto.setLineDirectionName(ConvertorUtil.getName(dicData, DataDictionaryConstant.LINE_DIRECTION, String.valueOf(dto.getLineDirection())));

        // 行政区域
        if (ToolKits.isNotEmpty(tmsBaseTranslineModel.getAdministrativeAreas())) {
            String[] administrativeAreas = tmsBaseTranslineModel.getAdministrativeAreas().split(",");
            dto.setAdministrativeAreas(Arrays.asList(administrativeAreas));
        }

        // 发货方行政区域
        if (ToolKits.isNotEmpty(tmsBaseTranslineModel.getShipperAdministrativeAreas())) {
            String[] shipperAdministrativeAreas = tmsBaseTranslineModel.getShipperAdministrativeAreas().split(",");
            dto.setShipperAdministrativeAreas(Arrays.asList(shipperAdministrativeAreas));
        }

        // 获取线路发货方
        TmsBaselineVO shipperVo = new TmsBaselineVO();
        shipperVo.setEnterpriseId(user.getEnterpriseId());
        shipperVo.setLineId(lineId);
        List<TmsShipperDTO> shippers = tmsLineShipperLinkMapper.queryLineShipper(shipperVo);
        if (ToolKits.isNotEmpty(shippers)) {
            shippers.forEach(o -> {
                if (ToolKits.isNotEmpty(o.getPhoneNumber())) {
                    o.setContactTel(o.getPhoneNumber());
                } else {
                    o.setContactTel(o.getLandlineNumber());
                }
                if (ToolKits.isNotEmpty(o.getShipperAddress())) {
                    o.setAddress(o.getShipperAddress());
                }
            });
        }
        dto.setTmsShipperDTOs(shippers);
        return dto;
    }

    /**
     * 线路查看
     *
     * @param vo
     * @return
     */
    @Override
    public TmsBaseTranslineViewDTO viewByName(TmsBaseTranslineVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(vo.getLineName(), "参数不能为空！");
        String lineName = vo.getLineName();

        Criteria criteria = Criteria.forClass(TmsBaseLineModel.class);
        Restriction r1 = Restrictions.eq(TmsBaseLineModel::getLineName, lineName);
        criteria.setRestriction(Restrictions.and(r1));
        List<TmsBaseLineModel> lineModels = tmsBaseTranslineMapper.findByCriteria(criteria);

        if (ObjectUtil.isEmpty(lineModels)) {
            throw new PrologException(StrUtil.format("线路信息{}不存在",lineName));
        }
        TmsBaseTranslineViewDTO dto = new TmsBaseTranslineViewDTO();
        BeanUtils.copyProperties(lineModels.get(0), dto);

        return dto;
    }

    /**
     * 线路修改
     *
     * @param vo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TmsBaseTranslineVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(vo, "参数不能为空！");
        ToolKits.isParamNull(vo.getLineId(), "线路ID不能为空");

        ToolKits.isParamNull(vo.getDepartmentId(), "所属部门ID不能为空");
        ToolKits.isParamNull(vo.getDepartmentCode(), "所属部门编号不能为空");
        ToolKits.isParamNull(vo.getDepartmentName(), "所属部门名称不能为空");

        Date date = DateUtils.nowDate();

        TmsBaseLineModel tmsBaseTranslineModel = tmsBaseTranslineMapper.findById(vo.getLineId(), TmsBaseLineModel.class);

        ToolKits.isParamNull(tmsBaseTranslineModel, "线路ID[" + vo.getLineId() + "]有误,查询为空！");

        if (tmsBaseTranslineModel.getStatus() == StatusConstant.STATUS_DISABLE) {
            throw new RuntimeException("该线路已被停用不可操作");
        }

        BeanUtils.copyProperties(vo, tmsBaseTranslineModel);

        // 判断划分类型是否为行政区域
        if (ToolKits.isNotEmpty(tmsBaseTranslineModel.getDistinguishType()) && tmsBaseTranslineModel.getDistinguishType().equals(DataDictionaryConstant.DISTINGUISH_TYPE_XZQY)) {
            if (ToolKits.isNotEmpty(vo.getAdministrativeAreas())) {
                String administrativeAreas = vo.getAdministrativeAreas().stream().distinct().collect(Collectors.joining(","));
                // 行政区域ID储存
                tmsBaseTranslineModel.setAdministrativeAreas(administrativeAreas);
            }
        } else {
            tmsBaseTranslineModel.setAdministrativeAreas(null);
        }

        if (ToolKits.isNotEmpty(tmsBaseTranslineModel.getStartLineType()) && tmsBaseTranslineModel.getStartLineType().equals(DataDictionaryConstant.START_LINE_TYPE_ZONE)) {
            if (ToolKits.isNotEmpty(vo.getShipperAdministrativeAreas())) {
                String administrativeAreas = vo.getShipperAdministrativeAreas().stream().distinct().collect(Collectors.joining(","));
                // 发活方-行政区域ID储存
                tmsBaseTranslineModel.setShipperAdministrativeAreas(administrativeAreas);
            }
        } else {
            tmsBaseTranslineModel.setShipperAdministrativeAreas(null);
        }

        if (ToolKits.isNotEmpty(vo.getEndLineCode()) || ToolKits.isNotEmpty(vo.getEndLineName())) {
            tmsBaseTranslineModel.setEndLineType(1);
        }

        tmsBaseTranslineModel.setUpdateperson(user.getNickname());
        tmsBaseTranslineModel.setUpdatetime(DateUtils.nowDate());

        List<TmsArriverVO> tmsArriverVOS = vo.getTmsArriverVOS();// 收货方

        // 收货方修改
        if (ToolKits.isNotEmpty(tmsArriverVOS)) {
            List<String> consigneeCodes = tmsArriverVOS.stream().map(TmsArriverVO::getConsigneeCode).distinct().collect(Collectors.toList());
            Integer deliverySiteNumber = 0;
            for (TmsArriverVO tmsArriverVO : tmsArriverVOS) {
                ToolKits.isParamNull(tmsArriverVO.getConsigneeCode(), "收货方编号不能为空");
                ToolKits.isParamNull(tmsArriverVO.getConsigneeName(), "收货方名称不能为空");
                ToolKits.isParamNull(tmsArriverVO.getDeliveryOrder(), "配送顺序不能为空");
                ToolKits.isParamNull(tmsArriverVO.getConsigneeAddress(), "收货地址不能为空");
                if (DataDictionaryConstant.DISTINGUISH_TYPE_SHF.equals(tmsBaseTranslineModel.getDistinguishType())) {
                    ToolKits.isParamNull(tmsArriverVO.getCustomerId(), "客户ID不能为空");
                    ToolKits.isParamNull(tmsArriverVO.getCustomerCode(), "客户编号不能为空");
                    ToolKits.isParamNull(tmsArriverVO.getCustomerName(), "客户名称不能为空");
                    ToolKits.isParamNull(tmsArriverVO.getConsigneeId(), "收货方ID不能为空");
                    ToolKits.isParamNull(tmsArriverVO.getConsigneePhoneNumber(), "联系方式不能为空");
                } else {
                    //tmsArriverVO.setConsigneeAddress(getName(tmsArriverVO.getConsigneeCode(),tmsArriverVO.getConsigneeName()));
                }
                // 修改现有收货方
                Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
                Restriction r1 = ToolKits.isEmpty(tmsArriverVO.getCustomerId()) ? null : Restrictions.eq("customerId", tmsArriverVO.getCustomerId());
                Restriction r2 = Restrictions.eq("consigneeCode", tmsArriverVO.getConsigneeCode());
                Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                criteria.setRestriction(Restrictions.and(r1, r2, r3));

                List<TmsLineConsigneeLinkModel> tmsLineConsigneeLinkModelList = tmsLineConsigneeLinkMapper.findByCriteria(criteria);
                if (tmsLineConsigneeLinkModelList.size() > 0) {
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("lineId", vo.getLineId());
                    map.put("updateperson", user.getNickname());
                    map.put("updatetime", date);
                    map.put("deliveryOrder", tmsArriverVO.getDeliveryOrder());
                    map.put("consigneeAgingTime", tmsArriverVO.getConsigneeAgingTime());
                    map.put("consigneeAgingTimeLine", tmsArriverVO.getConsigneeAgingTimeLine());
                    tmsLineConsigneeLinkMapper.updateMapByCriteria(map, criteria);
                    deliverySiteNumber++;
                } else {
                    if (DataDictionaryConstant.DISTINGUISH_TYPE_SHF.equals(tmsBaseTranslineModel.getDistinguishType())) {
                        long count = tmsLineConsigneeLinkMapper.findCountByConsignee(tmsArriverVO);
                        if (count > 0) {
                            throw new RuntimeException("一个客户[" + tmsArriverVO.getCustomerName() + "]的一个收货方[" + tmsArriverVO.getConsigneeName() + "]当前只能存在于一个线路中");
                        }
                    }
                    TmsLineConsigneeLinkModel model = new TmsLineConsigneeLinkModel();

                    String linkId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_LINE_CONSIGNEE_LINK, "L");
                    ToolKits.isParamNull(linkId, "获取线路收货方关联表ID失败！");

                    BeanUtils.copyProperties(tmsArriverVO, model);
                    model.setId(linkId);
                    model.setLineId(tmsBaseTranslineModel.getLineId());
                    model.setLineCode(tmsBaseTranslineModel.getLineCode());
                    model.setLineName(tmsBaseTranslineModel.getLineName());
                    model.setCreateperson(tmsBaseTranslineModel.getCreateperson());
                    model.setCreatetime(tmsBaseTranslineModel.getCreatetime());
                    // 企业ID
                    model.setEnterpriseId(user.getEnterpriseId());

                    // 企业名称
                    model.setEnterpriseName(user.getEnterpriseName());
                    // 来源(1.新增 2.excel导入 3.接口导入)
                    model.setSource(DataDictionaryConstant.SOURCE_ADD);
                    // 保存收货方
                    tmsLineConsigneeLinkMapper.save(model);
                    deliverySiteNumber++;
                }
                // 删除
                r1 = Restrictions.eq("lineId", vo.getLineId());
                r2 = Restrictions.notIn("consigneeCode", consigneeCodes.toArray());
                Restriction r4 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                criteria.setRestriction(Restrictions.and(r1, r2, r4));
                tmsLineConsigneeLinkMapper.deleteByCriteria(criteria);
            }
            tmsBaseTranslineModel.setDeliverySiteNumber(deliverySiteNumber);
        } else {
            // 删除收货方
            Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
            Restriction r1 = Restrictions.eq("lineId", vo.getLineId());
            criteria.setRestriction(Restrictions.and(r1));
            tmsLineConsigneeLinkMapper.deleteByCriteria(criteria);

            tmsBaseTranslineModel.setDeliverySiteNumber(0);
        }

        List<TmsCarrierVO> tmsCarrierVOS = vo.getTmsCarrierVOS();// 承运方

        if (ToolKits.isNotEmpty(tmsCarrierVOS)) {
            List<String> carrierCodes = tmsCarrierVOS.stream().filter(o -> ToolKits.isNotEmpty(o.getCarrierCode())).map(TmsCarrierVO::getCarrierCode).collect(Collectors.toList());
            if (carrierCodes.size() != carrierCodes.stream().distinct().collect(Collectors.toList()).size()) {
                throw new RuntimeException("承运方/司机编码重复");
            }
            if (tmsBaseTranslineModel.getLimit() == 1) {
                long sum = tmsCarrierVOS.stream().collect(Collectors.summarizingInt(o -> o.getShares().intValue())).getSum();
                if (sum != 100) {
                    throw new RuntimeException("线路已限制份额,份额总和要等于100");
                }

            }

            for (TmsCarrierVO tmsCarrierVO : tmsCarrierVOS) {
                Criteria criteria = Criteria.forClass(TmsLineCarrierLinkModel.class);
                Restriction r1 = Restrictions.eq("lineId", vo.getLineId());
                Restriction r2 = Restrictions.eq("carrierId", tmsCarrierVO.getCarrierId());
                criteria.setRestriction(Restrictions.and(r1, r2));
                List<TmsLineCarrierLinkModel> tmsLineCarrierLinkModels = tmsLineCarrierLinkMapper.findByCriteria(criteria);
                // 查询承运方 有 修改 ,无 新增
                if (tmsLineCarrierLinkModels.size() > 0) {
                    TmsLineCarrierLinkModel tmsLineCarrierLinkModel = tmsLineCarrierLinkModels.get(0);
                    // BeanUtils.copyProperties(tmsCarrierVO, tmsLineCarrierLinkModel);
                    tmsLineCarrierLinkModel.setCarrierId(tmsCarrierVO.getCarrierId());
                    tmsLineCarrierLinkModel.setCarrierCode(tmsCarrierVO.getCarrierCode());
                    tmsLineCarrierLinkModel.setCarrierName(tmsCarrierVO.getCarrierName());
                    tmsLineCarrierLinkModel.setPhoneNumber(tmsCarrierVO.getPhoneNumber());
                    tmsLineCarrierLinkModel.setVehicleCode(tmsCarrierVO.getVehicleCode());
                    tmsLineCarrierLinkModel.setVehicleId(tmsCarrierVO.getVehicleId());
                    tmsLineCarrierLinkModel.setVehiclePlateNumber(tmsCarrierVO.getVehiclePlateNumber());
                    tmsLineCarrierLinkModel.setUpdateperson(user.getNickname());
                    tmsLineCarrierLinkModel.setUpdatetime(date);
                    tmsLineCarrierLinkMapper.update(tmsLineCarrierLinkModel);
                } else {
                    String linkId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_LINE_CARRIER_LINK, "L");
                    ToolKits.isParamNull(linkId, "获取线路收货方关联表ID失败！");

                    TmsLineCarrierLinkModel tmsLineCarrierLinkModel = new TmsLineCarrierLinkModel();
                    BeanUtils.copyProperties(tmsCarrierVO, tmsLineCarrierLinkModel);

                    tmsLineCarrierLinkModel.setPrimaryKey(linkId);
                    tmsLineCarrierLinkModel.setLineId(tmsBaseTranslineModel.getLineId());
                    tmsLineCarrierLinkModel.setLineCode(tmsBaseTranslineModel.getLineCode());
                    tmsLineCarrierLinkModel.setLineName(tmsBaseTranslineModel.getLineName());
                    tmsLineCarrierLinkModel.setType(tmsBaseTranslineModel.getCarrierType());
                    tmsLineCarrierLinkModel.setCreateperson(tmsBaseTranslineModel.getCreateperson());
                    tmsLineCarrierLinkModel.setCreatetime(tmsBaseTranslineModel.getCreatetime());
                    tmsLineCarrierLinkModel.setUpdateperson(user.getNickname());
                    tmsLineCarrierLinkModel.setUpdatetime(DateUtils.nowDate());
                    tmsLineCarrierLinkModel.setSource(DataDictionaryConstant.SOURCE_ADD);

                    tmsLineCarrierLinkMapper.save(tmsLineCarrierLinkModel);
                }
            }

            List<Long> carrierIds = tmsCarrierVOS.stream().filter(o -> ToolKits.isNotEmpty(o.getCarrierId())).map(TmsCarrierVO::getCarrierId).distinct().collect(Collectors.toList());

            // 删除
            Criteria criteria = Criteria.forClass(TmsLineCarrierLinkModel.class);
            Restriction r1 = Restrictions.eq("lineId", vo.getLineId());
            Restriction r2 = Restrictions.notIn("carrierId", carrierIds.toArray());
            criteria.setRestriction(Restrictions.and(r1, r2));
            tmsLineCarrierLinkMapper.deleteByCriteria(criteria);
        } else {
            // 删除
            Criteria criteria = Criteria.forClass(TmsLineCarrierLinkModel.class);
            Restriction r1 = Restrictions.eq("lineId", vo.getLineId());
            criteria.setRestriction(Restrictions.and(r1));
            tmsLineCarrierLinkMapper.deleteByCriteria(criteria);
        }
        List<TmsShipperVO> tmsShipperVOS = vo.getTmsShipperVOS();// 发货方

        // 发货方修改
        if (ToolKits.isNotEmpty(tmsShipperVOS)) {
            List<String> brandCodes = tmsShipperVOS.stream().map(TmsShipperVO::getBranchCode).distinct().collect(Collectors.toList());

            Integer pickUpNum = 0;
            for (TmsShipperVO tmsShipperVO : tmsShipperVOS) {
                ToolKits.isParamNull(tmsShipperVO.getBranchCode(), "仓库编号不能为空");
                ToolKits.isParamNull(tmsShipperVO.getBranchName(), "仓库名称不能为空");
                //ToolKits.isParamNull(tmsShipperVO.getPickupOrder(), "提货顺序不能为空");
                if (DataDictionaryConstant.START_LINE_TYPE_BRANCH.equals(tmsBaseTranslineModel.getStartLineType())) {
                    ToolKits.isParamNull(tmsShipperVO.getBranchId(), "仓库ID不能为空");
                } else {
                    //tmsShipperVO.setShipperAddress(getName(tmsShipperVO.getBranchCode(),tmsShipperVO.getBranchName()));
                }
                // 修改现有发货方
                Criteria criteria = Criteria.forClass(TmsLineShipperLinkModel.class);
                Restriction r1 = Restrictions.eq(TmsLineShipperLinkModel::getBranchCode, tmsShipperVO.getBranchCode());
                Restriction r2 = Restrictions.eq(TmsLineShipperLinkModel::getEnterpriseId, user.getEnterpriseId());
                Restriction r3 = Restrictions.eq(TmsLineShipperLinkModel::getLineId, vo.getLineId());
                criteria.setRestriction(Restrictions.and(r1, r2, r3));

                List<TmsLineShipperLinkModel> tmsLineShipperLinkModels = tmsLineShipperLinkMapper.findByCriteria(criteria);
                if (tmsLineShipperLinkModels.size() > 0) {
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("lineCode", vo.getLineCode());
                    map.put("lineName", vo.getLineName());
                    map.put("branchCode", tmsShipperVO.getBranchCode());
                    map.put("branchName", tmsShipperVO.getBranchName());
                    map.put("shipperAddress", tmsShipperVO.getShipperAddress());
                    map.put("updateperson", user.getNickname());
                    map.put("updatetime", date);
                    map.put("pickupOrder", tmsShipperVO.getPickupOrder());
                    map.put("shipperAgingTime", tmsShipperVO.getShipperAgingTime());
                    map.put("shipperAgingTimeLine", tmsShipperVO.getShipperAgingTimeLine());
                    tmsLineShipperLinkMapper.updateMapByCriteria(map, criteria);
                    pickUpNum++;
                } else {
                    TmsLineShipperLinkModel shipperLinkModel = new TmsLineShipperLinkModel();
                    BeanUtils.copyProperties(tmsShipperVO, shipperLinkModel);
                    String linkId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_LINE_SHIPPER_LINK, "L");
                    ToolKits.isParamNull(linkId, "获取线路发货方关联表ID失败！");

                    shipperLinkModel.setId(linkId);
                    shipperLinkModel.setLineId(tmsBaseTranslineModel.getLineId());
                    shipperLinkModel.setLineCode(tmsBaseTranslineModel.getLineCode());
                    shipperLinkModel.setLineName(tmsBaseTranslineModel.getLineName());
                    shipperLinkModel.setSource(DataDictionaryConstant.SOURCE_ADD);
                    shipperLinkModel.setCreateperson(user.getNickname());
                    shipperLinkModel.setCreatetime(DateUtils.nowDate());
                    // 企业ID
                    shipperLinkModel.setEnterpriseId(user.getEnterpriseId());
                    // 企业名称
                    shipperLinkModel.setEnterpriseName(user.getEnterpriseName());
                    tmsLineShipperLinkMapper.save(shipperLinkModel);
                    pickUpNum++;
                }
                // 删除
                r1 = Restrictions.eq("lineId", vo.getLineId());
                r2 = Restrictions.notIn("branchCode", brandCodes.toArray());
                Restriction r4 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                criteria.setRestriction(Restrictions.and(r1, r2, r4));
                tmsLineShipperLinkMapper.deleteByCriteria(criteria);
            }
            tmsBaseTranslineModel.setPickUpSiteNumber(pickUpNum);
        } else {
            // 删除收货方
            Criteria criteria = Criteria.forClass(TmsLineShipperLinkModel.class);
            Restriction r1 = Restrictions.eq("lineId", vo.getLineId());
            criteria.setRestriction(Restrictions.and(r1));
            tmsLineShipperLinkMapper.deleteByCriteria(criteria);
            tmsBaseTranslineModel.setPickUpSiteNumber(0);
        }

        // 修改线路
        tmsBaseTranslineModel.setLineDirection(vo.getLineDirection());
        tmsBaseTranslineModel.setTotalStations(tmsBaseTranslineModel.getDeliverySiteNumber().intValue() + tmsBaseTranslineModel.getPickUpSiteNumber().intValue());
        tmsBaseTranslineMapper.update(tmsBaseTranslineModel);
    }

    /**
     * 线路新增
     *
     * @param vo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(TmsBaseTranslineBySaveVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");

        ToolKits.isParamNull(vo, "参数不能为空！");
        ToolKits.isParamNull(vo.getLineCode(), "线路编号不能为空");
        ToolKits.isParamNull(vo.getLineName(), "线路名称不能为空");
        ToolKits.isParamNull(vo.getLineType(), "线路类型不能为空");
        ToolKits.isParamNull(vo.getDistinguishType(), "划分类型不能为空");

        ToolKits.isParamNull(vo.getDepartmentId(), "所属部门ID不能为空");
        ToolKits.isParamNull(vo.getDepartmentCode(), "所属部门编号不能为空");
        ToolKits.isParamNull(vo.getDepartmentName(), "所属部门名称不能为空");

        // 判断线路编号是否存在
        Criteria criteria = Criteria.forClass(TmsBaseLineModel.class);
        Restriction r1 = Restrictions.eq("lineCode", vo.getLineCode());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        long count = tmsBaseTranslineMapper.findCountByCriteria(criteria);
        if (count != 0) {
            throw new RuntimeException("线路编码[" + vo.getLineCode() + "]已存在");
        }
        // 判断线路名称是否存在
        r1 = Restrictions.eq("lineName", vo.getLineCode());
        criteria.setRestriction(r1);
        long count2 = tmsBaseTranslineMapper.findCountByCriteria(criteria);
        if (count2 != 0) {
            throw new RuntimeException("线路名称[" + vo.getLineCode() + "]已存在");
        }

        TmsBaseLineModel model = new TmsBaseLineModel();

        BeanUtils.copyProperties(vo, model);

        String lineId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_BASE_TRANSLINE_ID, "L");
        ToolKits.isParamNull(lineId, "获取线路ID失败！");
        model.setLineId(Long.valueOf(lineId));

        // 判断划分类型（收货方）是否为行政区域
        if (ToolKits.isNotEmpty(vo.getDistinguishType()) && vo.getDistinguishType().equals(DataDictionaryConstant.DISTINGUISH_TYPE_XZQY)) {
            if (ToolKits.isNotEmpty(vo.getAdministrativeAreas())) {
                String administrativeAreas = vo.getAdministrativeAreas().stream().distinct().collect(Collectors.joining(","));
                // 行政区域ID储存
                model.setAdministrativeAreas(administrativeAreas);
            }
        }

        // 判断起点类型是否为行政区域
        if (ToolKits.isNotEmpty(vo.getStartLineType()) && vo.getStartLineType().equals(DataDictionaryConstant.START_LINE_TYPE_ZONE)) {
            if (ToolKits.isNotEmpty(vo.getShipperAdministrativeAreas())) {
                String shipperAdministrativeAreas = vo.getShipperAdministrativeAreas().stream().distinct().collect(Collectors.joining(","));
                // 行政区域ID储存
                model.setShipperAdministrativeAreas(shipperAdministrativeAreas);
            }
        }

        // 企业ID
        model.setEnterpriseId(user.getEnterpriseId());

        // 企业名称
        model.setEnterpriseName(user.getEnterpriseName());

        // 设置类型(1仓库2客户3供应商)，目前默认仓库
        if (ToolKits.isNotEmpty(model.getStartLineCode()) && ToolKits.isNotEmpty(model.getStartLineName())) {
            model.setStartLineType(DataDictionaryConstant.LINE_TYPE_CK);
        }
        if (ToolKits.isNotEmpty(model.getEndLineCode()) && ToolKits.isNotEmpty(model.getEndLineName())) {
            model.setEndLineType(DataDictionaryConstant.LINE_TYPE_CK);
        }

        // 状态有效
        model.setStatus(StatusConstant.STATUS_ENABLE);

        // 来源(1.新增 2.excel导入 3.接口导入)
        model.setSource(DataDictionaryConstant.SOURCE_ADD);

        // 创建人
        model.setCreateperson(user.getNickname());
        model.setCreatetime(DateUtils.nowDate());
        model.setUpdateperson(user.getNickname());
        model.setUpdatetime(DateUtils.nowDate());

        // 承运方
        List<TmsCarrierVO> tmsCarrierVOS = vo.getTmsCarrierVOS();

        if (ToolKits.isNotEmpty(tmsCarrierVOS)) {
            List<String> carrierCodes = tmsCarrierVOS.stream().filter(o -> ToolKits.isNotEmpty(o.getCarrierCode())).map(TmsCarrierVO::getCarrierCode).collect(Collectors.toList());
            if (carrierCodes.size() != carrierCodes.stream().distinct().collect(Collectors.toList()).size()) {
                throw new RuntimeException("承运方/司机重复");
            }

            if (vo.getLimit() == 1) {
                long sum = tmsCarrierVOS.stream().collect(Collectors.summarizingInt(o -> o.getShares().intValue())).getSum();
                if (sum != 100) {
                    throw new RuntimeException("线路已限制份额,份额总和要等于100");
                }
            } else if (vo.getLimit() == 0) {
                for (TmsCarrierVO tmsCarrierVO : tmsCarrierVOS) {
                    if (ToolKits.isNotEmpty(tmsCarrierVO.getShares()) && tmsCarrierVO.getShares().intValue() > 0) {
                        throw new RuntimeException("线路没有限制份额,不可分配份额");
                    }
                }
            }
            List<TmsLineCarrierLinkModel> tmsLineCarrierLinkModels = Lists.newArrayList();
            for (TmsCarrierVO tmsCarrierVO : tmsCarrierVOS) {
                TmsLineCarrierLinkModel tmsLineCarrierLinkModel = new TmsLineCarrierLinkModel();
                BeanUtils.copyProperties(tmsCarrierVO, tmsLineCarrierLinkModel);

                String linkId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_LINE_CARRIER_LINK, "L");
                ToolKits.isParamNull(linkId, "获取线路承运方关联表ID失败！");

                tmsLineCarrierLinkModel.setPrimaryKey(linkId);
                tmsLineCarrierLinkModel.setSource(DataDictionaryConstant.SOURCE_ADD);
                tmsLineCarrierLinkModel.setLineId(Long.valueOf(lineId));
                tmsLineCarrierLinkModel.setLineCode(vo.getLineCode());
                tmsLineCarrierLinkModel.setLineName(vo.getLineName());
                tmsLineCarrierLinkModel.setType(vo.getCarrierType());
                tmsLineCarrierLinkModel.setShares(ToolKits.isNotEmpty(tmsCarrierVO.getShares()) ? tmsCarrierVO.getShares() : BigDecimal.ZERO);
                tmsLineCarrierLinkModel.setCreateperson(user.getNickname());
                tmsLineCarrierLinkModel.setCreatetime(DateUtils.nowDate());

                tmsLineCarrierLinkModels.add(tmsLineCarrierLinkModel);

            }
            tmsLineCarrierLinkMapper.saveBatch(tmsLineCarrierLinkModels);
        }

        // 收货方
        List<TmsArriverVO> tmsArriverVOS = vo.getTmsArriverVOS();

        if (ToolKits.isNotEmpty(tmsArriverVOS)) {
            List<TmsLineConsigneeLinkModel> tmsLineConsigneeLinkModels = Lists.newArrayList();
            for (TmsArriverVO tmsArriverVO : tmsArriverVOS) {
                ToolKits.isParamNull(tmsArriverVO.getConsigneeCode(), "收货方编号不能为空");
                ToolKits.isParamNull(tmsArriverVO.getConsigneeName(), "收货方名称不能为空");
                ToolKits.isParamNull(tmsArriverVO.getDeliveryOrder(), "配送顺序不能为空");
                ToolKits.isParamNull(tmsArriverVO.getConsigneeAddress(), "收货地址不能为空");
                if (DataDictionaryConstant.DISTINGUISH_TYPE_SHF.equals(vo.getDistinguishType())) {
                    ToolKits.isParamNull(tmsArriverVO.getCustomerId(), "客户ID不能为空");
                    ToolKits.isParamNull(tmsArriverVO.getCustomerCode(), "客户编号不能为空");
                    ToolKits.isParamNull(tmsArriverVO.getCustomerName(), "客户名称不能为空");
                    ToolKits.isParamNull(tmsArriverVO.getConsigneeId(), "收货方ID不能为空");
                    ToolKits.isParamNull(tmsArriverVO.getConsigneePhoneNumber(), "联系方式不能为空");
                    TmsArriverVO arriverVO = new TmsArriverVO();
                    arriverVO.setCustomerId(tmsArriverVO.getCustomerId());
                    arriverVO.setConsigneeId(tmsArriverVO.getConsigneeId());
                    long count3 = tmsLineConsigneeLinkMapper.findCountByConsignee(arriverVO);
                    if (count3 > 0) {
                        throw new RuntimeException("一个客户[" + tmsArriverVO.getCustomerName() + "]的一个收货方[" + tmsArriverVO.getConsigneeName() + "]当前只能存在于一个线路中");
                    }
                } else {
                    //tmsArriverVO.setConsigneeAddress(getName(tmsArriverVO.getConsigneeCode(),tmsArriverVO.getConsigneeName()));
                }

                TmsLineConsigneeLinkModel tmsLineConsigneeLinkModel = new TmsLineConsigneeLinkModel();
                BeanUtils.copyProperties(tmsArriverVO, tmsLineConsigneeLinkModel);

                String linkId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_LINE_CONSIGNEE_LINK, "L");
                ToolKits.isParamNull(linkId, "获取线路收货方关联表ID失败！");

                tmsLineConsigneeLinkModel.setId(linkId);
                tmsLineConsigneeLinkModel.setLineId(Long.valueOf(lineId));
                tmsLineConsigneeLinkModel.setLineCode(vo.getLineCode());
                tmsLineConsigneeLinkModel.setLineName(vo.getLineName());
                tmsLineConsigneeLinkModel.setSource(DataDictionaryConstant.SOURCE_ADD);
                tmsLineConsigneeLinkModel.setCreateperson(user.getNickname());
                tmsLineConsigneeLinkModel.setCreatetime(DateUtils.nowDate());
                // 企业ID
                tmsLineConsigneeLinkModel.setEnterpriseId(user.getEnterpriseId());

                // 企业名称
                tmsLineConsigneeLinkModel.setEnterpriseName(user.getEnterpriseName());
                tmsLineConsigneeLinkModels.add(tmsLineConsigneeLinkModel);
            }
            tmsLineConsigneeLinkMapper.saveBatch(tmsLineConsigneeLinkModels);

            model.setDeliverySiteNumber(tmsLineConsigneeLinkModels.size());
        } else {
            model.setDeliverySiteNumber(0);
        }

        // 发货方
        List<TmsShipperVO> tmsShippers = vo.getTmsShipperVOS();
        if (ToolKits.isNotEmpty(tmsShippers)) {
            for (TmsShipperVO shipperVO : tmsShippers) {
                ToolKits.isParamNull(shipperVO.getBranchCode(), "仓库编号不能为空");
                ToolKits.isParamNull(shipperVO.getBranchName(), "仓库名称不能为空");
                //ToolKits.isParamNull(shipperVO.getPickupOrder(), "提货顺序不能为空");
                if (DataDictionaryConstant.START_LINE_TYPE_BRANCH.equals(vo.getStartLineType())) {
                    ToolKits.isParamNull(shipperVO.getBranchId(), "仓库ID不能为空");
                } else {
                    //shipperVO.setShipperAddress(getName(shipperVO.getBranchCode(),shipperVO.getBranchName()));
                }
                TmsLineShipperLinkModel shipperLinkModel = new TmsLineShipperLinkModel();
                BeanUtils.copyProperties(shipperVO, shipperLinkModel);

                String linkId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_LINE_SHIPPER_LINK, "L");
                ToolKits.isParamNull(linkId, "获取线路发货方关联表ID失败！");

                shipperLinkModel.setId(linkId);
                shipperLinkModel.setLineId(Long.valueOf(lineId));
                shipperLinkModel.setLineCode(vo.getLineCode());
                shipperLinkModel.setLineName(vo.getLineName());
                shipperLinkModel.setSource(DataDictionaryConstant.SOURCE_ADD);
                shipperLinkModel.setCreateperson(user.getNickname());
                shipperLinkModel.setCreatetime(DateUtils.nowDate());
                // 企业ID
                shipperLinkModel.setEnterpriseId(user.getEnterpriseId());
                // 企业名称
                shipperLinkModel.setEnterpriseName(user.getEnterpriseName());
                tmsLineShipperLinkMapper.save(shipperLinkModel);
            }
            model.setPickUpSiteNumber(tmsShippers.size());
        } else {
            model.setPickUpSiteNumber(0);
        }

        model.setTotalStations(model.getDeliverySiteNumber().intValue() + model.getPickUpSiteNumber().intValue());
        // 线路方向
        model.setLineDirection(vo.getLineDirection());
        // 保存操作
        tmsBaseTranslineMapper.save(model);
    }

    // 获取省市区的名称
    public String getProvinceCityName(String zoneId, String zoneName) {
        List<String> zoneIds = Lists.newArrayList();
        if (zoneId.contains("0000")) {
            return zoneName;
        } else if (zoneId.contains("00")) {
            // 获取省的名称
            zoneIds.add(zoneId.substring(0, 2) + "0000");
        } else {
            // 获取省，市的名称
            zoneIds.add(zoneId.substring(0, 2) + "0000");
            zoneIds.add(zoneId.substring(0, 4) + "00");
        }
        List<LmsTmsZoneModel> zoneModels = lmsTmsZoneMapper.findByIds(LmsTmsZoneModel.class, zoneIds.stream().toArray(), null);
        if (ToolKits.isNotEmpty(zoneModels)) {
            List<String> upNames = zoneModels.stream().sorted(Comparator.comparing(LmsTmsZoneModel::getZlevel)).map(LmsTmsZoneModel::getZname).collect(Collectors.toList());
            upNames.add(zoneName);
            return upNames.stream().collect(Collectors.joining());
        }
        return zoneName;
    }

    /**
     * 线路删除
     *
     * @param list
     */
    @Override
    public void remove(List<TmsBaseTranslineByIdsVO> list) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(list, "参数不能为空！");

        List<Long> lineIds = list.stream().map(TmsBaseTranslineByIdsVO::getLineId).distinct().collect(Collectors.toList());
        List<Integer> collect = list.stream().map(TmsBaseTranslineByIdsVO::getStatus).distinct().collect(Collectors.toList());

        ToolKits.isParamNull(collect, "状态不能为空");

        if (collect.size() > 1) {
            throw new RuntimeException("该组线路中已存在被启用/禁用的线路");
        }

        Criteria criteria = Criteria.forClass(TmsBaseLineModel.class);
        Restriction r1 = Restrictions.in("lineId", lineIds.toArray());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));

        Map<String, Object> map = Maps.newHashMap();
        Integer status = null;
        if (collect.get(0) == StatusConstant.STATUS_DISABLE) {
            status = StatusConstant.STATUS_ENABLE;
        } else {
            status = StatusConstant.STATUS_DISABLE;
        }
        map.put("status", status);

        tmsBaseTranslineMapper.updateMapByCriteria(map, criteria);
    }

    /**
     * 线路物理删除
     *
     * @param list
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void neverDelete(List<TmsBaseTranslineByIdsVO> list) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(list, "参数不能为空！");

        List<Long> lineIds = list.stream().map(TmsBaseTranslineByIdsVO::getLineId).distinct().collect(Collectors.toList());

        ToolKits.isParamNull(lineIds, "线路ID不能为空");

        // 删除线路
        tmsBaseTranslineMapper.deleteByIds(lineIds.toArray(), TmsBaseLineModel.class);

        // 删除线路-收货方
        Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
        Restriction r1 = Restrictions.in("lineId", lineIds.toArray());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        tmsLineConsigneeLinkMapper.deleteByCriteria(criteria);

        // 删除线路-承运方
        criteria = Criteria.forClass(TmsLineCarrierLinkModel.class);
        criteria.setRestriction(r1);
        tmsLineCarrierLinkMapper.deleteByCriteria(criteria);

        // 删除线路-发货方
        criteria = Criteria.forClass(TmsLineShipperLinkModel.class);
        r1 = Restrictions.in("lineId", lineIds.toArray());
        r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        tmsLineShipperLinkMapper.deleteByCriteria(criteria);
    }

    /**
     * 线路-承运方保存
     *
     * @param list
     */
    @Override
    public void tmsCarrierSave(List<TmsCarrierVO> list) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(list, "参数不能为空！");

        List<Long> lineIds = list.stream().map(TmsCarrierVO::getLineId).distinct().collect(Collectors.toList());
        ToolKits.isParamNull(lineIds, "承运方绑定的线路ID不可为空");
        if (lineIds.size() > 1) {
            throw new RuntimeException("承运方绑定的路线不是唯一");
        }

        List<String> carrierCodes = list.stream().filter(o -> ToolKits.isNotEmpty(o.getCarrierCode())).map(TmsCarrierVO::getCarrierCode).collect(Collectors.toList());
        if (carrierCodes.size() != carrierCodes.stream().distinct().collect(Collectors.toList()).size()) {
            throw new RuntimeException("承运方/司机重复");
        }
        TmsBaseLineModel tmsBaseTranslineModel = tmsBaseTranslineMapper.findById(lineIds.get(0), TmsBaseLineModel.class);
        ToolKits.isParamNull(tmsBaseTranslineModel, "线路ID[" + lineIds.get(0) + "]有误,查询为空！");
        if (tmsBaseTranslineModel.getLimit() == 1) {
            long sum = list.stream().collect(Collectors.summarizingInt(o -> o.getShares().intValue())).getSum();
            if (sum != 100) {
                throw new RuntimeException("线路已限制份额,份额总和要等于100");
            }
        } else if (tmsBaseTranslineModel.getLimit() == 0) {
            for (TmsCarrierVO tmsCarrierVO : list) {
                if (ToolKits.isNotEmpty(tmsCarrierVO.getShares()) && tmsCarrierVO.getShares().intValue() > 0) {
                    throw new RuntimeException("线路没有限制份额,不可分配份额");
                }
            }
        }

        Criteria criteria = Criteria.forClass(TmsLineCarrierLinkModel.class);
        Restriction r1 = Restrictions.eq("lineId", lineIds.get(0));
        Restriction r2 = Restrictions.notIn("carrierCode", carrierCodes.toArray());
        Restriction r3 = null;
        criteria.setRestriction(Restrictions.and(r1, r2));
        tmsLineCarrierLinkMapper.deleteByCriteria(criteria);

        for (TmsCarrierVO tmsCarrierVO : list) {
            r3 = Restrictions.eq("carrierCode", tmsCarrierVO.getCarrierCode());
            criteria.setRestriction(Restrictions.and(r1, r3));

            Map<String, Object> map = Maps.newHashMap();
            map.put("shares", ToolKits.isNotEmpty(tmsCarrierVO.getShares()) ? tmsCarrierVO.getShares() : 0);

            tmsLineCarrierLinkMapper.updateMapByCriteria(map, criteria);
        }

    }

    /**
     * 线路-收货方删除
     *
     * @param list
     */
    @Override
    public void tmsArriverRemove(List<TmsArriverRemoveVO> list) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(list, "参数不能为空！");
        DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);

        try {
            for (TmsArriverRemoveVO tmsArriverRemoveVO : list) {
                ToolKits.isParamNull(tmsArriverRemoveVO.getLineId(), "线路ID不能为空");
                ToolKits.isParamNull(tmsArriverRemoveVO.getCustomerId(), "客户ID不能为空");
                ToolKits.isParamNull(tmsArriverRemoveVO.getConsigneeId(), "收货方ID不能为空");

                Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
                Restriction r1 = Restrictions.eq("lineId", tmsArriverRemoveVO.getLineId());
                Restriction r2 = Restrictions.eq("customerId", tmsArriverRemoveVO.getCustomerId());
                Restriction r3 = Restrictions.eq("consigneeId", tmsArriverRemoveVO.getConsigneeId());
                Restriction r5 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                criteria.setRestriction(Restrictions.and(r1, r2, r3, r5));

                List<TmsLineConsigneeLinkModel> TmsLineConsigneeLinkModels = tmsLineConsigneeLinkMapper.findByCriteria(criteria);
                ToolKits.isParamNull(TmsLineConsigneeLinkModels, "线路ID[" + tmsArriverRemoveVO.getLineId() + "],客户ID[" + tmsArriverRemoveVO.getCustomerId() + "],收货方ID[" + tmsArriverRemoveVO.getConsigneeId() + "]查询对数据为空");
                TmsLineConsigneeLinkModel TmsLineConsigneeLinkModel = TmsLineConsigneeLinkModels.get(0);

                // 删除
                tmsLineConsigneeLinkMapper.deleteByCriteria(criteria);

                // 获取配送顺序
                Integer index = TmsLineConsigneeLinkModel.getDeliveryOrder();
                Restriction r4 = Restrictions.lt("deliveryOrder", index);
                criteria.setRestriction(Restrictions.and(r1, r2, r3, r4));
                List<TmsLineConsigneeLinkModel> modelList = tmsLineConsigneeLinkMapper.findByCriteria(criteria);
                // 更改配送顺序
                for (TmsLineConsigneeLinkModel arriverModel : modelList) {
                    arriverModel.setDeliveryOrder(arriverModel.getDeliveryOrder() + 1);
                    tmsLineConsigneeLinkMapper.update(arriverModel);
                }
            }
            transactionManager.commit(transactionStatus);
        } catch (Exception e) {
            transactionManager.rollback(transactionStatus);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 线路-发货方删除
     *
     * @param list
     * @return
     */
    @Override
    public void tmsShipperRemove(List<TmsShipperRemoveVO> list) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(list, "参数不能为空！");
        DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);

        try {
            for (TmsShipperRemoveVO shipperRemoveVO : list) {
                ToolKits.isParamNull(shipperRemoveVO.getLineId(), "线路ID不能为空");
                ToolKits.isParamNull(shipperRemoveVO.getBranchId(), "仓库ID不能为空");

                Criteria criteria = Criteria.forClass(TmsLineShipperLinkModel.class);
                Restriction r1 = Restrictions.eq("lineId", shipperRemoveVO.getLineId());
                Restriction r2 = Restrictions.eq("branchId", shipperRemoveVO.getBranchId());
                Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                criteria.setRestriction(Restrictions.and(r1, r2, r3));

                List<TmsLineShipperLinkModel> shipperLinkModels = tmsLineShipperLinkMapper.findByCriteria(criteria);
                ToolKits.isParamNull(shipperLinkModels, "线路ID[" + shipperRemoveVO.getLineId() + "],仓库ID[" + shipperRemoveVO.getBranchId() + "]查询对数据为空");
                TmsLineShipperLinkModel shipperLinkModel = shipperLinkModels.get(0);
                // 删除
                tmsLineShipperLinkMapper.deleteByCriteria(criteria);

                // 获取提货顺序
                Integer index = shipperLinkModel.getPickupOrder();
                Restriction r4 = Restrictions.lt("pickupOrder", index);
                criteria.setRestriction(Restrictions.and(r1, r2, r3, r4));
                List<TmsLineShipperLinkModel> modelList = tmsLineShipperLinkMapper.findByCriteria(criteria);
                // 更改配送顺序
                for (TmsLineShipperLinkModel shipperModel : modelList) {
                    shipperModel.setPickupOrder(shipperModel.getPickupOrder() + 1);
                    tmsLineShipperLinkMapper.update(shipperModel);
                }
            }
            transactionManager.commit(transactionStatus);
        } catch (Exception e) {
            transactionManager.rollback(transactionStatus);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 线路-收货方新增
     *
     * @param list
     */
    @Override
    public void tmsArriverSave(List<TmsArriverVO> list) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(list, "参数不能为空！");

        List<Long> lineIds = list.stream().map(TmsArriverVO::getLineId).distinct().collect(Collectors.toList());
        ToolKits.isParamNull(lineIds, "收货方绑定的线路ID不可为空");
        if (lineIds.size() > 1) {
            throw new RuntimeException("收货方绑定的路线不是唯一");
        }

        for (TmsArriverVO tmsArriverVO : list) {
            ToolKits.isParamNull(tmsArriverVO.getCustomerId(), "客户ID不能为空");
            ToolKits.isParamNull(tmsArriverVO.getCustomerCode(), "客户编号不能为空");
            ToolKits.isParamNull(tmsArriverVO.getCustomerName(), "客户名称不能为空");
            ToolKits.isParamNull(tmsArriverVO.getConsigneeId(), "收货方ID不能为空");
            ToolKits.isParamNull(tmsArriverVO.getConsigneeCode(), "收货方编号不能为空");
            ToolKits.isParamNull(tmsArriverVO.getConsigneeName(), "收货方名称不能为空");
            ToolKits.isParamNull(tmsArriverVO.getConsigneeAddress(), "收货地址不能为空");
            ToolKits.isParamNull(tmsArriverVO.getConsigneePhoneNumber(), "联系方式不能为空");

            TmsArriverVO arriverVO = new TmsArriverVO();
            arriverVO.setCustomerId(tmsArriverVO.getCustomerId());
            arriverVO.setConsigneeId(tmsArriverVO.getConsigneeId());
            arriverVO.setEnterpriseId(user.getEnterpriseId());
            long count = tmsLineConsigneeLinkMapper.findCountByConsignee(tmsArriverVO);
            if (count > 0) {
                throw new RuntimeException("一个客户[" + tmsArriverVO.getCustomerName() + "]的一个收货方[" + tmsArriverVO.getConsigneeName() + "]当前只能存在于一个线路中");
            }

            Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
            Restriction r1 = Restrictions.eq("lineId", tmsArriverVO.getLineId());
            Restriction r2 = Restrictions.eq("customerId", tmsArriverVO.getCustomerId());
            Restriction r3 = Restrictions.eq("consigneeId", tmsArriverVO.getConsigneeId());
            Restriction r4 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            criteria.setRestriction(Restrictions.and(r1, r2, r3, r4));
            long count1 = tmsLineConsigneeLinkMapper.findCountByCriteria(criteria);

            TmsLineConsigneeLinkModel model = new TmsLineConsigneeLinkModel();
            BeanUtils.copyProperties(tmsArriverVO, model);
            model.setDeliveryOrder((int) count1 + 1);
            model.setSource(1);

            tmsLineConsigneeLinkMapper.save(model);
        }

    }

    /**
     * 线路-发货方新增
     *
     * @param list
     * @return
     */
    public void tmsShipperSave(List<TmsShipperVO> list) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(list, "参数不能为空！");

        List<Long> lineIds = list.stream().map(TmsShipperVO::getLineId).distinct().collect(Collectors.toList());
        ToolKits.isParamNull(lineIds, "发货方绑定的线路ID不可为空");
        if (lineIds.size() > 1) {
            throw new RuntimeException("发货方绑定的路线不是唯一");
        }

        for (TmsShipperVO shipperVO : list) {
            ToolKits.isParamNull(shipperVO.getLineId(), "线路ID不能为空");
            ToolKits.isParamNull(shipperVO.getBranchId(), "仓库ID不能为空");
            ToolKits.isParamNull(shipperVO.getBranchCode(), "仓库编号不能为空");
            ToolKits.isParamNull(shipperVO.getBranchName(), "仓库名称不能为空");
            ToolKits.isParamNull(shipperVO.getPickupOrder(), "提货顺序不能为空");

            shipperVO.setEnterpriseId(user.getEnterpriseId());
            long count = tmsLineShipperLinkMapper.findCountByShipper(shipperVO);
            if (count > 0) {
                throw new RuntimeException("仓库[" + shipperVO.getBranchName() + "]当前存在于线路中");
            }

            Criteria criteria = Criteria.forClass(TmsLineShipperLinkModel.class);
            Restriction r1 = Restrictions.eq("lineId", shipperVO.getLineId());
            Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            criteria.setRestriction(Restrictions.and(r1, r2));
            long count1 = tmsLineShipperLinkMapper.findCountByCriteria(criteria);

            TmsLineShipperLinkModel model = new TmsLineShipperLinkModel();
            BeanUtils.copyProperties(shipperVO, model);
            String linkId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_LINE_SHIPPER_LINK, "L");
            ToolKits.isParamNull(linkId, "获取线路发货方关联表ID失败！");

            model.setId(linkId);
            model.setPickupOrder((int) count1 + 1);
            model.setSource(DataDictionaryConstant.SOURCE_ADD);
            model.setCreateperson(user.getNickname());
            model.setCreatetime(DateUtils.nowDate());
            // 企业ID
            model.setEnterpriseId(user.getEnterpriseId());
            // 企业名称
            model.setEnterpriseName(user.getEnterpriseName());
            tmsLineShipperLinkMapper.save(model);
        }
    }

    /**
     * 线路-查看地图
     *
     * @param list
     * @return
     */
    @Override
    public List<TmsBaseTranslineMapDTO> selectMap(List<TmsBaseTranslineByIdsVO> list) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(list, "参数不能为空！");

        List<Long> ids = list.stream().filter(o -> ToolKits.isNotEmpty(o.getLineId())).map(TmsBaseTranslineByIdsVO::getLineId).collect(Collectors.toList());
        List<TmsBaseLineModel> tmsBaseTranslineModels = tmsBaseTranslineMapper.findByIds(TmsBaseLineModel.class, ids.toArray(), null);

        List<String> strList = tmsBaseTranslineModels.stream().filter(o -> o.getStatus() == StatusConstant.STATUS_DISABLE).map(TmsBaseLineModel::getLineName).collect(Collectors.toList());
        if (ToolKits.isNotEmpty(strList)) {
            throw new RuntimeException("线路[" + strList.stream().collect(Collectors.joining(",")) + "]已被停用不可操作");
        }
        List<String> collect1 = tmsBaseTranslineModels.stream().filter(o -> o.getDistinguishType() != DataDictionaryConstant.DISTINGUISH_TYPE_SHF).map(TmsBaseLineModel::getLineName).collect(Collectors.toList());
        if (ToolKits.isNotEmpty(collect1) && collect1.size() > 0) {
            throw new RuntimeException("只有划分类型为收货方时,才支持查看地图");
        }

        List<TmsBaseTranslineMapDTO> dtoList = Lists.newArrayList();
        // 获取收货方
        TmsBaseCustomerReceiverQueryVO tmsBaseCustomerReceiverQueryVO = new TmsBaseCustomerReceiverQueryVO();
        tmsBaseCustomerReceiverQueryVO.setEnterpriseId(user.getEnterpriseId());
        List<TmsBaseCustomerReceiverDTO> tmsBaseCustomerReceiverDTOS = tmsCustomerConsigneeMapper.queryTmsBaseCustomerReceiver(tmsBaseCustomerReceiverQueryVO, null);

        // 翻译字典
        List<String> params = Lists.newArrayList(DataDictionaryConstant.AGING_TIME_LINE);
        Map<String, Object> dicData = ConvertorUtil.listDropDownData(sysRefdatadService, params);

        for (TmsBaseLineModel tmsBaseTranslineModel : tmsBaseTranslineModels) {
            TmsBaseTranslineMapDTO dto = new TmsBaseTranslineMapDTO();
            BeanUtils.copyProperties(tmsBaseTranslineModel, dto);
            Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
            Restriction r1 = Restrictions.eq("lineId", tmsBaseTranslineModel.getLineId());
            Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            criteria.setRestriction(Restrictions.and(r1, r2));
            criteria.setOrder(Order.newInstance().asc(new String[]{"deliveryOrder"}));
            List<TmsLineConsigneeLinkModel> TmsLineConsigneeLinkModels = tmsLineConsigneeLinkMapper.findByCriteria(criteria);
            List<TmsArriverDTO> tmsArriverDTOS = Lists.newArrayList();

            criteria = Criteria.forClass(TmsBaseBranchModel.class);
            List<TmsBaseBranchModel> tmsBaseBranchModels = tmsBaseBranchMapper.findByCriteria(criteria);

            Integer sum = 0;
            // 判断是否有起点
            if (ToolKits.isNotEmpty(tmsBaseTranslineModel.getStartLineCode())) {
                List<TmsBaseBranchModel> collect = tmsBaseBranchModels.stream().filter(o -> o.getCode().equals(tmsBaseTranslineModel.getStartLineCode())).collect(Collectors.toList());
                TmsBaseBranchModel tmsBaseBranchModel = collect.get(0);
                dto.setStartLineLongitude(ToolKits.isEmpty(tmsBaseBranchModel.getLongitude()) ? 0 : tmsBaseBranchModel.getLongitude().doubleValue());
                dto.setStartLineLatitude(ToolKits.isEmpty(tmsBaseBranchModel.getLatitude()) ? 0 : tmsBaseBranchModel.getLatitude().doubleValue());
                sum++;
            }

            // 判断是否有终点
            if (ToolKits.isNotEmpty(tmsBaseTranslineModel.getEndLineCode())) {
                List<TmsBaseBranchModel> collect = tmsBaseBranchModels.stream().filter(o -> o.getCode().equals(tmsBaseTranslineModel.getEndLineCode())).collect(Collectors.toList());
                TmsBaseBranchModel tmsBaseBranchModel = collect.get(0);
                dto.setEndLineLongitude(ToolKits.isEmpty(tmsBaseBranchModel.getLongitude()) ? 0 : tmsBaseBranchModel.getLongitude().doubleValue());
                dto.setEndLineLatitude(ToolKits.isEmpty(tmsBaseBranchModel.getLatitude()) ? 0 : tmsBaseBranchModel.getLatitude().doubleValue());
                sum++;
            }

            // 判断是否少于两个点
            if (ToolKits.isEmpty(tmsBaseTranslineModel.getStartLineCode()) && ToolKits.isEmpty(tmsBaseTranslineModel.getEndLineCode())) {
                if (TmsLineConsigneeLinkModels.size() < 2) {
                    throw new RuntimeException("线路[" + tmsBaseTranslineModel.getLineName() + "]的收货方至少两个才可绘制地图");
                }
            } else if ((ToolKits.isNotEmpty(tmsBaseTranslineModel.getStartLineCode()) && ToolKits.isEmpty(tmsBaseTranslineModel.getEndLineCode())) || (ToolKits.isEmpty(tmsBaseTranslineModel.getStartLineCode()) && ToolKits.isNotEmpty(tmsBaseTranslineModel.getEndLineCode()))) {
                if (TmsLineConsigneeLinkModels.size() < 1) {
                    throw new RuntimeException("线路[" + tmsBaseTranslineModel.getLineName() + "]的收货方至少一个才可绘制地图");
                }
            }

            for (TmsLineConsigneeLinkModel TmsLineConsigneeLinkModel : TmsLineConsigneeLinkModels) {
                TmsArriverDTO tmsArriverDTO = new TmsArriverDTO();
                BeanUtils.copyProperties(TmsLineConsigneeLinkModel, tmsArriverDTO);

                List<TmsBaseCustomerReceiverDTO> collect = tmsBaseCustomerReceiverDTOS.stream().filter(o -> TmsLineConsigneeLinkModel.getConsigneeId().equals(o.getId())).collect(Collectors.toList());
                if (ToolKits.isNotEmpty(collect)) {
                    TmsBaseCustomerReceiverDTO tmsBaseCustomerReceiverDTO = collect.get(0);
                    tmsArriverDTO.setLongitude(tmsBaseCustomerReceiverDTO.getLongitude());
                    tmsArriverDTO.setLatitude(tmsBaseCustomerReceiverDTO.getLatitude());
                }
                tmsArriverDTO.setConsigneeAgingTimeLineName(ConvertorUtil.getName(dicData, DataDictionaryConstant.AGING_TIME_LINE, TmsLineConsigneeLinkModel.getConsigneeAgingTimeLine()));


                tmsArriverDTOS.add(tmsArriverDTO);
            }
            dto.setTmsArriverByMapDTOs(tmsArriverDTOS);
            dto.setTerminalNumber(tmsArriverDTOS.size() + sum);
            dtoList.add(dto);
        }
        return dtoList;
    }

    /**
     * 新-线路-查看地图
     *
     * @param list
     * @return
     */
    public List<TmsLineMapDTO> newSelectMap(List<TmsBaseTranslineByIdsVO> list) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(list, "参数不能为空！");

        List<TmsLineMapDTO> lineMapDTOS = Lists.newArrayList();

        List<Long> ids = list.stream().filter(o -> ToolKits.isNotEmpty(o.getLineId())).map(TmsBaseTranslineByIdsVO::getLineId).collect(Collectors.toList());
        List<TmsBaseLineModel> tmsBaseTranslineModels = tmsBaseTranslineMapper.findByIds(TmsBaseLineModel.class, ids.toArray(), null);

        List<String> strList = tmsBaseTranslineModels.stream().filter(o -> o.getStatus().intValue() == StatusConstant.STATUS_DISABLE.intValue()).map(TmsBaseLineModel::getLineName).collect(Collectors.toList());
        if (ToolKits.isNotEmpty(strList)) {
            throw new RuntimeException("线路[" + strList.stream().collect(Collectors.joining(",")) + "]已被停用不可操作");
        }

        // 获取收货方
        TmsBaseCustomerReceiverQueryVO tmsBaseCustomerReceiverQueryVO = new TmsBaseCustomerReceiverQueryVO();
        tmsBaseCustomerReceiverQueryVO.setEnterpriseId(user.getEnterpriseId());
        List<TmsBaseCustomerReceiverDTO> tmsBaseCustomerReceiverDTOS = tmsCustomerConsigneeMapper.queryTmsBaseCustomerReceiver(tmsBaseCustomerReceiverQueryVO, null);

        // 翻译字典
        List<String> params = Lists.newArrayList(DataDictionaryConstant.AGING_TIME_LINE);
        Map<String, Object> dicData = ConvertorUtil.listDropDownData(sysRefdatadService, params);

        for (TmsBaseLineModel tmsBaseTranslineModel : tmsBaseTranslineModels) {
            TmsLineMapDTO lineMapDTO = new TmsLineMapDTO();
            BeanUtils.copyProperties(tmsBaseTranslineModel, lineMapDTO);
            Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
            Restriction r1 = Restrictions.eq(tmsBaseTranslineModel::getLineId, tmsBaseTranslineModel.getLineId());
            Restriction r2 = Restrictions.eq(tmsBaseTranslineModel::getEnterpriseId, user.getEnterpriseId());
            criteria.setRestriction(Restrictions.and(r1, r2));
            List<TmsLineConsigneeLinkModel> TmsLineConsigneeLinkModels = tmsLineConsigneeLinkMapper.findByCriteria(criteria);
            List<TmsLineWaySiteDTO> lineWaySiteDTOS = Lists.newArrayList();

            for (TmsLineConsigneeLinkModel consigneeLinkModel : TmsLineConsigneeLinkModels) {
                TmsLineWaySiteDTO lineWaySiteDTO = new TmsLineWaySiteDTO();
                lineWaySiteDTO.setConsigneeAgingTime(consigneeLinkModel.getConsigneeAgingTime());
                lineWaySiteDTO.setConsigneeAgingTimeLine(consigneeLinkModel.getConsigneeAgingTimeLine());
                lineWaySiteDTO.setConsigneeAgingTimeLineName(ConvertorUtil.getName(dicData, DataDictionaryConstant.AGING_TIME_LINE, consigneeLinkModel.getConsigneeAgingTimeLine()));
                lineWaySiteDTO.setSiteOrder(consigneeLinkModel.getDeliveryOrder());
                lineWaySiteDTO.setSiteTypeName("送货");
                lineWaySiteDTO.setAddress(consigneeLinkModel.getConsigneeAddress());
                lineWaySiteDTO.setLinkId(consigneeLinkModel.getId());
                if (tmsBaseTranslineModel.getDistinguishType().equals(DataDictionaryConstant.DISTINGUISH_TYPE_SHF)) {
                    lineWaySiteDTO.setTypeName("客户-收货方");
                    lineWaySiteDTO.setSiteCode(consigneeLinkModel.getConsigneeCode());
                    lineWaySiteDTO.setSiteName(consigneeLinkModel.getConsigneeName());
                    List<TmsBaseCustomerReceiverDTO> collect = tmsBaseCustomerReceiverDTOS.stream().filter(o -> consigneeLinkModel.getConsigneeId().equals(o.getId()) && consigneeLinkModel.getCustomerId().equals(o.getCustomerId())).collect(Collectors.toList());
                    if (ToolKits.isNotEmpty(collect)) {
                        TmsBaseCustomerReceiverDTO tmsBaseCustomerReceiverDTO = collect.get(0);
                        lineWaySiteDTO.setLongitude(tmsBaseCustomerReceiverDTO.getLongitude());
                        lineWaySiteDTO.setLatitude(tmsBaseCustomerReceiverDTO.getLatitude());
                    }
                } else {
                    lineWaySiteDTO.setSiteCode(consigneeLinkModel.getConsigneeCode());
                    lineWaySiteDTO.setSiteName(consigneeLinkModel.getConsigneeName());
                    lineWaySiteDTO.setTypeName("行政区");
                }

                lineWaySiteDTOS.add(lineWaySiteDTO);
            }

            if (ToolKits.isNotEmpty(TmsLineConsigneeLinkModels)) {
                lineMapDTO.setDeliverySiteNumber(TmsLineConsigneeLinkModels.size());
            } else {
                lineMapDTO.setDeliverySiteNumber(0);
            }

            // 发货方
            TmsBaselineVO baselineVO = new TmsBaselineVO();
            baselineVO.setLineId(tmsBaseTranslineModel.getLineId());
            List<TmsShipperDTO> shipperDTOS = tmsLineShipperLinkMapper.queryLineShipper(baselineVO);
            for (TmsShipperDTO shipperDTO : shipperDTOS) {
                TmsLineWaySiteDTO lineWaySiteDTO = new TmsLineWaySiteDTO();
                lineWaySiteDTO.setShipperAgingTime(shipperDTO.getShipperAgingTime());
                lineWaySiteDTO.setShipperAgingTimeLine(shipperDTO.getShipperAgingTimeLine());
                lineWaySiteDTO.setShipperAgingTimeLineName(ConvertorUtil.getName(dicData, DataDictionaryConstant.AGING_TIME_LINE, shipperDTO.getShipperAgingTimeLine()));
                lineWaySiteDTO.setSiteOrder(shipperDTO.getPickupOrder());
                lineWaySiteDTO.setSiteTypeName("提货");
                if (tmsBaseTranslineModel.getStartLineType().equals(DataDictionaryConstant.START_LINE_TYPE_BRANCH)) {
                    lineWaySiteDTO.setTypeName("仓库");
                    lineWaySiteDTO.setAddress(shipperDTO.getAddress());
                    lineWaySiteDTO.setLongitude(shipperDTO.getLongitude());
                    lineWaySiteDTO.setLatitude(shipperDTO.getLatitude());
                } else {
                    lineWaySiteDTO.setTypeName("行政区");
                    lineWaySiteDTO.setAddress(shipperDTO.getShipperAddress());
                }
                lineWaySiteDTO.setSiteCode(shipperDTO.getBranchCode());
                lineWaySiteDTO.setSiteName(shipperDTO.getBranchName());
                lineWaySiteDTO.setLinkId(shipperDTO.getId());
                lineWaySiteDTOS.add(lineWaySiteDTO);
            }
            if (ToolKits.isNotEmpty(shipperDTOS)) {
                lineMapDTO.setPickUpSiteNumber(shipperDTOS.size());
            } else {
                lineMapDTO.setPickUpSiteNumber(0);
            }
            lineWaySiteDTOS = lineWaySiteDTOS.stream().filter(line -> ToolKits.isNotEmpty(line.getSiteOrder())).collect(Collectors.toList());
            lineWaySiteDTOS = lineWaySiteDTOS.stream().sorted(Comparator.comparing(TmsLineWaySiteDTO::getSiteOrder)).collect(Collectors.toList());

            lineMapDTO.setSiteDTOs(lineWaySiteDTOS);

            lineMapDTOS.add(lineMapDTO);
        }

        return lineMapDTOS;
    }

    /**
     * 新线路-站点信息
     *
     * @param ids
     * @return
     */
    public List<TmsLineMapDTO> lineSites(List<Long> ids) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(ids, "参数不能为空！");

        List<TmsLineMapDTO> lineMapDTOS = Lists.newArrayList();

        List<TmsBaseLineModel> tmsBaseTranslineModels = tmsBaseTranslineMapper.findByIds(TmsBaseLineModel.class, ids.toArray(), null);

        // 获取收货方
        TmsBaseCustomerReceiverQueryVO tmsBaseCustomerReceiverQueryVO = new TmsBaseCustomerReceiverQueryVO();
        tmsBaseCustomerReceiverQueryVO.setEnterpriseId(user.getEnterpriseId());
        List<TmsBaseCustomerReceiverDTO> tmsBaseCustomerReceiverDTOS = tmsCustomerConsigneeMapper.queryTmsBaseCustomerReceiver(tmsBaseCustomerReceiverQueryVO, null);

        // 翻译字典
        List<String> params = Lists.newArrayList(DataDictionaryConstant.AGING_TIME_LINE);
        Map<String, Object> dicData = ConvertorUtil.listDropDownData(sysRefdatadService, params);

        for (TmsBaseLineModel tmsBaseTranslineModel : tmsBaseTranslineModels) {
            if (!tmsBaseTranslineModel.getDistinguishType().equals(DataDictionaryConstant.DISTINGUISH_TYPE_SHF) && !tmsBaseTranslineModel.getStartLineType().equals(DataDictionaryConstant.START_LINE_TYPE_BRANCH)) {
                continue;
            }
            TmsLineMapDTO lineMapDTO = new TmsLineMapDTO();
            BeanUtils.copyProperties(tmsBaseTranslineModel, lineMapDTO);
            Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
            Restriction r1 = Restrictions.eq(tmsBaseTranslineModel::getLineId, tmsBaseTranslineModel.getLineId());
            Restriction r2 = Restrictions.eq(tmsBaseTranslineModel::getEnterpriseId, user.getEnterpriseId());
            criteria.setRestriction(Restrictions.and(r1, r2));
            List<TmsLineConsigneeLinkModel> TmsLineConsigneeLinkModels = tmsLineConsigneeLinkMapper.findByCriteria(criteria);
            List<TmsLineWaySiteDTO> lineWaySiteDTOS = Lists.newArrayList();

            for (TmsLineConsigneeLinkModel consigneeLinkModel : TmsLineConsigneeLinkModels) {
                TmsLineWaySiteDTO lineWaySiteDTO = new TmsLineWaySiteDTO();
                lineWaySiteDTO.setConsigneeAgingTime(consigneeLinkModel.getConsigneeAgingTime());
                lineWaySiteDTO.setConsigneeAgingTimeLine(consigneeLinkModel.getConsigneeAgingTimeLine());
                lineWaySiteDTO.setConsigneeAgingTimeLineName(ConvertorUtil.getName(dicData, DataDictionaryConstant.AGING_TIME_LINE, consigneeLinkModel.getConsigneeAgingTimeLine()));
                lineWaySiteDTO.setSiteOrder(consigneeLinkModel.getDeliveryOrder());
                lineWaySiteDTO.setSiteTypeName("送货");
                lineWaySiteDTO.setTypeName("客户-收货方");

                lineWaySiteDTO.setSiteCode(consigneeLinkModel.getConsigneeCode());
                lineWaySiteDTO.setSiteName(consigneeLinkModel.getConsigneeName());
                lineWaySiteDTO.setAddress(consigneeLinkModel.getConsigneeAddress());
                lineWaySiteDTO.setLinkId(consigneeLinkModel.getId());

                List<TmsBaseCustomerReceiverDTO> collect = tmsBaseCustomerReceiverDTOS.stream().filter(o -> consigneeLinkModel.getConsigneeId().equals(o.getId()) && consigneeLinkModel.getCustomerId().equals(o.getCustomerId())).collect(Collectors.toList());
                if (ToolKits.isNotEmpty(collect)) {
                    TmsBaseCustomerReceiverDTO tmsBaseCustomerReceiverDTO = collect.get(0);
                    lineWaySiteDTO.setLongitude(tmsBaseCustomerReceiverDTO.getLongitude());
                    lineWaySiteDTO.setLatitude(tmsBaseCustomerReceiverDTO.getLatitude());
                }

                lineWaySiteDTO.setCustomerId(consigneeLinkModel.getCustomerId());
                lineWaySiteDTO.setCustomerCode(consigneeLinkModel.getCustomerCode());
                lineWaySiteDTO.setCustomerName(consigneeLinkModel.getCustomerName());
                lineWaySiteDTO.setConsigneeId(consigneeLinkModel.getConsigneeId());
                lineWaySiteDTO.setConsigneeCode(consigneeLinkModel.getConsigneeCode());
                lineWaySiteDTO.setConsigneeName(consigneeLinkModel.getConsigneeName());

                lineWaySiteDTOS.add(lineWaySiteDTO);
            }

            if (ToolKits.isNotEmpty(TmsLineConsigneeLinkModels)) {
                lineMapDTO.setDeliverySiteNumber(TmsLineConsigneeLinkModels.size());
            } else {
                lineMapDTO.setDeliverySiteNumber(0);
            }

            // 发货方
            TmsBaselineVO baselineVO = new TmsBaselineVO();
            baselineVO.setLineId(tmsBaseTranslineModel.getLineId());
            List<TmsShipperDTO> shipperDTOS = tmsLineShipperLinkMapper.queryLineShipper(baselineVO);
            for (TmsShipperDTO shipperDTO : shipperDTOS) {
                TmsLineWaySiteDTO lineWaySiteDTO = new TmsLineWaySiteDTO();
                lineWaySiteDTO.setShipperAgingTime(shipperDTO.getShipperAgingTime());
                lineWaySiteDTO.setShipperAgingTimeLine(shipperDTO.getShipperAgingTimeLine());
                lineWaySiteDTO.setShipperAgingTimeLineName(ConvertorUtil.getName(dicData, DataDictionaryConstant.AGING_TIME_LINE, shipperDTO.getShipperAgingTimeLine()));
                lineWaySiteDTO.setSiteOrder(shipperDTO.getPickupOrder());
                lineWaySiteDTO.setSiteTypeName("提货");
                lineWaySiteDTO.setTypeName("仓库");

                lineWaySiteDTO.setSiteCode(shipperDTO.getBranchCode());
                lineWaySiteDTO.setSiteName(shipperDTO.getBranchName());
                lineWaySiteDTO.setAddress(shipperDTO.getAddress());
                lineWaySiteDTO.setLinkId(shipperDTO.getId());

                lineWaySiteDTO.setLongitude(shipperDTO.getLongitude());
                lineWaySiteDTO.setLatitude(shipperDTO.getLatitude());

                lineWaySiteDTO.setBranchId(shipperDTO.getBranchId());
                lineWaySiteDTO.setBranchCode(shipperDTO.getBranchCode());
                lineWaySiteDTO.setBranchName(shipperDTO.getBranchName());

                lineWaySiteDTOS.add(lineWaySiteDTO);
            }
            if (ToolKits.isNotEmpty(shipperDTOS)) {
                lineMapDTO.setPickUpSiteNumber(shipperDTOS.size());
            } else {
                lineMapDTO.setPickUpSiteNumber(0);
            }
            lineWaySiteDTOS = lineWaySiteDTOS.stream().sorted(Comparator.comparing(TmsLineWaySiteDTO::getSiteOrder)).collect(Collectors.toList());

            lineMapDTO.setSiteDTOs(lineWaySiteDTOS);

            lineMapDTOS.add(lineMapDTO);
        }
        return lineMapDTOS;
    }

    /**
     * 线路-站点移动
     *
     * @param lineMoveVO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void lineMove(TmsLineMoveVO lineMoveVO) {
        ToolKits.isParamNull(lineMoveVO, "参数不能为空！");
        ToolKits.isParamNull(lineMoveVO.getTargetLineId(), "移动的目标线路ID不能为空！");
        ToolKits.isParamNull(lineMoveVO.getSourceLineMoveSiteVO(), "移动的原线路站点信息不能为空！");

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

        // 原线路站点删除
        TmsLineMoveSiteVO sourceLineMoveSiteVO = lineMoveVO.getSourceLineMoveSiteVO();
        if (sourceLineMoveSiteVO.getSiteTypeName().equals(DataDictionaryConstant.SITE_TYPE_NAME_CONSIGNEE)) {
            // 删除收货方站点
            TmsLineConsigneeLinkModel sourceSite = tmsLineConsigneeLinkMapper.findById(sourceLineMoveSiteVO.getLinkId(), TmsLineConsigneeLinkModel.class);
            if (ToolKits.isEmpty(sourceSite)) {
                throw new PrologException("线路客户收货方【" + sourceLineMoveSiteVO.getSiteCode() + "】不存在");
            }
            tmsLineConsigneeLinkMapper.deleteById(sourceLineMoveSiteVO.getLinkId(), TmsLineConsigneeLinkModel.class);

            // 目标线路的客户收货方增加
            TmsLineConsigneeLinkModel consigneeLinkModel = new TmsLineConsigneeLinkModel();
            BeanUtils.copyProperties(sourceSite, consigneeLinkModel);
            String linkId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_LINE_CONSIGNEE_LINK, "L");
            ToolKits.isParamNull(linkId, "获取线路收货方关联表ID失败！");

            consigneeLinkModel.setId(linkId);
            consigneeLinkModel.setLineId(lineMoveVO.getTargetLineId());
            consigneeLinkModel.setLineCode(lineMoveVO.getTargetLineCode());
            consigneeLinkModel.setLineName(lineMoveVO.getTargetLineName());
            consigneeLinkModel.setSource(DataDictionaryConstant.SOURCE_ADD);
            consigneeLinkModel.setCreateperson(user.getNickname());
            consigneeLinkModel.setCreatetime(date);
            // 企业ID
            consigneeLinkModel.setEnterpriseId(user.getEnterpriseId());
            // 企业名称
            consigneeLinkModel.setEnterpriseName(user.getEnterpriseName());
            tmsLineConsigneeLinkMapper.save(consigneeLinkModel);
        } else if (sourceLineMoveSiteVO.getSiteTypeName().equals(DataDictionaryConstant.SITE_TYPE_NAME_SHIPPER)) {
            // 删除发货方站点
            TmsLineShipperLinkModel sourceSite = tmsLineShipperLinkMapper.findById(sourceLineMoveSiteVO.getLinkId(), TmsLineShipperLinkModel.class);
            if (ToolKits.isEmpty(sourceSite)) {
                throw new PrologException("线路的仓库【" + sourceLineMoveSiteVO.getSiteCode() + "】不存在");
            }
            tmsLineShipperLinkMapper.deleteById(sourceLineMoveSiteVO.getLinkId(), TmsLineShipperLinkModel.class);

            // 目标线路的客户收货方增加
            TmsLineShipperLinkModel shipperLinkModel = new TmsLineShipperLinkModel();
            BeanUtils.copyProperties(sourceSite, shipperLinkModel);
            String linkId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_LINE_SHIPPER_LINK, "L");
            ToolKits.isParamNull(linkId, "获取线路发货方关联表ID失败！");

            shipperLinkModel.setId(linkId);
            shipperLinkModel.setLineId(lineMoveVO.getTargetLineId());
            shipperLinkModel.setLineCode(lineMoveVO.getTargetLineCode());
            shipperLinkModel.setLineName(lineMoveVO.getTargetLineName());
            shipperLinkModel.setSource(DataDictionaryConstant.SOURCE_ADD);
            shipperLinkModel.setCreateperson(user.getNickname());
            shipperLinkModel.setCreatetime(date);
            // 企业ID
            shipperLinkModel.setEnterpriseId(user.getEnterpriseId());
            // 企业名称
            shipperLinkModel.setEnterpriseName(user.getEnterpriseName());
            tmsLineShipperLinkMapper.save(shipperLinkModel);
        }
    }

    /**
     * 线路地图弹窗
     *
     * @param list
     * @return
     */
    @Override
    public List<LineByMapDTO> selectLineByMap(List<String> list) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(list, "线路ID不能为空！");

        Criteria criteria = Criteria.forClass(TmsBaseLineModel.class);
        Restriction r1 = Restrictions.in("lineId", list.toArray());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));

        List<TmsBaseLineModel> tmsBaseTranslineModels = tmsBaseTranslineMapper.findByCriteria(criteria);
        List<LineByMapDTO> dtos = Lists.newArrayList();
        for (TmsBaseLineModel tmsBaseTranslineModel : tmsBaseTranslineModels) {
            LineByMapDTO dto = new LineByMapDTO();
            BeanUtils.copyProperties(tmsBaseTranslineModel, dto);
            dtos.add(dto);
        }

        return dtos;
    }

    /**
     * 查询地图明细
     *
     * @param vo
     * @return
     */
    @Override
    public List<TmsBaseTranslineMapDetailsDTO> selectMapDetails(TmsBaseTranslineMapDetailsVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(vo.getLineIds(), "线路ID不能为空不能为空！");
        vo.setEnterpriseId(user.getEnterpriseId());
        List<TmsBaseTranslineMapDetailsDTO> list = tmsBaseTranslineMapper.selectMapDetails(vo);

        return list;
    }

    /**
     * 线路-地图修改
     *
     * @param list
     */
    @Override
    public void saveMap(List<TmsBaseTranslineMapVO> list) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(list, "参数不能为空！");

        DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);

        try {
            for (TmsBaseTranslineMapVO vo : list) {
                ToolKits.isParamNull(vo.getLineId(), "线路ID不能为空");
                ToolKits.isParamNull(vo.getCustomerId(), "客户ID不能为空");
                ToolKits.isParamNull(vo.getConsigneeId(), "收货方ID不能为空");
                ToolKits.isParamNull(vo.getDeliveryOrder(), "配送顺序不能为空");
                TmsBaseLineModel model = tmsBaseTranslineMapper.findById(vo.getLineId(), TmsBaseLineModel.class);
                ToolKits.isParamNull(model, "线路ID[" + vo.getLineId() + "]有误");

                // 修改现有收货方
                Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
                Restriction r1 = Restrictions.eq("customerId", vo.getCustomerId());
                Restriction r2 = Restrictions.eq("consigneeId", vo.getConsigneeId());
                Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                criteria.setRestriction(Restrictions.and(r1, r2, r3));

                Map<String, Object> map = Maps.newHashMap();
                map.put("lineId", vo.getLineId());
                map.put("updateperson", user.getNickname());
                map.put("updatetime", DateUtils.nowDate());
                map.put("deliveryOrder", vo.getDeliveryOrder());
                tmsLineConsigneeLinkMapper.updateMapByCriteria(map, criteria);
            }

            transactionManager.commit(transactionStatus);
        } catch (Exception e) {
            transactionManager.rollback(transactionStatus);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 线路-地图修改
     *
     * @param lineMapSaveVOS
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void newSaveMap(List<TmsLineMapSaveVO> lineMapSaveVOS) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(lineMapSaveVOS, "参数不能为空！");

        Date date = DateUtil.date();

        for (TmsLineMapSaveVO lineMapSaveVO : lineMapSaveVOS) {
            ToolKits.isParamNull(lineMapSaveVO.getLineId(), "线路ID不能为空！");
            ToolKits.isParamNull(lineMapSaveVO.getSiteDTOs(), "线路的站点信息不能为空！");
            // 更新线路的总里程，站点数
            Map<String, Object> mapUpdateLine = Maps.newHashMap();
            mapUpdateLine.put("updateperson", user.getNickname());
            mapUpdateLine.put("updatetime", date);
            mapUpdateLine.put("pickUpSiteNumber", lineMapSaveVO.getPickUpSiteNumber());
            mapUpdateLine.put("deliverySiteNumber", lineMapSaveVO.getDeliverySiteNumber());
            mapUpdateLine.put("totalStations", lineMapSaveVO.getTotalStations());
            mapUpdateLine.put("totalMileage", lineMapSaveVO.getTotalMileage());
            tmsBaseTranslineMapper.updateMapById(lineMapSaveVO.getLineId(), mapUpdateLine, TmsBaseLineModel.class);

            for (TmsLineMapSiteSaveVO mapSiteSaveVO : lineMapSaveVO.getSiteDTOs()) {
                if (mapSiteSaveVO.getSiteTypeName().equals(DataDictionaryConstant.SITE_TYPE_NAME_CONSIGNEE)) {
                    // 修改收货方站点
                    Map<String, Object> mapLineConsigneeUpdateLine = Maps.newHashMap();
                    mapLineConsigneeUpdateLine.put("updateperson", user.getNickname());
                    mapLineConsigneeUpdateLine.put("updatetime", date);
                    mapLineConsigneeUpdateLine.put("deliveryOrder", mapSiteSaveVO.getSiteOrder());
                    tmsLineConsigneeLinkMapper.updateMapById(mapSiteSaveVO.getLinkId(), mapLineConsigneeUpdateLine, TmsLineConsigneeLinkModel.class);
                } else if (mapSiteSaveVO.getSiteTypeName().equals(DataDictionaryConstant.SITE_TYPE_NAME_SHIPPER)) {
                    // 更新发货方站点信息
                    Map<String, Object> mapLineShipperUpdateLine = Maps.newHashMap();
                    mapLineShipperUpdateLine.put("updateperson", user.getNickname());
                    mapLineShipperUpdateLine.put("updatetime", date);
                    mapLineShipperUpdateLine.put("pickupOrder", mapSiteSaveVO.getSiteOrder());
                    tmsLineShipperLinkMapper.updateMapById(mapSiteSaveVO.getLinkId(), mapLineShipperUpdateLine, TmsLineShipperLinkModel.class);
                }
            }
        }

    }

    /**
     * 线路-计算里程
     *
     * @param list
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object calculate(List<TmsBaseTranslineByCalculateVO> list) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(list, "参数不能为空");
        String sum = "";
        for (TmsBaseTranslineByCalculateVO vo : list) {
            ToolKits.isParamNull(vo.getLineId(), "线路ID不能为空");
            TmsBaseLineModel model = tmsBaseTranslineMapper.findById(vo.getLineId(), TmsBaseLineModel.class);
            if (ToolKits.isNotEmpty(model.getDistinguishType()) && model.getDistinguishType() != DataDictionaryConstant.DISTINGUISH_TYPE_SHF) {
                throw new RuntimeException("只有划分类型为收货方时,才支持计算里程");
            }
            ToolKits.isParamNull(model, "线路ID[" + vo.getLineId() + "]有误,查询为空!");

            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            if (ToolKits.isNotEmpty(vo.getDistance())) {
                sum = decimalFormat.format((float) vo.getDistance() / (float) 1000);
            } else {
                sum = "0";
            }

            model.setTotalMileage(new BigDecimal(sum));
            tmsBaseTranslineMapper.update(model);
        }
        if (list.size() > 1) {
            return null;
        } else {
            return sum;
        }
    }

    /**
     * 线路-承运方查询
     *
     * @param vo
     * @return
     */
    @Override
    public Page<TmsCarrierDTO> tmsCarrierPage(TmsCarrierVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(vo, "参数不能为空！");
        ToolKits.isParamNull(vo.getPageNum(), "当前页码不能为空");
        ToolKits.isParamNull(vo.getPageSize(), "每页条数不能为空");

        Criteria criteria = Criteria.forClass(TmsLineCarrierLinkModel.class);
        Restriction r1 = ToolKits.isEmpty(vo.getLineId()) ? null : Restrictions.eq("lineId", vo.getLineId());
        Restriction r2 = ToolKits.isEmpty(vo.getCarrierCode()) ? null : Restrictions.like("carrierCode", "%" + vo.getCarrierCode() + "%");
        Restriction r3 = ToolKits.isEmpty(vo.getCarrierName()) ? null : Restrictions.like("carrierName", "%" + vo.getCarrierName() + "%");
        Restriction r4 = ToolKits.isEmpty(vo.getPhoneNumber()) ? null : Restrictions.like("phoneNumber", "%" + vo.getPhoneNumber() + "%");
        Restriction r5 = ToolKits.isEmpty(vo.getVehiclePlateNumber()) ? null : Restrictions.like("vehiclePlateNumber", "%" + vo.getVehiclePlateNumber() + "%");
        criteria.setRestriction(Restrictions.and(r1, r2, r3, r4, r5));

        PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
        List<TmsLineCarrierLinkModel> tmsLineCarrierLinkModels = tmsLineCarrierLinkMapper.findByCriteria(criteria);

        List<TmsCarrierDTO> dtos = Lists.newArrayList();
        for (TmsLineCarrierLinkModel tmsLineCarrierLinkModel : tmsLineCarrierLinkModels) {
            TmsCarrierDTO dto = new TmsCarrierDTO();
            BeanUtils.copyProperties(tmsLineCarrierLinkModel, dto);
            dtos.add(dto);
        }

        Page<TmsCarrierDTO> page = PageUtils.getPage(dtos);
        return page;
    }

    /**
     * 线路-收货方查询
     *
     * @param vo
     * @return
     */
    @Override
    public Page<TmsArriverDTO> tmsArriverPage(TmsArriverVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(vo, "参数不能为空！");
        ToolKits.isParamNull(vo.getPageNum(), "当前页码不能为空");
        ToolKits.isParamNull(vo.getPageSize(), "每页条数不能为空");

        Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
        Restriction r1 = ToolKits.isEmpty(vo.getLineId()) ? null : Restrictions.eq("lineId", vo.getLineId());
        Restriction r2 = ToolKits.isEmpty(vo.getCustomerId()) ? null : Restrictions.eq("customerId", vo.getCustomerId());
        Restriction r3 = ToolKits.isEmpty(vo.getCustomerName()) ? null : Restrictions.like("customerName", "%" + vo.getCustomerName() + "%");
        Restriction r4 = ToolKits.isEmpty(vo.getConsigneeId()) ? null : Restrictions.eq("consigneeId", vo.getConsigneeId());
        Restriction r5 = ToolKits.isEmpty(vo.getConsigneeName()) ? null : Restrictions.like("arriverName", "%" + vo.getConsigneeName() + "%");
        Restriction r6 = ToolKits.isEmpty(vo.getConsigneePhoneNumber()) ? null : Restrictions.like("consigneeTel", "%" + vo.getConsigneePhoneNumber() + "%");
        Restriction r7 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2, r3, r4, r5, r6, r7));

        PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
        List<TmsLineConsigneeLinkModel> TmsLineConsigneeLinkModels = tmsLineConsigneeLinkMapper.findByCriteria(criteria);
        // 翻译字典
        List<String> params = Lists.newArrayList(DataDictionaryConstant.AGING_TIME_LINE);
        Map<String, Object> dicData = ConvertorUtil.listDropDownData(sysRefdatadService, params);

        List<TmsArriverDTO> dtos = Lists.newArrayList();
        for (TmsLineConsigneeLinkModel TmsLineConsigneeLinkModel : TmsLineConsigneeLinkModels) {
            TmsArriverDTO dto = new TmsArriverDTO();
            TmsCustomerConsignee tmsCustomerConsignee = tmsCustomerConsigneeMapper.findById(TmsLineConsigneeLinkModel.getConsigneeId(), TmsCustomerConsignee.class);
            BeanUtils.copyProperties(TmsLineConsigneeLinkModel, dto);

            dto.setLatitude(tmsCustomerConsignee.getLatitude());
            dto.setLongitude(tmsCustomerConsignee.getLongitude());
            dto.setConsigneeAgingTimeLineName(ConvertorUtil.getName(dicData, DataDictionaryConstant.AGING_TIME_LINE, TmsLineConsigneeLinkModel.getConsigneeAgingTimeLine()));
            dtos.add(dto);
        }

        Page<TmsArriverDTO> page = PageUtils.getPage(dtos);
        return page;
    }

    /**
     * 线路-收,发货方关联表查询
     *
     * @param lineIds
     * @return
     */
    public List<LineShipperConsigneeDTO> queryLineShipperConsignee(List<Long> lineIds) {
        log.info("线路{}的收,发货方信息查询开始", JSONUtil.toJsonStr(lineIds));
        if (ToolKits.isEmpty(lineIds)) {
            return null;
        }
        List<LineShipperConsigneeDTO> shipperConsigneeDTOS = Lists.newArrayList();
        // 翻译字典
        List<String> params = Lists.newArrayList(DataDictionaryConstant.AGING_TIME_LINE);
        Map<String, Object> dicData = ConvertorUtil.listDropDownData(sysRefdatadService, params);
        Criteria criteriaConsignee = Criteria.forClass(TmsLineConsigneeLinkModel.class);
        Restriction r1 = Restrictions.in(TmsLineConsigneeLinkModel::getLineId, lineIds);
        criteriaConsignee.setRestriction(Restrictions.and(r1));
        List<TmsArriverDTO> arriverDTOS = Lists.newArrayList();
        List<TmsLineConsigneeLinkModel> tmsLineConsigneeLinkModels = tmsLineConsigneeLinkMapper.findByCriteria(criteriaConsignee);
        if (ToolKits.isEmpty(tmsLineConsigneeLinkModels)) {
            return null;
        }
        tmsLineConsigneeLinkModels.stream().forEach(consignee -> {
            TmsArriverDTO dto = new TmsArriverDTO();
            dto.setConsigneeCode(consignee.getConsigneeCode());
            dto.setConsigneeName(consignee.getConsigneeName());
            dto.setCustomerName(consignee.getCustomerName());
            dto.setLineId(consignee.getLineId());
            dto.setConsigneeAgingTimeLineName(ConvertorUtil.getName(dicData, DataDictionaryConstant.AGING_TIME_LINE, consignee.getConsigneeAgingTimeLine()));
            arriverDTOS.add(dto);
        });
        Criteria criteriaShipper = Criteria.forClass(TmsLineShipperLinkModel.class);
        r1 = Restrictions.in(TmsLineShipperLinkModel::getLineId, lineIds);
        criteriaShipper.setRestriction(Restrictions.and(r1));

        List<TmsLineShipperLinkModel> tmsLineShipperLinkModels = tmsLineShipperLinkMapper.findByCriteria(criteriaShipper);
        if (ToolKits.isEmpty(tmsLineShipperLinkModels)) {
            return null;
        }
        Map<Object, List<TmsLineShipperLinkModel>> shipperMap = Maps.newHashMap();

        shipperMap = tmsLineShipperLinkModels.stream().collect(Collectors.groupingBy(TmsLineShipperLinkModel::getLineId));

        if (ToolKits.isEmpty(shipperMap)) {
            return null;
        }
        shipperMap.entrySet().forEach(entry -> {
            LineShipperConsigneeDTO shipperConsigneeDTO = new LineShipperConsigneeDTO();
            shipperConsigneeDTO.setLineId(entry.getValue().get(0).getLineId());

            List<TmsShipperDTO> shipperDTOS = Lists.newArrayList();
            entry.getValue().stream().forEach(shipper-> {
                        TmsShipperDTO dto = new TmsShipperDTO();
                        dto.setBranchCode(shipper.getBranchCode());
                        dto.setBranchName(shipper.getBranchName());
                        dto.setBranchId(shipper.getBranchId());
                        dto.setLineId(shipper.getLineId());
                        dto.setShipperAgingTimeLineName(ConvertorUtil.getName(dicData, DataDictionaryConstant.AGING_TIME_LINE, shipper.getShipperAgingTimeLine()));
                        shipperDTOS.add(dto);
                    }
            );
            shipperConsigneeDTO.setShipperDTOS(shipperDTOS);

            List<TmsArriverDTO> lineArriverDTOS = arriverDTOS.stream().filter(lc->lc.getLineId().equals(entry.getValue().get(0).getLineId())).collect(Collectors.toList());
            if (ToolKits.isNotEmpty(lineArriverDTOS)) {
                shipperConsigneeDTO.setConsigneeDTOS(lineArriverDTOS);
            }
            shipperConsigneeDTOS.add(shipperConsigneeDTO);
        });
        log.info("线路的收,发货方查询到的信息{}", JSONUtil.toJsonStr(shipperConsigneeDTOS));
        return shipperConsigneeDTOS;
    }

    /**
     * 线路-发货方分页查询
     *
     * @param vo
     * @return
     */
    public Page<TmsShipperDTO> tmsLineShipperPage(TmsLineShipperVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(vo, "参数不能为空！");
        ToolKits.isParamNull(vo.getPageNum(), "当前页码不能为空");
        ToolKits.isParamNull(vo.getPageSize(), "每页条数不能为空");

        TmsBaselineVO shipperVo = new TmsBaselineVO();
        shipperVo.setEnterpriseId(user.getEnterpriseId());
        shipperVo.setLineId(vo.getLineId());
        PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
        List<TmsShipperDTO> shippers = tmsLineShipperLinkMapper.queryLineShipper(shipperVo);
        if (CollectionUtil.isNotEmpty(shippers)) {
            // 翻译字典
            List<String> params = Lists.newArrayList(DataDictionaryConstant.AGING_TIME_LINE);
            Map<String, Object> dicData = ConvertorUtil.listDropDownData(sysRefdatadService, params);
            shippers = shippers.stream().peek(shipper -> shipper.setShipperAgingTimeLineName(ConvertorUtil.getName(dicData, DataDictionaryConstant.AGING_TIME_LINE, shipper.getShipperAgingTimeLine()))).collect(Collectors.toList());
        }
        Page<TmsShipperDTO> page = PageUtils.getPage(shippers);
        return page;
    }

    /**
     * 线路-发货方查询
     *
     * @param lineShipperQueryVO
     * @return
     */
    public List<TmsShipperDTO> tmsLineShipperQuery(TmsLineShipperQueryVO lineShipperQueryVO) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(lineShipperQueryVO, "参数不能为空！");

        TmsBaselineVO shipperVo = new TmsBaselineVO();
        shipperVo.setEnterpriseId(user.getEnterpriseId());
        shipperVo.setLineId(lineShipperQueryVO.getLineId());
        List<TmsShipperDTO> shippers = tmsLineShipperLinkMapper.queryLineShipper(shipperVo);
        if (CollectionUtil.isNotEmpty(shippers)) {
            // 翻译字典
            List<String> params = Lists.newArrayList(DataDictionaryConstant.AGING_TIME_LINE);
            Map<String, Object> dicData = ConvertorUtil.listDropDownData(sysRefdatadService, params);
            shippers = shippers.stream().peek(shipper -> shipper.setShipperAgingTimeLineName(ConvertorUtil.getName(dicData, DataDictionaryConstant.AGING_TIME_LINE, shipper.getShipperAgingTimeLine()))).collect(Collectors.toList());
        }
        return shippers;
    }

    /**
     * 线路-行政区域查询
     *
     * @param vo
     * @return
     */
    @Override
    public List<String> getAdministrativeAreas(TmsArriverVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(vo, "参数不能为空！");
        ToolKits.isParamNull(vo.getLineId(), "线路ID不能为空！");

        TmsBaseLineModel tmsBaseLineModel = tmsBaseTranslineMapper.findById(vo.getLineId(), TmsBaseLineModel.class);
        ToolKits.isParamNull(tmsBaseLineModel, "线路ID[" + vo.getLineId() + "]有误,查询为空!");

        List<String> list = Lists.newArrayList();
        if (ToolKits.isNotEmpty(tmsBaseLineModel.getAdministrativeAreas())) {
            String[] administrativeAreas = tmsBaseLineModel.getAdministrativeAreas().split(",");
            list = Arrays.asList(administrativeAreas);
        }
        return list;
    }

    /**
     * 线路-日期保存
     *
     * @param vo
     */
    @Override
    public void dateSave(TmsBaseTranslineByDateVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(vo.getLineId(), "线路ID不能为空！");

        TmsBaseLineModel model = tmsBaseTranslineMapper.findById(vo.getLineId(), TmsBaseLineModel.class);
        ToolKits.isParamNull(model, "线路ID[" + vo.getLineId() + "]有误");

        Map<String, Object> weekMap = conversion(vo.getWeeks(), null);
        Map<String, Object> dayMap = conversion(vo.getDays(), null);

        model.setWeek(weekMap.get("str").toString());
        model.setDay(dayMap.get("str").toString());

        tmsBaseTranslineMapper.update(model);

    }

    /**
     * 线路-日期查询
     *
     * @param vo
     * @return
     */
    @Override
    public TmsBaseTranslineByDateDTO dateQuery(TmsBaseTranslineByIdsVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(vo.getLineId(), "线路ID不能为空！");

        TmsBaseLineModel model = tmsBaseTranslineMapper.findById(vo.getLineId(), TmsBaseLineModel.class);
        ToolKits.isParamNull(model, "线路ID[" + vo.getLineId() + "]有误");

        Map<String, Object> weekMap = conversion(null, model.getWeek());
        Map<String, Object> dayMap = conversion(null, model.getDay());

        TmsBaseTranslineByDateDTO dto = new TmsBaseTranslineByDateDTO();
        dto.setLineId(model.getLineId());
        dto.setWeeks(weekMap);
        dto.setDays(dayMap);

        return dto;
    }

    /**
     * 日期格式转换
     *
     * @param map
     * @param str
     * @return
     */
    private Map<String, Object> conversion(Map<String, Object> map, String str) {
        Map<String, Object> dataMap = Maps.newHashMap();
        if (ToolKits.isNotEmpty(map)) {
            StringBuffer stringBuffer = new StringBuffer();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                stringBuffer.append(entry.getKey());
                stringBuffer.append(":");
                stringBuffer.append(entry.getValue());
                stringBuffer.append(",");
            }
            if (stringBuffer.charAt(stringBuffer.length() - 1) == ',') {
                dataMap.put("str", stringBuffer.substring(0, stringBuffer.length() - 1));
                return dataMap;
            } else {
                dataMap.put("str", stringBuffer);
                return dataMap;
            }
        } else if (ToolKits.isNotEmpty(str)) {
            try {
                String[] split = str.split(",");
                for (String s : split) {
                    String[] split1 = s.split(":");
                    dataMap.put(split1[0], split1[1]);
                }
            } catch (ArrayIndexOutOfBoundsException a) {
                throw new RuntimeException("查询失败[字段格式有误]");
            }
            return dataMap;
        }
        return dataMap;
    }

    /**
     * 线路导入撤销
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void rollbackData(String batchno) throws Exception {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限！");
        ToolKits.isParamNull(batchno, "导入批次号不能为空");

        Criteria criteria = Criteria.forClass(TmsBaseLineModel.class);
        Restriction r1 = Restrictions.eq("importBatchNumber", batchno);
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        List<TmsBaseLineModel> tmsBaseShipperModels = tmsBaseTranslineMapper.findByCriteria(criteria);

        if (ToolKits.isEmpty(tmsBaseShipperModels)) {
            throw new ParameterException("批次号[" + batchno + "]错误，查询为空");
        }

        for (TmsBaseLineModel model : tmsBaseShipperModels) {
            // 删除收货方
            Criteria consigneeCriteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
            Restriction consigneeR1 = Restrictions.eq("lineId", model.getLineId());
            Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            consigneeCriteria.setRestriction(Restrictions.and(consigneeR1, r3));

            tmsLineConsigneeLinkMapper.deleteByCriteria(consigneeCriteria);

            // 删除承运商
            Criteria carrierCriteria = Criteria.forClass(TmsLineCarrierLinkModel.class);
            Restriction carrierR1 = Restrictions.eq("lineId", model.getLineId());
            carrierCriteria.setRestriction(Restrictions.and(carrierR1));

            tmsLineCarrierLinkMapper.deleteByCriteria(consigneeCriteria);
        }

        tmsBaseTranslineMapper.deleteByCriteria(criteria);
    }

    /**
     * 线路-收货方导入撤销
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void rollbackConsigneeData(String batchno) throws Exception {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限！");
        ToolKits.isParamNull(batchno, "导入批次号不能为空");

        Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
        Restriction r1 = Restrictions.eq("importBatchNumber", batchno);
        criteria.setRestriction(r1);
        List<TmsLineConsigneeLinkModel> tmsLineConsigneeLinkModels = tmsLineConsigneeLinkMapper.findByCriteria(criteria);

        if (ToolKits.isEmpty(tmsLineConsigneeLinkModels)) {
            throw new ParameterException("批次号[" + batchno + "]错误，查询为空");
        }

        tmsLineConsigneeLinkMapper.deleteByCriteria(criteria);
    }

    /**
     * 线路-发货方导入撤销
     *
     * @param batchno
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void rollbackShipperData(String batchno) throws Exception {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限！");
        ToolKits.isParamNull(batchno, "导入批次号不能为空");

        Criteria criteria = Criteria.forClass(TmsLineShipperLinkModel.class);
        Restriction r1 = Restrictions.eq(TmsLineShipperLinkModel::getImportBatchNumber, batchno);
        criteria.setRestriction(r1);
        List<TmsLineShipperLinkModel> tmsLineShipperLinkModels = tmsLineShipperLinkMapper.findByCriteria(criteria);

        if (ToolKits.isEmpty(tmsLineShipperLinkModels)) {
            throw new ParameterException("批次号[" + batchno + "]错误，查询为空");
        }

        tmsLineShipperLinkMapper.deleteByCriteria(criteria);
    }

    /**
     * 线路-承运方导入撤销
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void rollbackCarrierData(String batchno) throws Exception {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限！");
        ToolKits.isParamNull(batchno, "导入批次号不能为空");

        Criteria criteria = Criteria.forClass(TmsLineCarrierLinkModel.class);
        Restriction r1 = Restrictions.eq("importBatchNumber", batchno);
        criteria.setRestriction(r1);
        List<TmsLineCarrierLinkModel> tmsLineCarrierLinkModels = tmsLineCarrierLinkMapper.findByCriteria(criteria);

        if (ToolKits.isEmpty(tmsLineCarrierLinkModels)) {
            throw new ParameterException("批次号[" + batchno + "]错误，查询为空");
        }

        tmsLineCarrierLinkMapper.deleteByCriteria(criteria);
    }

    /**
     * 线路导入分页查询
     */
    @Override
    @SuppressWarnings("resource")
    public RestMessage<Object> pageLineByImportBatchNumberData(ImportPageVO importPageVO) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");

        // 响应对象集合
        List<LineImportPageDTO> lineImportPageDTOs = new ArrayList<LineImportPageDTO>();

        // 判断账号类型
        if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
            // 自有账号
            importPageVO.setDepartmentIds(user.getDepts().stream().toArray(String[]::new));
            importPageVO.setIsDept("Y");
        } else {
            throw new BizException("当前人员没有操作权限！");
        }
        // 分页
        PageUtils.startPage(importPageVO.getPageNum(), importPageVO.getPageSize());
        List<TmsBaseTranslineDTO> tmsBaseTranslineModels = tmsBaseTranslineMapper.queryImport(importPageVO);

        for (TmsBaseTranslineDTO tmsBaseTranslineModel : tmsBaseTranslineModels) {
            // 响应对象
            LineImportPageDTO lineImportPageDTO = new LineImportPageDTO();
            BeanUtils.copyProperties(tmsBaseTranslineModel, lineImportPageDTO);
            lineImportPageDTOs.add(lineImportPageDTO);
        }

        Page<LineImportPageDTO> page = PageUtils.getPage(lineImportPageDTOs);
        if (tmsBaseTranslineModels instanceof com.github.pagehelper.Page) {
            com.github.pagehelper.Page<TmsBaseTranslineDTO> p0 = (com.github.pagehelper.Page<TmsBaseTranslineDTO>) tmsBaseTranslineModels;
            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 RestMessage.newInstance(true, "查询成功", page);
    }

    /**
     * 线路承运方导入分页查询
     */
    @SuppressWarnings("resource")
    @Override
    public RestMessage<Object> pageLineCarrierByImportBatchNumberData(ImportPageVO importPageVO) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");

        // 响应对象集合
        List<LineCarrierImportPageDTO> lineCarrierImportPageDTOs = new ArrayList<LineCarrierImportPageDTO>();

        // 分页
        PageUtils.startPage(importPageVO.getPageNum(), importPageVO.getPageSize());

        // 承运方类型
        List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.LINE_CARRIER_TYPE, null, null, null);

        Criteria criteria = Criteria.forClass(TmsLineCarrierLinkModel.class);
        Restriction r1 = Restrictions.eq("importBatchNumber", importPageVO.getImportBatchNumber());
        Restriction r2 = Restrictions.eq("source", DataDictionaryConstant.SOURCE_EXCEL);
        criteria.setRestriction(Restrictions.and(r1, r2));
        criteria.setOrder(Order.newInstance().desc(new String[]{"updatetime"}));
        List<TmsLineCarrierLinkModel> tmsLineCarrierLinkModels = tmsLineCarrierLinkMapper.findByCriteria(criteria);
        for (TmsLineCarrierLinkModel tmsLineCarrierLinkModel : tmsLineCarrierLinkModels) {
            // 响应对象
            LineCarrierImportPageDTO lineCarrierImportPageDTO = new LineCarrierImportPageDTO();
            BeanUtils.copyProperties(tmsLineCarrierLinkModel, lineCarrierImportPageDTO);
            lineCarrierImportPageDTO.setTypeName(PublicMethods.change(restMessage1, String.valueOf(lineCarrierImportPageDTO.getType())));

            lineCarrierImportPageDTOs.add(lineCarrierImportPageDTO);
        }

        Page<LineCarrierImportPageDTO> page = PageUtils.getPage(lineCarrierImportPageDTOs);
        if (tmsLineCarrierLinkModels instanceof com.github.pagehelper.Page) {
            com.github.pagehelper.Page<TmsLineCarrierLinkModel> p0 = (com.github.pagehelper.Page<TmsLineCarrierLinkModel>) tmsLineCarrierLinkModels;
            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 RestMessage.newInstance(true, "查询成功", page);
    }

    /**
     * 线路收货方导入分页查询
     */
    @SuppressWarnings("resource")
    @Override
    public RestMessage<Object> pageLineConsigneeByImportBatchNumberData(ImportPageVO importPageVO) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");

        // 响应对象集合
        List<LineConsigneeImportPageDTO> lineConsigneeImportPageDTOs = new ArrayList<LineConsigneeImportPageDTO>();

        // 分页
        PageUtils.startPage(importPageVO.getPageNum(), importPageVO.getPageSize());

        Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
        Restriction r1 = Restrictions.eq("importBatchNumber", importPageVO.getImportBatchNumber());
        Restriction r2 = Restrictions.eq("source", DataDictionaryConstant.SOURCE_EXCEL);
        Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2, r3));
        criteria.setOrder(Order.newInstance().desc(new String[]{"updatetime"}));
        List<TmsLineConsigneeLinkModel> tmsLineConsigneeLinkModels = tmsLineConsigneeLinkMapper.findByCriteria(criteria);

        for (TmsLineConsigneeLinkModel tmsLineConsigneeLinkModel : tmsLineConsigneeLinkModels) {
            // 响应对象
            LineConsigneeImportPageDTO lineConsigneeImportPageDTO = new LineConsigneeImportPageDTO();
            BeanUtils.copyProperties(tmsLineConsigneeLinkModel, lineConsigneeImportPageDTO);
            lineConsigneeImportPageDTOs.add(lineConsigneeImportPageDTO);
        }

        Page<LineConsigneeImportPageDTO> page = PageUtils.getPage(lineConsigneeImportPageDTOs);
        if (tmsLineConsigneeLinkModels instanceof com.github.pagehelper.Page) {
            com.github.pagehelper.Page<TmsLineConsigneeLinkModel> p0 = (com.github.pagehelper.Page<TmsLineConsigneeLinkModel>) tmsLineConsigneeLinkModels;
            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 RestMessage.newInstance(true, "查询成功", page);
    }

    // 线路导入(新)
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchImportData(MultipartFile file, String importBatchNumber) throws Exception {
        // 导入文件判断
        FileUtils.multipartFileJudge(file);
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        // 导入日志对象
        ImportLogAddVO logAddVO = new ImportLogAddVO();
        logAddVO.setImportObjNo(DataDictionaryConstant.LINE_IMPORT);
        logAddVO.setImportBatchNumber(importBatchNumber);
        // 导入统计
        int count = 0;
        try {
            // 导入执行
            count = this.batchInsertLineProcess(file, importBatchNumber, user);
            logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_YES);
            logAddVO.setSuccessNum(count);
            logAddVO.setFailNum(0);
            importLogService.addImportLogData(logAddVO);
        } catch (Exception e) {
            Class<TranslineImportStdVO> importVOClass = TranslineImportStdVO.class;
            List<TranslineImportStdVO> importVOs = ExcelUtils.read(file, importVOClass);

            logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_NO);
            logAddVO.setSuccessNum(0);
            logAddVO.setFailNum(importVOs.size());
            logAddVO.setFailReason(e.getMessage());
            // 为了避免导入失败时导入日志的保存事务也被回滚,所以采用消息队列异步保存导入失败的日志
            amqpTemplate.convertAndSend(RabbitMQConstant.LINE_IMPORT_LOG, logAddVO);
            e.printStackTrace();
            throw new ParameterException(e.getMessage());
        }
    }

    // 异步保存导入失败日志
    @RabbitListener(queues = RabbitMQConstant.LINE_IMPORT_LOG)
    @Transactional(rollbackFor = Exception.class)
    public void saveFailImportLog(ImportLogAddVO logAddVO) {
        try {
            importLogService.addImportLogData(logAddVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 线路导入过程(新)
     *
     * @param file
     * @param
     * @param
     * @return
     * @throws Exception
     */
    public int batchInsertLineProcess(MultipartFile file, String importBatchNumber, UserEntity user) {
        Date date = new Date();
        Properties properties = new Properties();
        // 待转换的对象
        Class<TranslineImportStdVO> importVOClass = TranslineImportStdVO.class;
        // 标准模板查询
        List<StandardTemplateDetailsListDTO> standardTemplateDetailsListDTOs = sysImportTemplethService.listStandardTemplateDetailsData(DataDictionaryConstant.LINE_IMPORT);
        for (StandardTemplateDetailsListDTO standardTemplateDetailsListDTO : standardTemplateDetailsListDTOs) {
            // 属性字段和注解属性字段值 键值对
            properties.setProperty(standardTemplateDetailsListDTO.getStdColNo(), standardTemplateDetailsListDTO.getCustColName());
        }
        // @ExcelProperty注解属性修改
        ImportUtils.setHeaderValue(properties, importVOClass);
        // EXCEL转对象
        List<TranslineImportStdVO> importVOs = null;
        try {
            importVOs = ExcelUtils.read(file, importVOClass);
        } catch (Exception e) {
            e.printStackTrace();

            throw new ParameterException("EXCEL转对象失败:" + e.getMessage());
        }

        ToolKits.isParamNull(importVOs, "EXCEL文件内容为空,请重新导入");
        log.info("线路导入详情:{}", JsonMapper.toJson(importVOs));

        int i = 1;
        for (TranslineImportStdVO importVO : importVOs) {
            if (ToolKits.isEmpty(importVO.getLineCode())) {
                throw new PrologException("第" + i + "行导入数据,线路编码不能为空");
            }
            if (ToolKits.isEmpty(importVO.getLineName())) {
                throw new PrologException("第" + i + "行导入数据,线路名称不能为空");
            }
            if (ToolKits.isEmpty(importVO.getDepartmentName())) {
                throw new PrologException("第" + i + "行导入数据,部门名称不能为空");
            }
            if (ToolKits.isEmpty(importVO.getLineType())) {
                throw new PrologException("第" + i + "行导入数据,线路类型为必选项");
            }
            if (ToolKits.isEmpty(importVO.getDistinguishType())) {
                throw new PrologException("第" + i + "行导入数据,划分类型为必选项");
            }
            if (ToolKits.isEmpty(importVO.getLineStartType())) {
                throw new PrologException("第" + i + "行导入数据,线路起点类型为必选项");
            }
            if (ToolKits.isEmpty(importVO.getStartLineName())) {
                throw new PrologException("第" + i + "行导入数据,线路起点名称为必选项");
            }
            if (ToolKits.isEmpty(importVO.getLineDirection())) {
                throw new PrologException("第" + i + "行导入数据,方向为必选项");
            }
            i++;
        }
        // 验证导入文件中线路编号是否重复
        Map<String, Long> codeMap = importVOs.stream().collect(Collectors.groupingBy(TranslineImportStdVO::getLineCode, Collectors.counting()));
        for (Map.Entry<String, Long> longEntry : codeMap.entrySet()) {
            if (longEntry.getValue() > 1) {
                throw new ParameterException(String.format("导入文件中，线路编号[%s]重复", longEntry.getKey()));
            }
        }
        // 验证导入文件中线路名称是否重复
        Map<String, Long> nameMap = importVOs.stream().collect(Collectors.groupingBy(TranslineImportStdVO::getLineName, Collectors.counting()));
        for (Map.Entry<String, Long> longEntry : nameMap.entrySet()) {
            if (longEntry.getValue() > 1) {
                throw new ParameterException(String.format("导入文件中，线路名称[%s]重复", longEntry.getKey()));
            }
        }

        i = 0;
        for (TranslineImportStdVO vo : importVOs) {
            List<Organization> data1 = Lists.newArrayList();
            // 所属部门名称判定是否存在
            RestMessage<List<Organization>> departMents = userTmsResource.search(null, vo.getDepartmentName(), null, String.valueOf(user.getEnterpriseId()));
            if (!departMents.isSuccess()) {
                throw new RuntimeException("部门信息查询失败!");
            } else {
                data1 = departMents.getData();
                if (data1.size() == 0) {
                    throw new RuntimeException("部门【" + vo.getDepartmentName() + "】不存在!");
                }
                if (!user.getDepts().contains(data1.get(0).getId())) {
                    throw new RuntimeException("部门【" + vo.getDepartmentName() + "】不存在，请先维护部门!");
                }
            }

            TmsBaseLineModel model = new TmsBaseLineModel();
            BeanUtils.copyProperties(vo, model);

            Map<String, Object> map = Maps.newHashMap();
            map.put("lineCode", vo.getLineCode());
            map.put("enterpriseId", user.getEnterpriseId());
            map.put("status", StatusConstant.STATUS_ENABLE);

            Map<String, Object> map2 = Maps.newHashMap();
            map2.put("lineName", vo.getLineName());
            map2.put("enterpriseId", user.getEnterpriseId());
            map2.put("status", StatusConstant.STATUS_ENABLE);

            // 判断线路编码 线路名称 是否已存在
            PublicMethods.doesItExistByMap(tmsBaseTranslineMapper, map, TmsBaseLineModel.class, "线路编码[" + vo.getLineCode() + "]已存在");
            PublicMethods.doesItExistByMap(tmsBaseTranslineMapper, map2, TmsBaseLineModel.class, "线路名称[" + vo.getLineName() + "]已存在");

            // 判断线路编码 线路名称 是否已停用
            map.put("status", StatusConstant.STATUS_DISABLE);
            map2.put("status", StatusConstant.STATUS_DISABLE);
            PublicMethods.doesItExistByMap(tmsBaseTranslineMapper, map, TmsBaseLineModel.class, "线路编码[" + vo.getLineCode() + "]已停用,请直接启用");
            PublicMethods.doesItExistByMap(tmsBaseTranslineMapper, map2, TmsBaseLineModel.class, "线路名称[" + vo.getLineName() + "]已停用,请直接启用");

            Criteria branchCriteria = Criteria.forClass(TmsBaseBranchModel.class);
            // 校验起点
            if (ObjectUtil.equal("1", vo.getLineStartType())) {// 起点类型为仓库时
                Restriction branchR1 = Restrictions.eq("name", vo.getStartLineName());
                Restriction branchR2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                branchCriteria.setRestriction(Restrictions.and(branchR1, branchR2));
                List<TmsBaseBranchModel> tmsBaseBranchModels = tmsBaseBranchMapper.findByCriteria(branchCriteria);

                if (ToolKits.isEmpty(tmsBaseBranchModels)) {
                    throw new ParameterException("线路名称[" + vo.getLineName() + "]的线路起点[" + vo.getStartLineName() + "]不存在");
                }

                model.setStartLineCode(tmsBaseBranchModels.get(0).getCode());
                model.setStartLineName(tmsBaseBranchModels.get(0).getName());
            } else if (ObjectUtil.equal("2", vo.getLineStartType())) {// 起点类型为行政区划时
                if (ObjectUtil.isEmpty(vo.getStartLineName()) || ObjectUtil.isEmpty(vo.getStartLineCode())) {
                    throw new PrologException("线路起点编码、线路起点名称不能为空");
                } else {
                    if (vo.getStartLineName().indexOf(",") != -1) {
                        String[] zones = vo.getStartLineName().split(",");
                        if (zones.length > 3) {
                            throw new PrologException("省市区格式不合法,省市区最多用两个英文逗号分割");
                        }
                        if (zones.length == 3) {
                            String province = zones[0];
                            List<LmsTmsZoneModel> lmsTmsZoneModels = lmsTmsZoneMapper.getZoneListByZname(province, "2", null);
                            if (ToolKits.isEmpty(lmsTmsZoneModels)) {
                                throw new ParameterException("省名称[" + province + "]错误");
                            }

                            String city = zones[1];
                            List<LmsTmsZoneModel> lmsTmsZoneModels2 = lmsTmsZoneMapper.getZoneListByZname(city, "3", province);
                            if (ToolKits.isEmpty(lmsTmsZoneModels2)) {
                                throw new ParameterException("市名称[" + city + "]错误");
                            }

                            String district = zones[2];
                            List<LmsTmsZoneModel> lmsTmsZoneModels3 = lmsTmsZoneMapper.getZoneListByZname(district, "4", city);
                            if (ToolKits.isEmpty(lmsTmsZoneModels3)) {
                                throw new ParameterException("区名称[" + district + "]错误");
                            }

                            model.setStartLineCode(lmsTmsZoneModels3.get(0).getZoneid());
                        }
                        if (zones.length == 2) {
                            String province = zones[0];
                            List<LmsTmsZoneModel> lmsTmsZoneModels = lmsTmsZoneMapper.getZoneListByZname(province, "2", null);
                            if (ToolKits.isEmpty(lmsTmsZoneModels)) {
                                throw new ParameterException("省名称[" + province + "]错误");
                            }

                            String city = zones[1];
                            List<LmsTmsZoneModel> lmsTmsZoneModels2 = lmsTmsZoneMapper.getZoneListByZname(city, "3", province);
                            if (ToolKits.isEmpty(lmsTmsZoneModels2)) {
                                throw new ParameterException("市名称[" + city + "]错误");
                            }

                            model.setStartLineCode(lmsTmsZoneModels2.get(0).getZoneid());
                        }
                        if (zones.length == 1) {
                            String province = zones[0];
                            List<LmsTmsZoneModel> lmsTmsZoneModels = lmsTmsZoneMapper.getZoneListByZname(province, "2", null);
                            if (ToolKits.isEmpty(lmsTmsZoneModels)) {
                                throw new ParameterException("省名称[" + province + "]错误");
                            }

                            model.setStartLineCode(lmsTmsZoneModels.get(0).getZoneid());
                        }
                    } else {// 省市区没有逗号分割 默认按省名称来匹配
                        List<LmsTmsZoneModel> lmsTmsZoneModels = lmsTmsZoneMapper.getZoneListByZname(vo.getStartLineName(), "2", null);
                        if (ToolKits.isEmpty(lmsTmsZoneModels)) {
                            throw new ParameterException("省名称[" + vo.getStartLineName() + "]错误");
                        }

                        model.setStartLineCode(lmsTmsZoneModels.get(0).getZoneid());
                    }
                }
            }

            // 校验终点
            if (ToolKits.isNotEmpty(vo.getEndLineName()) || ToolKits.isNotEmpty(vo.getEndLineCode())) {
                Criteria branchCriteria1 = Criteria.forClass(TmsBaseBranchModel.class);
                Restriction branchR11 = Restrictions.eq("name", vo.getEndLineName());
                Restriction branchR12 = Restrictions.eq("code", vo.getEndLineCode());
                Restriction branchR21 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                branchCriteria1.setRestriction(Restrictions.and(branchR11, branchR12, branchR21));
                List<TmsBaseBranchModel> tmsBaseBranchModels2 = tmsBaseBranchMapper.findByCriteria(branchCriteria1);
                if (ToolKits.isEmpty(tmsBaseBranchModels2)) {
                    throw new ParameterException("线路名称[" + vo.getLineName() + "]的线路终点[" + vo.getEndLineName() + "]不存在");
                }
                model.setEndLineCode(tmsBaseBranchModels2.get(0).getCode());
                model.setEndLineName(tmsBaseBranchModels2.get(0).getName());
            }

            if (ToolKits.isNotEmpty(vo.getCarrierTypeName())) {
                model.setCarrierType(Integer.parseInt(vo.getCarrierTypeName()));
            }
            if (ToolKits.isNotEmpty(vo.getLineType())) {
                model.setLineType(Integer.parseInt(vo.getLineType()));
            }
            if (ToolKits.isNotEmpty(vo.getDistinguishType())) {
                model.setDistinguishType(Integer.parseInt(vo.getDistinguishType()));
            }
            if (StatusConstant.WHETHER_STRING_YES.equals(vo.getLimitName())) {
                ToolKits.isParamNull(vo.getBasisName(), "开启承运方份额限制，限制依据不为空");
            }

            if (ToolKits.isNotEmpty(vo.getBasisName())) {
                model.setBasis(Integer.parseInt(vo.getBasisName()));
            }

            // 线路ID
            String lineId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_BASE_TRANSLINE_ID, "L");
            ToolKits.isParamNull(lineId, "承运商ID生成失败");
            // 线路对象
            model.setLineId(Long.valueOf(lineId));
            if (ToolKits.isNotEmpty(vo.getLimitName())) {
                model.setLimit(Integer.parseInt(vo.getLimitName()));
            }
            model.setStartLineType(Integer.valueOf(vo.getLineStartType()));
            model.setStatus(StatusConstant.STATUS_ENABLE);
            model.setSource(DataDictionaryConstant.SOURCE_EXCEL);
            model.setImportBatchNumber(importBatchNumber);
            model.setCreatetime(date);
            model.setCreateperson(user.getNickname());
            model.setUpdateperson(user.getNickname());
            model.setUpdatetime(date);
            model.setEnterpriseId(user.getEnterpriseId());
            model.setEnterpriseName(user.getEnterpriseName());

            model.setDepartmentId(data1.get(0).getId());
            model.setDepartmentCode(data1.get(0).getCode());
            model.setDepartmentName(data1.get(0).getName());
            model.setLineDirection(Integer.valueOf(vo.getLineDirection()));
            tmsBaseTranslineMapper.save(model);
            i++;
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchImportCarrierData(MultipartFile file, String importBatchNumber) throws Exception {
        // 人员权限
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");
        // 导入文件判断
        FileUtils.multipartFileJudge(file);
        // 导入日志对象
        ImportLogAddVO logAddVO = new ImportLogAddVO();
        logAddVO.setImportObjNo(DataDictionaryConstant.LINE_CARRIER_IMPORT);
        logAddVO.setImportBatchNumber(importBatchNumber);
        // 导入统计
        int count = 0;
        try {
            // 导入执行
            count = this.batchInsertCarrierProcess(file, importBatchNumber, user);
            logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_YES);
            logAddVO.setSuccessNum(count);
            logAddVO.setFailNum(0);
            importLogService.addImportLogData(logAddVO);
        } catch (Exception e) {
            Class<LineCarrierImportStdVO> importVOClass = LineCarrierImportStdVO.class;
            List<LineCarrierImportStdVO> importVOs = ExcelUtils.read(file, importVOClass);

            logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_NO);
            logAddVO.setSuccessNum(0);
            logAddVO.setFailNum(importVOs.size());
            logAddVO.setFailReason(e.getMessage());
            // 为了避免导入失败时导入日志的保存事务也被回滚,所以采用消息队列异步保存导入失败的日志
            amqpTemplate.convertAndSend(RabbitMQConstant.LINE_CARRIER_IMPORT_LOG, logAddVO);
            e.printStackTrace();
            throw new ParameterException(e.getMessage());
        }
    }

    // 异步保存导入失败日志
    @RabbitListener(queues = RabbitMQConstant.LINE_CARRIER_IMPORT_LOG)
    @Transactional(rollbackFor = Exception.class)
    public void saveFailImportLog2(ImportLogAddVO logAddVO) {
        try {
            importLogService.addImportLogData(logAddVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 线路承运方导入过程(新)
     *
     * @param file
     * @param
     * @param
     * @return
     * @throws Exception
     */
    public int batchInsertCarrierProcess(MultipartFile file, String importBatchNumber, UserEntity user) {
        Date date = new Date();
        Properties properties = new Properties();
        // 待转换的对象
        Class<LineCarrierImportStdVO> importVOClass = LineCarrierImportStdVO.class;
        // 标准模板查询
        List<StandardTemplateDetailsListDTO> standardTemplateDetailsListDTOs = sysImportTemplethService.listStandardTemplateDetailsData(DataDictionaryConstant.LINE_CARRIER_IMPORT);
        for (StandardTemplateDetailsListDTO standardTemplateDetailsListDTO : standardTemplateDetailsListDTOs) {
            // 属性字段和注解属性字段值 键值对
            properties.setProperty(standardTemplateDetailsListDTO.getStdColNo(), standardTemplateDetailsListDTO.getCustColName());
        }
        // @ExcelProperty注解属性修改
        ImportUtils.setHeaderValue(properties, importVOClass);
        // EXCEL转对象
        List<LineCarrierImportStdVO> importVOs = null;
        try {
            importVOs = ExcelUtils.read(file, importVOClass);
        } catch (Exception e) {
            e.printStackTrace();

            throw new ParameterException("EXCEL转对象失败:" + e.getMessage());
        }
        List<TmsLineCarrierLinkModel> tmsLineCarrierModelList = Lists.newArrayList();

        ToolKits.isParamNull(importVOs, "EXCEL文件内容为空,请重新导入");
        log.info("线路导入详情:{}", JsonMapper.toJson(importVOs));
        for (LineCarrierImportStdVO vo : importVOs) {
            ToolKits.isParamNull(vo.getLineCode(), "线路编码不为空");
            ToolKits.isParamNull(vo.getLineName(), "线路名称不为空");
            ToolKits.isParamNull(vo.getCarrierCode(), "承运方编码不为空");
            ToolKits.isParamNull(vo.getCarrierName(), "承运方名称不为空");

            TmsLineCarrierLinkModel tmsLineCarrierLinkModel = new TmsLineCarrierLinkModel();
            BeanUtils.copyProperties(vo, tmsLineCarrierLinkModel);

            // 校验线路
            Criteria lineCriteria = Criteria.forClass(TmsBaseLineModel.class);
            Restriction lineR1 = Restrictions.eq("lineCode", vo.getLineCode());
            Restriction lineR2 = Restrictions.eq("lineName", vo.getLineName());
            Restriction lineR3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            Restriction lineR4 = Restrictions.eq("status", StatusConstant.STATUS_ENABLE);
            lineCriteria.setRestriction(Restrictions.and(lineR1, lineR2, lineR3, lineR4));
            List<TmsBaseLineModel> tmsBaseTranslineModels = tmsBaseTranslineMapper.findByCriteria(lineCriteria);

            if (ToolKits.isEmpty(tmsBaseTranslineModels)) {
                throw new ParameterException("线路编码[" + vo.getLineCode() + "]线路名称[" + vo.getLineName() + "]不存在");
            }

            if (DataDictionaryConstant.LINE_CARRIER_TYPE_CARRIER == tmsBaseTranslineModels.get(0).getCarrierType()) {
                // 校验承运商
                Criteria carrierCriteria = Criteria.forClass(TmsBaseCarriersModel.class);
                Restriction carrierR1 = Restrictions.eq("code", vo.getCarrierCode());
                Restriction carrierR2 = Restrictions.eq("name", vo.getCarrierName());
                Restriction carrierR3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                Restriction carrierR4 = Restrictions.eq("status", StatusConstant.STATUS_ENABLE);
                carrierCriteria.setRestriction(Restrictions.and(carrierR1, carrierR2, carrierR3, carrierR4));
                List<TmsBaseCarriersModel> tmsBaseCarriersModels = tmsBaseCarriersMapper.findByCriteria(carrierCriteria);

                if (ToolKits.isEmpty(tmsBaseCarriersModels)) {
                    throw new ParameterException("承运方编码[" + vo.getCarrierCode() + "]承运方名称[" + vo.getCarrierName() + "]与线路编码[" + vo.getLineCode() + "]承运方类型不匹配");
                }

                tmsLineCarrierLinkModel.setType(DataDictionaryConstant.LINE_CARRIER_TYPE_CARRIER);
                tmsLineCarrierLinkModel.setCarrierId(tmsBaseCarriersModels.get(0).getId());
            }

            if (DataDictionaryConstant.LINE_CARRIER_TYPE_DRIVER == tmsBaseTranslineModels.get(0).getCarrierType()) {
                // 校验司机
                Criteria driverCriteria = Criteria.forClass(TmsBaseDriverModel.class);
                Restriction driverR1 = Restrictions.eq("code", vo.getCarrierCode());
                Restriction driverR2 = Restrictions.eq("name", vo.getCarrierName());
                Restriction driverR3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                Restriction driverR4 = Restrictions.eq("status", StatusConstant.STATUS_ENABLE);
                driverCriteria.setRestriction(Restrictions.and(driverR1, driverR2, driverR3, driverR4));
                List<TmsBaseDriverModel> tmsBaseDriverModels = tmsBaseDriverMapper.findByCriteria(driverCriteria);

                if (ToolKits.isEmpty(tmsBaseDriverModels)) {
                    throw new ParameterException("承运方编码[" + vo.getCarrierCode() + "]承运方名称[" + vo.getCarrierName() + "]与线路编码[" + vo.getLineCode() + "]承运方类型不匹配");
                }

                tmsLineCarrierLinkModel.setType(DataDictionaryConstant.LINE_CARRIER_TYPE_DRIVER);
                tmsLineCarrierLinkModel.setCarrierId(tmsBaseDriverModels.get(0).getId());

                // 校验车牌号
                Criteria vehicleCriteria = Criteria.forClass(TmsBaseVehicleModel.class);
                Restriction vehicleR1 = Restrictions.eq("plateNumber", vo.getVehiclePlateNumber());
                Restriction vehicleR2 = Restrictions.eq("status", StatusConstant.STATUS_ENABLE);
                Restriction vehicleR3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                vehicleCriteria.setRestriction(Restrictions.and(vehicleR1, vehicleR2, vehicleR3));
                List<TmsBaseVehicleModel> tmsBaseVehicleModels = tmsBaseVehicleMapper.findByCriteria(vehicleCriteria);

                if (ToolKits.isEmpty(tmsBaseVehicleModels)) {
                    throw new ParameterException("车牌号[" + vo.getVehiclePlateNumber() + "]不存在");
                }

                tmsLineCarrierLinkModel.setVehicleId(tmsBaseVehicleModels.get(0).getId());
                tmsLineCarrierLinkModel.setVehicleCode(tmsBaseVehicleModels.get(0).getCode());
            }

            if (ToolKits.isNotEmpty(vo.getPhoneNumber()) && !Validator.isMobile(vo.getPhoneNumber())) {
                throw new ParameterException(String.format("%s手机号不符合规范", vo.getPhoneNumber()));
            }

            // 线路承运方资料赋值
            tmsLineCarrierLinkModel.setPrimaryKey(ToolKits.getUUID());
            tmsLineCarrierLinkModel.setLineId(tmsBaseTranslineModels.get(0).getLineId());
            tmsLineCarrierLinkModel.setSource(DataDictionaryConstant.SOURCE_EXCEL);
            tmsLineCarrierLinkModel.setImportBatchNumber(importBatchNumber);
            tmsLineCarrierLinkModel.setCreatetime(date);
            tmsLineCarrierLinkModel.setCreateperson(user.getNickname());
            tmsLineCarrierLinkMapper.save(tmsLineCarrierLinkModel);
            tmsLineCarrierModelList.add(tmsLineCarrierLinkModel);
        }

        // 校验份额
        List<Long> ids = tmsLineCarrierModelList.stream().filter(o -> ToolKits.isNotEmpty(o.getLineId())).distinct().map(TmsLineCarrierLinkModel::getLineId).collect(Collectors.toList());
        for (Long id : ids) {
            BigDecimal sum = BigDecimal.ZERO;

            TmsBaseLineModel tmsBaseTranslineModel = tmsBaseTranslineMapper.findById(id, TmsBaseLineModel.class);

            Criteria criteria = Criteria.forClass(TmsLineCarrierLinkModel.class);
            Restriction r1 = Restrictions.eq("lineId", id);
            criteria.setRestriction(r1);
            List<TmsLineCarrierLinkModel> lineCarrierLinkModels = tmsLineCarrierLinkMapper.findByCriteria(criteria);

            for (TmsLineCarrierLinkModel model : lineCarrierLinkModels) {
                sum = sum.add(ToolKits.isEmpty(model.getShares()) ? BigDecimal.ZERO : model.getShares());
            }

            if (sum.compareTo(new BigDecimal("100")) != 0) {
                throw new ParameterException("线路名称[" + tmsBaseTranslineModel.getLineName() + "]份额应为100%");
            }
        }
        return tmsLineCarrierModelList.size();
    }

    // 线路收货方导入(新)
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchImportConsigneeData(MultipartFile file, String importBatchNumber) throws Exception {
        // 人员权限
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");
        // 导入文件判断
        FileUtils.multipartFileJudge(file);
        // 导入日志对象
        ImportLogAddVO logAddVO = new ImportLogAddVO();
        logAddVO.setImportObjNo(DataDictionaryConstant.LINE_CONSIGNEE_IMPORT);
        logAddVO.setImportBatchNumber(importBatchNumber);

        // 导入统计
        int count = 0;
        try {
            // 导入执行
            count = this.batchInsertConsigneeProcess(file, importBatchNumber, user);
            logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_YES);
            logAddVO.setSuccessNum(count);
            logAddVO.setFailNum(0);
            importLogService.addImportLogData(logAddVO);
        } catch (Exception e) {
            Class<LineConsigneeImportStdVO> importVOClass = LineConsigneeImportStdVO.class;
            List<LineConsigneeImportStdVO> importVOs = ExcelUtils.read(file, importVOClass);

            logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_NO);
            logAddVO.setSuccessNum(0);
            logAddVO.setFailNum(importVOs.size());
            logAddVO.setFailReason(e.getMessage());
            // 为了避免导入失败时导入日志的保存事务也被回滚,所以采用消息队列异步保存导入失败的日志
            amqpTemplate.convertAndSend(RabbitMQConstant.LINE_CONSIGNEE_IMPORT_LOG, logAddVO);
            e.printStackTrace();
            throw new ParameterException(e.getMessage());
        }
    }

    // 线路发货方导入(新)
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchImportShipperData(MultipartFile file, String importBatchNumber) throws Exception {
        // 人员权限
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");
        // 导入文件判断
        FileUtils.multipartFileJudge(file);
        // 导入日志对象
        ImportLogAddVO logAddVO = new ImportLogAddVO();
        logAddVO.setImportObjNo(DataDictionaryConstant.LINE_SHIPPER_IMPORT);
        logAddVO.setImportBatchNumber(importBatchNumber);

        // 导入统计
        int count = 0;
        try {
            // 导入执行
            count = this.batchInsertShipperProcess(file, importBatchNumber, user);
            logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_YES);
            logAddVO.setSuccessNum(count);
            logAddVO.setFailNum(0);
            importLogService.addImportLogData(logAddVO);
        } catch (Exception e) {
            Class<LineShipperImportStdVO> importVOClass = LineShipperImportStdVO.class;
            List<LineShipperImportStdVO> importVOs = ExcelUtils.read(file, importVOClass);

            logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_NO);
            logAddVO.setSuccessNum(0);
            logAddVO.setFailNum(importVOs.size());
            logAddVO.setFailReason(e.getMessage());
            // 为了避免导入失败时导入日志的保存事务也被回滚,所以采用消息队列异步保存导入失败的日志
            amqpTemplate.convertAndSend(RabbitMQConstant.LINE_SHIPPER_IMPORT_LOG, logAddVO);
            e.printStackTrace();
            throw new ParameterException(e.getMessage());
        }
    }

    // 异步保存导入失败日志
    @RabbitListener(queues = RabbitMQConstant.LINE_CONSIGNEE_IMPORT_LOG)
    @Transactional(rollbackFor = Exception.class)
    public void saveFailImportLog3(ImportLogAddVO logAddVO) {
        try {
            importLogService.addImportLogData(logAddVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 线路收货方导入过程(新)
     *
     * @param file
     * @param
     * @param
     * @return
     * @throws Exception
     */
    public int batchInsertConsigneeProcess(MultipartFile file, String importBatchNumber, UserEntity user) {
        // 当前时间
        Date date = new Date();
        // 返回对象集合
        List<TmsLineConsigneeLinkModel> tmsLineConsigneeLinkModels = Lists.newArrayList();
        Properties properties = new Properties();
        // 待转换的对象
        Class<LineConsigneeImportStdVO> importVOClass = LineConsigneeImportStdVO.class;
        // 标准模板查询
        List<StandardTemplateDetailsListDTO> standardTemplateDetailsListDTOs = sysImportTemplethService.listStandardTemplateDetailsData(DataDictionaryConstant.LINE_CONSIGNEE_IMPORT);
        for (StandardTemplateDetailsListDTO standardTemplateDetailsListDTO : standardTemplateDetailsListDTOs) {
            // 属性字段和注解属性字段值 键值对
            properties.setProperty(standardTemplateDetailsListDTO.getStdColNo(), standardTemplateDetailsListDTO.getCustColName());
        }
        // @ExcelProperty注解属性修改
        ImportUtils.setHeaderValue(properties, importVOClass);
        // EXCEL转对象
        List<LineConsigneeImportStdVO> importVOs = null;
        try {
            importVOs = ExcelUtils.read(file, importVOClass);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ParameterException("EXCEL转对象失败:" + e.getMessage());
        }

        ToolKits.isParamNull(importVOs, "EXCEL文件内容为空,请重新导入");
        log.info("线路导入详情:{}", JsonMapper.toJson(importVOs));

        for (LineConsigneeImportStdVO vo : importVOs) {
            ToolKits.isParamNull(vo.getLineCode(), "线路编码不为空");
            ToolKits.isParamNull(vo.getLineName(), "线路名称不为空");
            ToolKits.isParamNull(vo.getConsigneeCode(), "收货方编码不为空");
            ToolKits.isParamNull(vo.getConsigneeName(), "收货方名称不为空");
            ToolKits.isParamNull(vo.getCustomerCode(), "客户编码不为空");
            ToolKits.isParamNull(vo.getCustomerName(), "客户名称不为空");

            TmsLineConsigneeLinkModel tmsLineConsigneeLinkModel = new TmsLineConsigneeLinkModel();
            BeanUtils.copyProperties(vo, tmsLineConsigneeLinkModel);

            // 校验线路
            Criteria lineCriteria = Criteria.forClass(TmsBaseLineModel.class);
            Restriction lineR1 = Restrictions.eq("lineCode", vo.getLineCode());
            Restriction lineR2 = Restrictions.eq("lineName", vo.getLineName());
            Restriction lineR3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            Restriction lineR4 = Restrictions.eq("status", StatusConstant.STATUS_ENABLE);
            lineCriteria.setRestriction(Restrictions.and(lineR1, lineR2, lineR3, lineR4));
            List<TmsBaseLineModel> tmsBaseTranslineModels = tmsBaseTranslineMapper.findByCriteria(lineCriteria);

            if (ToolKits.isEmpty(tmsBaseTranslineModels)) {
                throw new ParameterException("线路编码[" + vo.getLineCode() + "]线路名称[" + vo.getLineName() + "]不存在");
            }

            // 校验客户
            Criteria customerCriteria = Criteria.forClass(TmsBaseCustomerModel.class);
            Restriction customerR1 = Restrictions.eq("code", vo.getCustomerCode());
            Restriction customerR2 = Restrictions.eq("name", vo.getCustomerName());
            Restriction customerR3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            Restriction customerR4 = Restrictions.eq("status", StatusConstant.STATUS_ENABLE);
            customerCriteria.setRestriction(Restrictions.and(customerR1, customerR2, customerR3, customerR4));
            List<TmsBaseCustomerModel> tmsBaseCustomerModels = tmsBaseCustomerMapper.findByCriteria(customerCriteria);

            if (ToolKits.isEmpty(tmsBaseCustomerModels)) {
                throw new ParameterException("客户编码[" + vo.getCustomerCode() + "]客户名称[" + vo.getCustomerName() + "]不存在");
            }

            // 校验收货方
            Criteria consigneeCriteria = Criteria.forClass(TmsCustomerConsignee.class);
            Restriction consigneeR1 = Restrictions.eq("code", vo.getConsigneeCode());
            Restriction consigneeR2 = Restrictions.eq("name", vo.getConsigneeName());
            Restriction consigneeR3 = Restrictions.eq("customerId", tmsBaseCustomerModels.get(0).getId());
            Restriction consigneeR4 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            Restriction consigneeR5 = Restrictions.eq("status", StatusConstant.STATUS_ENABLE);
            consigneeCriteria.setRestriction(Restrictions.and(consigneeR1, consigneeR2, consigneeR3, consigneeR4, consigneeR5));

            List<TmsCustomerConsignee> tmsBaseCustomerReceiverModels = tmsCustomerConsigneeMapper.findByCriteria(consigneeCriteria);

            if (ToolKits.isEmpty(tmsBaseCustomerReceiverModels)) {
                throw new ParameterException("客户名称[" + vo.getCustomerName() + "]的收货方名称[" + vo.getConsigneeName() + "]不存在");
            }

            if (ToolKits.isNotEmpty(vo.getConsigneePhoneNumber()) && !Validator.isMobile(vo.getConsigneePhoneNumber())) {
                throw new ParameterException(String.format("%s手机号不符合规范", vo.getConsigneePhoneNumber()));
            }

            // 线路收货方资料赋值
            tmsLineConsigneeLinkModel.setId(ToolKits.getUUID());
            tmsLineConsigneeLinkModel.setLineId(tmsBaseTranslineModels.get(0).getLineId());
            tmsLineConsigneeLinkModel.setCustomerId(tmsBaseCustomerModels.get(0).getId());
            tmsLineConsigneeLinkModel.setConsigneeId(tmsBaseCustomerReceiverModels.get(0).getId());

            if (ToolKits.isEmpty(vo.getConsigneeContact())) {
                tmsLineConsigneeLinkModel.setConsigneeContact(tmsBaseCustomerReceiverModels.get(0).getContact());
            } else {
                tmsLineConsigneeLinkModel.setConsigneeContact(vo.getConsigneeContact());
            }

            if (ToolKits.isEmpty(vo.getConsigneePhoneNumber())) {
                tmsLineConsigneeLinkModel.setConsigneePhoneNumber(tmsBaseCustomerReceiverModels.get(0).getPhoneNumber());
            } else {
                tmsLineConsigneeLinkModel.setConsigneePhoneNumber(vo.getConsigneePhoneNumber());
            }

            if (ToolKits.isEmpty(vo.getConsigneeAddress())) {
                tmsLineConsigneeLinkModel.setConsigneeAddress(tmsBaseCustomerReceiverModels.get(0).getAddress());
            } else {
                tmsLineConsigneeLinkModel.setConsigneeAddress(vo.getConsigneeAddress());
            }

            tmsLineConsigneeLinkModel.setSource(DataDictionaryConstant.SOURCE_EXCEL);
            tmsLineConsigneeLinkModel.setImportBatchNumber(importBatchNumber);
            tmsLineConsigneeLinkModel.setCreatetime(date);
            tmsLineConsigneeLinkModel.setCreateperson(user.getNickname());
            tmsLineConsigneeLinkModel.setEnterpriseId(user.getEnterpriseId());
            tmsLineConsigneeLinkModel.setEnterpriseName(user.getEnterpriseName());
            tmsLineConsigneeLinkModel.setDeliveryOrder(Integer.valueOf(1));
            tmsLineConsigneeLinkMapper.save(tmsLineConsigneeLinkModel);
            tmsLineConsigneeLinkModels.add(tmsLineConsigneeLinkModel);
        }
        return tmsLineConsigneeLinkModels.size();
    }

    /**
     * 线路发货方导入过程(新)
     *
     * @param file
     * @param
     * @param
     * @return
     * @throws Exception
     */
    public int batchInsertShipperProcess(MultipartFile file, String importBatchNumber, UserEntity user) {
        // 当前时间
        Date date = new Date();
        // 返回对象集合
        List<TmsLineShipperLinkModel> tmsLineShipperLinkModels = Lists.newArrayList();
        Properties properties = new Properties();
        // 待转换的对象
        Class<LineShipperImportStdVO> importVOClass = LineShipperImportStdVO.class;
        // 标准模板查询
        List<StandardTemplateDetailsListDTO> standardTemplateDetailsListDTOs = sysImportTemplethService.listStandardTemplateDetailsData(DataDictionaryConstant.LINE_SHIPPER_IMPORT);
        for (StandardTemplateDetailsListDTO standardTemplateDetailsListDTO : standardTemplateDetailsListDTOs) {
            // 属性字段和注解属性字段值 键值对
            properties.setProperty(standardTemplateDetailsListDTO.getStdColNo(), standardTemplateDetailsListDTO.getCustColName());
        }
        // @ExcelProperty注解属性修改
        ImportUtils.setHeaderValue(properties, importVOClass);
        // EXCEL转对象
        List<LineShipperImportStdVO> importVOs = null;
        try {
            importVOs = ExcelUtils.read(file, importVOClass);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ParameterException("EXCEL转对象失败:" + e.getMessage());
        }

        ToolKits.isParamNull(importVOs, "EXCEL文件内容为空,请重新导入");
        log.info("线路导入详情:{}", JsonMapper.toJson(importVOs));

        for (LineShipperImportStdVO vo : importVOs) {
            ToolKits.isParamNull(vo.getLineCode(), "线路编码不为空");
            ToolKits.isParamNull(vo.getLineName(), "线路名称不为空");
            ToolKits.isParamNull(vo.getBranchCode(), "仓库编码不为空");
            ToolKits.isParamNull(vo.getBranchName(), "仓库名称不为空");

            TmsLineShipperLinkModel tmsLineShipperLinkModel = new TmsLineShipperLinkModel();
            BeanUtils.copyProperties(vo, tmsLineShipperLinkModel);

            // 校验线路
            Criteria lineCriteria = Criteria.forClass(TmsBaseLineModel.class);
            Restriction lineR1 = Restrictions.eq("lineCode", vo.getLineCode());
            Restriction lineR2 = Restrictions.eq("lineName", vo.getLineName());
            Restriction lineR3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            Restriction lineR4 = Restrictions.eq("status", StatusConstant.STATUS_ENABLE);
            lineCriteria.setRestriction(Restrictions.and(lineR1, lineR2, lineR3, lineR4));
            List<TmsBaseLineModel> tmsBaseTranslineModels = tmsBaseTranslineMapper.findByCriteria(lineCriteria);

            if (ToolKits.isEmpty(tmsBaseTranslineModels)) {
                throw new ParameterException("线路编码[" + vo.getLineCode() + "]线路名称[" + vo.getLineName() + "]不存在");
            }

            // 校验仓库
            Criteria branchCriteria = Criteria.forClass(TmsBaseBranchModel.class);
            Restriction branchR1 = Restrictions.eq(TmsBaseBranchModel::getCode, vo.getBranchCode());
            Restriction branchR2 = Restrictions.eq(TmsBaseBranchModel::getName, vo.getBranchName());
            Restriction branchR3 = Restrictions.eq(TmsBaseBranchModel::getEnterpriseId, user.getEnterpriseId());
            Restriction branchR4 = Restrictions.eq(TmsBaseBranchModel::getStatus, StatusConstant.STATUS_ENABLE);
            branchCriteria.setRestriction(Restrictions.and(branchR1, branchR2, branchR3, branchR4));
            List<TmsBaseBranchModel> tmsBaseBranchModels = tmsBaseBranchMapper.findByCriteria(branchCriteria);

            if (ToolKits.isEmpty(tmsBaseBranchModels)) {
                throw new ParameterException("仓库编码[" + vo.getBranchCode() + "]仓库名称[" + vo.getBranchName() + "]不存在");
            }

            // 线路发货方资料赋值
            tmsLineShipperLinkModel.setId(ToolKits.getUUID());
            tmsLineShipperLinkModel.setLineId(tmsBaseTranslineModels.get(0).getLineId());
            tmsLineShipperLinkModel.setBranchId(tmsBaseBranchModels.get(0).getId());
            tmsLineShipperLinkModel.setSource(DataDictionaryConstant.SOURCE_EXCEL);
            tmsLineShipperLinkModel.setImportBatchNumber(importBatchNumber);
            tmsLineShipperLinkModel.setCreatetime(date);
            tmsLineShipperLinkModel.setCreateperson(user.getNickname());
            tmsLineShipperLinkModel.setEnterpriseId(user.getEnterpriseId());
            tmsLineShipperLinkModel.setEnterpriseName(user.getEnterpriseName());
            tmsLineShipperLinkModel.setPickupOrder(Integer.valueOf(1));
            tmsLineShipperLinkMapper.save(tmsLineShipperLinkModel);
            tmsLineShipperLinkModels.add(tmsLineShipperLinkModel);
        }
        return tmsLineShipperLinkModels.size();
    }

    /**
     * 线路-承运方查看
     *
     * @param vo
     * @return
     */
    public List<TmsCarrierDTO> tmsCarrierView(TmsCarrierViewVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        ToolKits.isParamNull(vo, "参数不能为空！");

        Criteria criteria = Criteria.forClass(TmsLineCarrierLinkModel.class);
        Restriction r1 = ToolKits.isEmpty(vo.getLineId()) ? null : Restrictions.eq("lineId", vo.getLineId());
        criteria.setRestriction(Restrictions.and(r1));

        List<TmsLineCarrierLinkModel> tmsLineCarrierLinkModels = tmsLineCarrierLinkMapper.findByCriteria(criteria);

        List<TmsCarrierDTO> dtos = Lists.newArrayList();
        for (TmsLineCarrierLinkModel tmsLineCarrierLinkModel : tmsLineCarrierLinkModels) {
            TmsCarrierDTO dto = new TmsCarrierDTO();
            BeanUtils.copyProperties(tmsLineCarrierLinkModel, dto);
            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public LineByCustomerQueryDTO getLineByCustomerData(LineByCustomerQueryVO lineByCustomerQueryVO) {
        // 根据客户及客户收货方查询对应的线路
        Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
        Restriction r1 = Restrictions.eq(TmsLineConsigneeLinkModel::getCustomerId, lineByCustomerQueryVO.getCustomerId());
        Restriction r2 = Restrictions.eq(TmsLineConsigneeLinkModel::getConsigneeId, lineByCustomerQueryVO.getConsigneeId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        List<TmsLineConsigneeLinkModel> tmsLineConsigneeLinkModels = tmsLineConsigneeLinkMapper.findByCriteria(criteria);

        // 响应对象
        LineByCustomerQueryDTO lineByCustomerQueryDTO = new LineByCustomerQueryDTO();
        if (ToolKits.isEmpty(tmsLineConsigneeLinkModels)) {
            return lineByCustomerQueryDTO;
        } else {
            if (tmsLineConsigneeLinkModels.size() > 1) {
                throw new ParameterException("客户收货方维护了多条线路");
            }

            lineByCustomerQueryDTO.setLineId(tmsLineConsigneeLinkModels.get(0).getLineId());
            lineByCustomerQueryDTO.setLineCode(tmsLineConsigneeLinkModels.get(0).getLineCode());
            lineByCustomerQueryDTO.setLineName(tmsLineConsigneeLinkModels.get(0).getLineName());
        }

        return lineByCustomerQueryDTO;
    }

    /**
     * 线路弹窗
     *
     * @param tmsBaseTranslinePopVO
     * @return
     */
    @Override
    public Page<TmsBaseTranslinePopDTO> getLineByPopData(TmsBaseTranslinePopVO tmsBaseTranslinePopVO) {
        ToolKits.isParamNull(tmsBaseTranslinePopVO, "参数不能为空！");
        ToolKits.isParamNull(tmsBaseTranslinePopVO.getPageNum(), "当前页码不能为空");
        ToolKits.isParamNull(tmsBaseTranslinePopVO.getPageSize(), "每页条数不能为空");

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

        PageUtils.startPage(tmsBaseTranslinePopVO.getPageNum(), tmsBaseTranslinePopVO.getPageSize());
        List<TmsBaseTranslinePopDTO> list = tmsBaseTranslineMapper.getLineByPop(user.getEnterpriseId(), user.getDepts(), "Y");

        Criteria criteria = Criteria.forClass(TmsBaseBranchModel.class);
        List<TmsBaseBranchModel> tmsBaseBranchModels = tmsBaseBranchMapper.findByCriteria(criteria);

        for (TmsBaseTranslinePopDTO tmsBaseTranslinePopDTO : list) {
            tmsBaseTranslinePopDTO.setType(1);
            if (ToolKits.isNotEmpty(tmsBaseTranslinePopDTO.getStartLineType()) && tmsBaseTranslinePopDTO.getStartLineType() == 1) {
                List<TmsBaseBranchModel> tmsBaseBranchModelList = tmsBaseBranchModels.stream().filter(o -> o.getId().equals(tmsBaseTranslinePopDTO.getStartLineId())).collect(Collectors.toList());
                if (ToolKits.isNotEmpty(tmsBaseBranchModelList)) {
                    TmsBaseBranchModel tmsBaseBranchModel = tmsBaseBranchModelList.get(0);
                    tmsBaseTranslinePopDTO.setPhoneNumber(tmsBaseBranchModel.getPhoneNumber());
                    tmsBaseTranslinePopDTO.setAddress(tmsBaseBranchModel.getAddress());
                }
            }
        }
        return PageUtils.getPage(list);
    }

    /**
     * 查看途径点
     *
     * @param lineVO
     * @return
     */
    public List<TmsLineWaySiteDTO> queryWaySite(TmsBaseTranslineByIdsVO lineVO) {
        ToolKits.isParamNull(lineVO, "参数不能为空！");
        ToolKits.isParamNull(lineVO.getLineId(), "线路ID不能为空");
        ToolKits.isParamNull(lineVO.getPageNum(), "当前页码不能为空");
        ToolKits.isParamNull(lineVO.getPageSize(), "每页条数不能为空");

        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        List<TmsLineWaySiteDTO> lineWaySiteDTOS = Lists.newArrayList();

        TmsBaseLineModel tmsBaseTranslineModel = tmsBaseTranslineMapper.findById(lineVO.getLineId(), TmsBaseLineModel.class);
        ToolKits.isParamNull(tmsBaseTranslineModel, "线路ID[" + lineVO.getLineId() + "]有误,查询为空！");

        Criteria criteria = Criteria.forClass(TmsLineConsigneeLinkModel.class);
        Restriction r1 = Restrictions.eq(TmsLineConsigneeLinkModel::getLineId, lineVO.getLineId());
        criteria.setRestriction(Restrictions.and(r1));
        List<TmsLineConsigneeLinkModel> lineConsigneeLinkModels = tmsLineConsigneeLinkMapper.findByCriteria(criteria);

        TmsBaseCustomerReceiverQueryVO tmsBaseCustomerReceiverQueryVO = new TmsBaseCustomerReceiverQueryVO();
        tmsBaseCustomerReceiverQueryVO.setEnterpriseId(user.getEnterpriseId());
        List<TmsBaseCustomerReceiverDTO> tmsBaseCustomerReceiverDTOS = tmsCustomerConsigneeMapper.queryTmsBaseCustomerReceiver(tmsBaseCustomerReceiverQueryVO, null);

        // 翻译字典
        List<String> params = Lists.newArrayList(DataDictionaryConstant.AGING_TIME_LINE);
        Map<String, Object> dicData = ConvertorUtil.listDropDownData(sysRefdatadService, params);

        for (TmsLineConsigneeLinkModel consigneeLinkModel : lineConsigneeLinkModels) {
            TmsLineWaySiteDTO lineWaySiteDTO = new TmsLineWaySiteDTO();
            lineWaySiteDTO.setConsigneeAgingTime(consigneeLinkModel.getConsigneeAgingTime());
            lineWaySiteDTO.setConsigneeAgingTimeLine(consigneeLinkModel.getConsigneeAgingTimeLine());
            lineWaySiteDTO.setConsigneeAgingTimeLineName(ConvertorUtil.getName(dicData, DataDictionaryConstant.AGING_TIME_LINE, consigneeLinkModel.getConsigneeAgingTimeLine()));
            lineWaySiteDTO.setSiteOrder(consigneeLinkModel.getDeliveryOrder());
            lineWaySiteDTO.setSiteTypeName(DataDictionaryConstant.SITE_TYPE_NAME_CONSIGNEE);
            lineWaySiteDTO.setAddress(consigneeLinkModel.getConsigneeAddress());
            lineWaySiteDTO.setLinkId(consigneeLinkModel.getId());
            if (DataDictionaryConstant.DISTINGUISH_TYPE_SHF.equals(tmsBaseTranslineModel.getDistinguishType())) {
                List<TmsBaseCustomerReceiverDTO> collect = tmsBaseCustomerReceiverDTOS.stream().filter(o -> consigneeLinkModel.getConsigneeId().equals(o.getId()) && consigneeLinkModel.getCustomerId().equals(o.getCustomerId())).collect(Collectors.toList());
                if (ToolKits.isNotEmpty(collect)) {
                    TmsBaseCustomerReceiverDTO tmsBaseCustomerReceiverDTO = collect.get(0);
                    lineWaySiteDTO.setLongitude(tmsBaseCustomerReceiverDTO.getLongitude());
                    lineWaySiteDTO.setLatitude(tmsBaseCustomerReceiverDTO.getLatitude());
                }
                lineWaySiteDTO.setSiteCode(consigneeLinkModel.getConsigneeCode());
                lineWaySiteDTO.setSiteName(consigneeLinkModel.getConsigneeName());
                lineWaySiteDTO.setTypeName("客户-收货方");
            } else {
                lineWaySiteDTO.setSiteCode(consigneeLinkModel.getConsigneeCode());
                lineWaySiteDTO.setSiteName(consigneeLinkModel.getConsigneeName());
                lineWaySiteDTO.setTypeName("行政区");
            }

            lineWaySiteDTOS.add(lineWaySiteDTO);
        }

        TmsBaselineVO baselineVO = new TmsBaselineVO();
        baselineVO.setLineId(lineVO.getLineId());
        List<TmsShipperDTO> shipperDTOS = tmsLineShipperLinkMapper.queryLineShipper(baselineVO);
        for (TmsShipperDTO shipperDTO : shipperDTOS) {
            TmsLineWaySiteDTO lineWaySiteDTO = new TmsLineWaySiteDTO();
            lineWaySiteDTO.setSiteOrder(shipperDTO.getPickupOrder());
            lineWaySiteDTO.setSiteTypeName(DataDictionaryConstant.SITE_TYPE_NAME_SHIPPER);
            if (DataDictionaryConstant.START_LINE_TYPE_BRANCH.equals(tmsBaseTranslineModel.getStartLineType())) {
                lineWaySiteDTO.setTypeName("仓库");
                lineWaySiteDTO.setAddress(shipperDTO.getAddress());
            } else {
                lineWaySiteDTO.setTypeName("行政区");
                lineWaySiteDTO.setAddress(shipperDTO.getShipperAddress());
            }
            lineWaySiteDTO.setSiteCode(shipperDTO.getBranchCode());
            lineWaySiteDTO.setSiteName(shipperDTO.getBranchName());

            lineWaySiteDTO.setLinkId(shipperDTO.getId());

            lineWaySiteDTO.setLongitude(shipperDTO.getLongitude());
            lineWaySiteDTO.setLatitude(shipperDTO.getLatitude());
            lineWaySiteDTO.setShipperAgingTime(shipperDTO.getShipperAgingTime());
            lineWaySiteDTO.setShipperAgingTimeLine(shipperDTO.getShipperAgingTimeLine());
            lineWaySiteDTO.setShipperAgingTimeLineName(ConvertorUtil.getName(dicData, DataDictionaryConstant.AGING_TIME_LINE, shipperDTO.getShipperAgingTimeLine()));
            lineWaySiteDTOS.add(lineWaySiteDTO);
        }
        lineWaySiteDTOS = lineWaySiteDTOS.stream().filter(line -> ToolKits.isNotEmpty(line.getSiteOrder())).collect(Collectors.toList());
        lineWaySiteDTOS = lineWaySiteDTOS.stream().sorted(Comparator.comparing(TmsLineWaySiteDTO::getSiteOrder)).collect(Collectors.toList());
        return lineWaySiteDTOS;
    }

    /**
     * 运单匹配线路查询
     *
     * @param vo
     * @return
     */
    public List<ShipbillMatchLineQueryDTO> shipbillMatchLineQuery(ShipbillMatchLineQueryVO vo) {
        ToolKits.isParamNull(vo, "参数不能为空！");
        ToolKits.isParamNull(vo.getStartLineType(), "线路起点类型不能为空");
        ToolKits.isParamNull(vo.getDistinguishType(), "线路划分类型不能为空");

        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        vo.setEnterpriseId(user.getEnterpriseId());
        List<ShipbillMatchLineQueryDTO> tmsBaseTranslineModels = tmsBaseTranslineMapper.shipbillMatchLine(vo);

        return tmsBaseTranslineModels;
    }

    /**
     * 运单匹配线路查询
     *
     * @param vo
     * @return
     */
    public List<ShipbillMatchLineQueryDTO> queryLineForPopup(TmsBaseTranslineByQueryVo vo) {
        ToolKits.isParamNull(vo, "参数不能为空！");

        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        List<ShipbillMatchLineQueryDTO> lines = Lists.newArrayList();

        Criteria criteria = Criteria.forClass(TmsBaseLineModel.class);
        Restriction r1 = Restrictions.eq(TmsBaseLineModel::getEnterpriseId, user.getEnterpriseId());
        Restriction r2 = Restrictions.eq(TmsBaseLineModel::getStatus, StatusConstant.STATUS_ENABLE);
        Restriction r3 = ToolKits.isEmpty(vo.getLineCode()) ? null : Restrictions.like(TmsBaseLineModel::getLineCode, "%" + vo.getLineCode() + "%");
        Restriction r4 = ToolKits.isEmpty(vo.getLineName()) ? null : Restrictions.like(TmsBaseLineModel::getLineName, "%" + vo.getLineName() + "%");
        criteria.setRestriction(Restrictions.and(r1, r2, r3, r4));
        List<TmsBaseLineModel> tmsLineModels = tmsBaseTranslineMapper.findByCriteria(criteria);

        if (ToolKits.isNotEmpty(tmsLineModels)) {
            for (TmsBaseLineModel lineModel : tmsLineModels) {
                ShipbillMatchLineQueryDTO lineQueryDTO = new ShipbillMatchLineQueryDTO();
                lineQueryDTO.setLineId(lineModel.getLineId());
                lineQueryDTO.setLineCode(lineModel.getLineCode());
                lineQueryDTO.setLineName(lineModel.getLineName());
                lines.add(lineQueryDTO);
            }
        }
        return lines;
    }
}