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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.prolog.cs.platform.power.model.Organization;
import com.prolog.framework.common.message.RestMessage;
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.easyexcel.util.ExcelUtils;
import com.prolog.product.core.framework.entity.UserEntity;
import com.prolog.product.core.framework.util.PlgFxUsrUtils;
import com.prolog.product.core.tools.util.ToolKits;
import com.prolog.rdc.tms.constant.BmsConstant;
import com.prolog.rdc.tms.dao.mapper.*;
import com.prolog.rdc.tms.model.dto.*;
import com.prolog.rdc.tms.model.dto.basicConfigure.StandardTemplateDetailsListDTO;
import com.prolog.rdc.tms.model.dto.basicData.*;
import com.prolog.rdc.tms.model.dto.fleetManagement.VehicleTypeCheckDTO;
import com.prolog.rdc.tms.model.entity.*;
import com.prolog.rdc.tms.model.vo.*;
import com.prolog.rdc.tms.model.vo.basicConfigure.ImportLogAddVO;
import com.prolog.rdc.tms.model.vo.basicData.*;
import com.prolog.rdc.tms.model.vo.fleetManagement.VehicleTypeCheckVO;
import com.prolog.rdc.tms.rmi.feign.MaindataFeign;
import com.prolog.rdc.tms.rmi.feign.UserFeign;
import com.prolog.rdc.tms.service.FreightPriceService;
import com.prolog.rdc.tms.util.ConvertorUtil;
import com.prolog.rdc.tms.util.FileUtils;
import com.prolog.rdc.tms.util.ImportUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.PluginException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

@Service
@Slf4j
public class FreightPriceServiceImpl implements FreightPriceService {

    @Autowired
    private FreightPriceMapper priceMapper;
    @Autowired
    private BmsFreightPriceConditionMapper conditionMapper;
    @Autowired
    private FreightPriceLadderMapper ladderMapper;
    @Autowired
    private ConvertorUtil convertorUtil;
    @Autowired
    private MaindataFeign maindataTmsResource;
    @Autowired
    private MergeBillStrategyMapper mergeBillStrategyMapper;
    @Autowired
    private TimeBillStrategyMapper timeBillStrategyMapper;
    @Autowired
    private ProportionBillStrategyMapper proportionBillStrategyMapper;

    @Autowired
    private BmsLogOperationMapper logOperationMapper;

    @Autowired
    private LogisticsContractMapper contractMapper;
    @Autowired
    private ExpenseManagementMapper expenseManagementMapper;
    @Autowired
    private UserFeign userFeign;

    @Autowired
    private FreightPriceService priceService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(FreightPriceVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();

        // 1.判断合同编号是否存在
        Criteria criteria = Criteria.forClass(BmsFreightPriceModel.class);
        Restriction r1 = Restrictions.eq("priceNo", vo.getPriceNo());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        List<BmsFreightPriceModel> priceModels = priceMapper.findByCriteria(criteria);
        if (ObjectUtil.isNotEmpty(priceModels)) {
            throw new PluginException(String.format("价格编码[%s]已存在，请不要重复添加", vo.getPriceNo()));
        }

        r1 = Restrictions.eq(BmsFreightPriceModel::getPriceName, vo.getPriceName());
        criteria.setRestriction(Restrictions.and(r1, r2));
        priceModels = priceMapper.findByCriteria(criteria);
        if (ObjectUtil.isNotEmpty(priceModels)) {
            throw new PluginException(String.format("价格名称[%s]已存在，请不要重复添加", vo.getPriceNo()));
        }
        // 2.判断合同名称是否存在
        Criteria nCriteria = Criteria.forClass(BmsFreightPriceModel.class);
        Restriction r3 = Restrictions.eq("priceName", vo.getPriceName());
        Restriction r4 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        nCriteria.setRestriction(Restrictions.and(r3, r4));
        List<BmsFreightPriceModel> models = priceMapper.findByCriteria(nCriteria);
        if (ObjectUtil.isNotEmpty(models)) {
            throw new PluginException(String.format("价格名称[%s]已存在，请不要重复添加", vo.getPriceName()));
        }

        // 1.运费价格
        BmsFreightPriceModel priceModel = new BmsFreightPriceModel();
        BeanUtils.copyProperties(vo, priceModel);
        priceModel.setCreateperson(user.getNickname());
        priceModel.setCreatetime(DateUtil.date());
        priceModel.setUpdatetime(DateUtil.date());
        priceModel.setUpdateperson(user.getNickname());
        priceModel.setEnterpriseId(user.getEnterpriseId());
        priceModel.setEnterpriseName(user.getEnterpriseName());
        priceModel.setIsSurcharge(vo.getIsSurcharge());
        priceModel.setExpenseId(vo.getExpenseId());
        priceModel.setExpenseName(vo.getExpenseName());
        priceModel.setStatus(2);
        priceModel.setSource(1);
        priceMapper.save(priceModel);
        // 2.匹配条件
        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{
                BmsConstant.BMS_APPROVAL_CONDITION_TYPE
        });
        List<BmsFreightPriceConditionModel> conditionList = vo.getConditionList();
        if (ObjectUtil.isNotEmpty(conditionList)) {
            List<BmsFreightPriceConditionModel> conditionModels = Lists.newArrayList();
            for (BmsFreightPriceConditionModel freightPriceConditionModel : conditionList) {
                freightPriceConditionModel.setPriceNo(vo.getPriceNo());
                freightPriceConditionModel.setCreateperson(user.getNickname());
                freightPriceConditionModel.setCreatetime(DateUtil.date());
                freightPriceConditionModel.setUpdatetime(DateUtil.date());
                freightPriceConditionModel.setUpdateperson(user.getNickname());
                freightPriceConditionModel.setEnterpriseId(user.getEnterpriseId());
                freightPriceConditionModel.setEnterpriseName(user.getEnterpriseName());
                freightPriceConditionModel.setConditionTypeName(ConvertorUtil.getName(dicData, BmsConstant.BMS_APPROVAL_CONDITION_TYPE, String.valueOf(freightPriceConditionModel.getConditionType())));
                conditionModels.add(freightPriceConditionModel);
            }
            conditionMapper.saveBatch(conditionModels);
        }
        // 3.计费阶梯
        List<BmsFreightPriceLadderModel> ladderList = vo.getLadderList();
        if (ObjectUtil.isNotEmpty(ladderList)) {
            List<String> ladderTypeList = ladderList.stream().map(BmsFreightPriceLadderModel::getLadderType).collect(Collectors.toList());
            List<String> ladders = ladderTypeList.stream().filter(Objects::nonNull).collect(Collectors.toList());
            Map<String, List<String>> ladderMap = ladders.stream().collect(Collectors.groupingBy(o -> o));
            if (ladders.size() != ladderMap.size() && ObjectUtil.isNotEmpty(ladders)) {
                throw new PluginException("阶梯类别重复，请重新添加");
            }
            List<BmsFreightPriceLadderModel> ladderModels = Lists.newArrayList();
            for (BmsFreightPriceLadderModel bmsFreightPriceLadderModel : ladderList) {
                bmsFreightPriceLadderModel.setId(null);
                bmsFreightPriceLadderModel.setPriceNo(vo.getPriceNo());
                bmsFreightPriceLadderModel.setCreateperson(user.getNickname());
                bmsFreightPriceLadderModel.setCreatetime(DateUtil.date());
                bmsFreightPriceLadderModel.setUpdatetime(DateUtil.date());
                bmsFreightPriceLadderModel.setUpdateperson(user.getNickname());
                bmsFreightPriceLadderModel.setEnterpriseId(user.getEnterpriseId());
                bmsFreightPriceLadderModel.setEnterpriseName(user.getEnterpriseName());
                if (ObjectUtil.isEmpty(bmsFreightPriceLadderModel.getFirstHour())) {
                    bmsFreightPriceLadderModel.setFirstHour(BigDecimal.ZERO);
                }
                ladderModels.add(bmsFreightPriceLadderModel);
            }
            ladderMapper.saveBatch(ladderModels);
        }

        BmsLogOperationModel feeVo = new BmsLogOperationModel();
        feeVo.setCreatetime(DateUtil.date());
        feeVo.setCreateperson(user.getNickname());
        feeVo.setEnterpriseId(user.getEnterpriseId());
        feeVo.setEnterpriseName(user.getEnterpriseName());
        feeVo.setOrderNo(vo.getContractNo());
        feeVo.setLogMemo("运费价格新增");
        feeVo.setLogType(2);
        logOperationMapper.save(feeVo);
    }

    @Override
    public Page<FreightPriceDTO> findList(FreightPriceQuery vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        Criteria criteria = Criteria.forClass(BmsFreightPriceModel.class);
        Restriction r1 = Restrictions.eq("contractNo", vo.getContractNo());
        Restriction r2 = Restrictions.eq("isSurcharge", vo.getIsSurcharge());
        Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2, r3));
        criteria.setOrder(Order.newInstance().desc("updatetime").asc("createtime"));
        PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
        List<BmsFreightPriceModel> models = priceMapper.findByCriteria(criteria);

        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{
                BmsConstant.COST_TYPE,
                BmsConstant.SETTLEMENT_MODEL,
                BmsConstant.LADDER_TYPE,
                BmsConstant.CONTRACT_STATUS,
                BmsConstant.SOURCE,
                BmsConstant.SETTLEMENT_TYPE,
                BmsConstant.SETTLEMENT_ORDER_TYPE

        });

        List<FreightPriceDTO> dtos = Lists.newArrayList();
        for (BmsFreightPriceModel model : models) {
            FreightPriceDTO dto = new FreightPriceDTO();
            BeanUtils.copyProperties(model, dto);
            dto.setSettlementModelName(ConvertorUtil.getName(dicData, BmsConstant.SETTLEMENT_MODEL, String.valueOf(dto.getSettlementModel())));
            dto.setSettlementTypeName(ConvertorUtil.getName(dicData, BmsConstant.SETTLEMENT_TYPE, String.valueOf(dto.getSettlementType())));
            dto.setStatusName(ConvertorUtil.getName(dicData, BmsConstant.CONTRACT_STATUS, String.valueOf(dto.getStatus())));

            dto.setSourceName(ConvertorUtil.getName(dicData, BmsConstant.SOURCE, String.valueOf(model.getSource())));
            dto.setSettlementOrderTypeName(ConvertorUtil.getName(dicData, BmsConstant.SETTLEMENT_ORDER_TYPE, String.valueOf(model.getSettlementOrderType())));
            // 查询匹配条件
            Criteria aClass = Criteria.forClass(BmsFreightPriceConditionModel.class);
            Restriction r5 = Restrictions.eq("priceNo", model.getPriceNo());
            Restriction r6 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            aClass.setRestriction(Restrictions.and(r5, r6));
            List<BmsFreightPriceConditionModel> conditionModels = conditionMapper.findByCriteria(aClass);
            if (ObjectUtil.isNotEmpty(conditionModels)) {
                List<SysRefdatadModel> dicConditionData = convertorUtil.getDictionary(new String[]{
                        BmsConstant.DELIVERY_METHOD_TYPE,
                        BmsConstant.SHIPPER_TYPE,
                        BmsConstant.CONSIGNEE_TYPE,
                        BmsConstant.ORDER_TYPE,
                        BmsConstant.ORDER_BUSINESS_TYPE,
                        BmsConstant.TRANSPORT_TYPE,
                        BmsConstant.TEMPERATURE_REQUIREMENT});

                List<String> conditionListName = Lists.newArrayList();
                for (BmsFreightPriceConditionModel conditionModel : conditionModels) {
                    String conditionValueName = null;
                    switch (conditionModel.getConditionType().intValue()) {
                        case 1:
                            conditionValueName = ConvertorUtil.getName(dicConditionData, BmsConstant.DELIVERY_METHOD_TYPE, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName);
                            break;
                        case 2:
                            conditionValueName = ConvertorUtil.getName(dicConditionData, BmsConstant.SHIPPER_TYPE, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName + " " + conditionModel.getUnitName());
                            break;
                        case 3:
                            conditionValueName = ConvertorUtil.getName(dicConditionData, BmsConstant.CONSIGNEE_TYPE, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName + " " + conditionModel.getUnitName());
                            break;
                        case 4:
                            conditionValueName = ConvertorUtil.getName(dicConditionData, BmsConstant.ORDER_TYPE, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName);
                            break;
                        case 5:
                            conditionValueName = ConvertorUtil.getName(dicConditionData, BmsConstant.ORDER_BUSINESS_TYPE, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName);
                            break;
                        case 6:
                            conditionValueName = ConvertorUtil.getName(dicConditionData, BmsConstant.TRANSPORT_TYPE, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName);
                            break;
                        case 7:
                            conditionValueName = ConvertorUtil.getName(dicConditionData, BmsConstant.TEMPERATURE_REQUIREMENT, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName);
                            break;
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                        case 12:
                        case 17:
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionModel.getUnitName());
                            break;
                        case 13:
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionModel.getConditionValue() + " " + conditionModel.getUnitName());
                            break;
                        case 14:
                        case 15:
                        case 16:
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionModel.getConditionValue());
                            break;
                        default:
                            break;
                    }
                }
                String join = Joiner.on(";").join(conditionListName);
                dto.setConditionListName(join);
            }
            // 查询阶梯条件
            Criteria lClass = Criteria.forClass(BmsFreightPriceLadderModel.class);
            Restriction r7 = Restrictions.eq("priceNo", model.getPriceNo());
            Restriction r8 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            lClass.setRestriction(Restrictions.and(r7, r8));
            List<BmsFreightPriceLadderModel> ladderModels = ladderMapper.findByCriteria(lClass);
            if (ObjectUtil.isNotEmpty(ladderModels)) {
                List<BmsFreightPriceLadderModel> modelList = ladderModels.stream().filter(Objects::nonNull).collect(Collectors.toList());
                if (ObjectUtil.isNotEmpty(modelList)) {
                    List<String> list = modelList.stream().map(BmsFreightPriceLadderModel::getLadderType).filter(Objects::nonNull).collect(Collectors.toList());
                    dto.setLadderTypeName(Joiner.on(",").join(list));
                }
            }
            dtos.add(dto);
        }
        Page<FreightPriceDTO> page = PageUtils.getPage(dtos);
        if (models instanceof com.github.pagehelper.Page) {
            com.github.pagehelper.Page<BmsFreightPriceModel> p0 = (com.github.pagehelper.Page<BmsFreightPriceModel>) models;
            page.setPageCount(p0.getPages());
            page.setPageNum(p0.getPageNum());
            page.setPageSize(p0.getPageSize());
            page.setTotalCount(p0.getTotal());
            page.setStartRow(p0.getStartRow());
            page.setEndRow(p0.getEndRow());
        }
        return page;
    }

    @Override
    public FreightPriceDTO detail(Long id) {
        if (ObjectUtil.isEmpty(id)) {
            throw new PluginException("查询条件不能为空");
        }
        BmsFreightPriceModel freightPriceModel = priceMapper.findById(id, BmsFreightPriceModel.class);
        if (ObjectUtil.isEmpty(freightPriceModel)) {
            throw new PluginException("查询详情信息为空");
        }
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{
                BmsConstant.COST_TYPE,
                BmsConstant.SETTLEMENT_MODEL,
                BmsConstant.LADDER_TYPE,
                BmsConstant.SECTION_SYMBOL,
                BmsConstant.LESS_THAN,
                BmsConstant.SETTLEMENT_TYPE,
                BmsConstant.SETTLEMENT_ORDER_TYPE,
                BmsConstant.CALCULATE_RULE
        });
        FreightPriceDTO dto = new FreightPriceDTO();
        BeanUtils.copyProperties(freightPriceModel, dto);
        dto.setSettlementModelName(ConvertorUtil.getName(dicData, BmsConstant.SETTLEMENT_MODEL, String.valueOf(dto.getSettlementModel())));
        dto.setLadderTypeName(ConvertorUtil.getName(dicData, BmsConstant.LADDER_TYPE, String.valueOf(dto.getLadderType())));
        dto.setSettlementTypeName(ConvertorUtil.getName(dicData, BmsConstant.SETTLEMENT_TYPE, String.valueOf(dto.getSettlementType())));
        dto.setSettlementOrderTypeName(ConvertorUtil.getName(dicData, BmsConstant.SETTLEMENT_ORDER_TYPE, String.valueOf(dto.getSettlementOrderType())));
        if (freightPriceModel.getMergeStrategyId() != null) {
            BmsMergeBillStrategyModel mergeStrategyModel = mergeBillStrategyMapper.findById(freightPriceModel.getMergeStrategyId(), BmsMergeBillStrategyModel.class);
            dto.setMergeStrategyName(mergeStrategyModel.getStrategyName());
        }
        if (freightPriceModel.getTimeStrategyId() != null) {
            BmsTimeBillStrategyModel timeStrategyModel = timeBillStrategyMapper.findById(freightPriceModel.getTimeStrategyId(), BmsTimeBillStrategyModel.class);
            dto.setTimeStrategyName(timeStrategyModel.getStrategyName());
        }
        if (freightPriceModel.getProportionStrategyId() != null) {
            BmsProportionBillStrategyModel proportionStrategyModel = proportionBillStrategyMapper.findById(freightPriceModel.getProportionStrategyId(), BmsProportionBillStrategyModel.class);
            dto.setProportionStrategyName(proportionStrategyModel.getStrategyName());
        }
        // 查询匹配条件
        Criteria criteria = Criteria.forClass(BmsFreightPriceConditionModel.class);
        Restriction r1 = Restrictions.eq("priceNo", freightPriceModel.getPriceNo());
        Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r3));
        List<BmsFreightPriceConditionModel> conditionModels = conditionMapper.findByCriteria(criteria);
        dto.setConditionList(conditionModels);

        // 阶梯
        Criteria lCriteria = Criteria.forClass(BmsFreightPriceLadderModel.class);
        Restriction r2 = Restrictions.eq("priceNo", freightPriceModel.getPriceNo());
        Restriction r4 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        lCriteria.setRestriction(Restrictions.and(r2, r4));
        List<BmsFreightPriceLadderModel> ladderModels = ladderMapper.findByCriteria(lCriteria);
        List<BmsFreightPriceLadderDTO> ladderList = Lists.newArrayList();
        for (BmsFreightPriceLadderModel ladderModel : ladderModels) {
            BmsFreightPriceLadderDTO ladderDTO = new BmsFreightPriceLadderDTO();
            BeanUtils.copyProperties(ladderModel, ladderDTO);
            ladderDTO.setSectionDownSymbolName(ConvertorUtil.getName(dicData, BmsConstant.SECTION_SYMBOL, String.valueOf(ladderModel.getSectionDownSymbol())));
            ladderDTO.setSectionUpSymbolName(ConvertorUtil.getName(dicData, BmsConstant.LESS_THAN, String.valueOf(ladderModel.getSectionUpSymbol())));
            ladderDTO.setCalculateRuleName(ObjectUtil.isEmpty(ladderModel.getCalculateRule()) ? StrUtil.EMPTY : ConvertorUtil.getName(dicData, BmsConstant.CALCULATE_RULE, String.valueOf(ladderModel.getCalculateRule())));
            ladderList.add(ladderDTO);
        }
        dto.setLadderList(ladderList);
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(FreightPriceVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        // 1.判断合同编号是否存在
        Criteria criteria = Criteria.forClass(BmsFreightPriceModel.class);
        Restriction r1 = Restrictions.eq("priceNo", vo.getPriceNo());
        Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        Restriction r3 = Restrictions.ne("id", vo.getId());
        criteria.setRestriction(Restrictions.and(r1, r2, r3));
        List<BmsFreightPriceModel> priceModels = priceMapper.findByCriteria(criteria);
        if (ObjectUtil.isNotEmpty(priceModels)) {
            throw new PluginException(String.format("价格编码[%s]已存在，请不要重复添加", vo.getPriceNo()));
        }
        // 2.判断合同名称是否存在
        Criteria nCriteria = Criteria.forClass(BmsFreightPriceModel.class);
        Restriction r4 = Restrictions.eq("priceName", vo.getPriceName());
        Restriction r5 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        Restriction r6 = Restrictions.ne("id", vo.getId());
        nCriteria.setRestriction(Restrictions.and(r4, r5, r6));
        List<BmsFreightPriceModel> models = priceMapper.findByCriteria(nCriteria);
        if (ObjectUtil.isNotEmpty(models)) {
            throw new PluginException(String.format("价格名称[%s]已存在，请不要重复添加", vo.getPriceName()));
        }

        BmsFreightPriceModel priceModel = priceMapper.findById(vo.getId(), BmsFreightPriceModel.class);
        BeanUtils.copyProperties(vo, priceModel);
        priceModel.setUpdateperson(user.getNickname());
        priceModel.setUpdatetime(DateUtil.date());
        priceModel.setEnterpriseId(user.getEnterpriseId());
        priceModel.setEnterpriseName(user.getEnterpriseName());
        priceMapper.update(priceModel);

        BmsLogOperationModel feeVo = new BmsLogOperationModel();
        feeVo.setCreatetime(DateUtil.date());
        feeVo.setCreateperson(user.getNickname());
        feeVo.setEnterpriseId(user.getEnterpriseId());
        feeVo.setEnterpriseName(user.getEnterpriseName());
        feeVo.setOrderNo(vo.getContractNo());
        feeVo.setLogMemo("运费价格更新");
        feeVo.setLogType(2);
        logOperationMapper.save(feeVo);

        // 删除条件
        Criteria cCriteria = Criteria.forClass(BmsFreightPriceConditionModel.class);
        Restriction r7 = Restrictions.eq("priceNo", priceModel.getPriceNo());
        Restriction r8 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        cCriteria.setRestriction(Restrictions.and(r7, r8));
        conditionMapper.deleteByCriteria(cCriteria);

        // 删除阶梯
        Criteria lCriteria = Criteria.forClass(BmsFreightPriceLadderModel.class);
        Restriction r9 = Restrictions.eq("priceNo", priceModel.getPriceNo());
        Restriction r10 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        lCriteria.setRestriction(Restrictions.and(r9, r10));
        ladderMapper.deleteByCriteria(lCriteria);

        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{
                BmsConstant.BMS_APPROVAL_CONDITION_TYPE
        });
        // 新增
        // 2.匹配条件
        List<BmsFreightPriceConditionModel> conditionList = vo.getConditionList();
        if (ObjectUtil.isNotEmpty(conditionList)) {
            List<BmsFreightPriceConditionModel> conditionModels = Lists.newArrayList();
            for (BmsFreightPriceConditionModel freightPriceConditionModel : conditionList) {
                freightPriceConditionModel.setId(null);
                freightPriceConditionModel.setPriceNo(priceModel.getPriceNo());
                freightPriceConditionModel.setCreateperson(user.getNickname());
                freightPriceConditionModel.setCreatetime(DateUtil.date());
                freightPriceConditionModel.setUpdatetime(DateUtil.date());
                freightPriceConditionModel.setUpdateperson(user.getNickname());
                freightPriceConditionModel.setEnterpriseId(user.getEnterpriseId());
                freightPriceConditionModel.setEnterpriseName(user.getEnterpriseName());
                freightPriceConditionModel.setConditionTypeName(ConvertorUtil.getName(dicData, BmsConstant.BMS_APPROVAL_CONDITION_TYPE, String.valueOf(freightPriceConditionModel.getConditionType())));
                conditionModels.add(freightPriceConditionModel);
            }
            conditionMapper.saveBatch(conditionModels);
        }
        // 3.计费阶梯
        List<BmsFreightPriceLadderModel> ladderList = vo.getLadderList();
        if (ObjectUtil.isNotEmpty(ladderList)) {
            List<String> ladderTypeList = ladderList.stream().map(BmsFreightPriceLadderModel::getLadderType).collect(Collectors.toList());
            List<String> ladders = ladderTypeList.stream().filter(Objects::nonNull).collect(Collectors.toList());
            Map<String, List<String>> ladderMap = ladders.stream().collect(Collectors.groupingBy(o -> o));
            if (ladders.size() != ladderMap.size() && ObjectUtil.isNotEmpty(ladders)) {
                throw new PluginException("阶梯类别重复，请重新添加");
            }
            List<BmsFreightPriceLadderModel> ladderModels = Lists.newArrayList();
            for (BmsFreightPriceLadderModel bmsFreightPriceLadderModel : ladderList) {
                bmsFreightPriceLadderModel.setId(null);
                bmsFreightPriceLadderModel.setPriceNo(priceModel.getPriceNo());
                bmsFreightPriceLadderModel.setCreateperson(user.getNickname());
                bmsFreightPriceLadderModel.setCreatetime(DateUtil.date());
                bmsFreightPriceLadderModel.setUpdatetime(DateUtil.date());
                bmsFreightPriceLadderModel.setUpdateperson(user.getNickname());
                bmsFreightPriceLadderModel.setEnterpriseId(user.getEnterpriseId());
                bmsFreightPriceLadderModel.setEnterpriseName(user.getEnterpriseName());
                if (ObjectUtil.isEmpty(bmsFreightPriceLadderModel.getFirstHour())) {
                    bmsFreightPriceLadderModel.setFirstHour(BigDecimal.ZERO);
                }
                ladderModels.add(bmsFreightPriceLadderModel);
            }
            ladderMapper.saveBatch(ladderModels);
        }
    }

    @Override
    public void updateStatus(List<StatusUpdate> list) {
        // 1 校验数据
        if (ObjectUtil.isEmpty(list)) {
            throw new RuntimeException("请求参数不能为空");
        }
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        for (StatusUpdate statusUpdate : list) {
            BmsFreightPriceModel model = priceMapper.findById(statusUpdate.getId(), BmsFreightPriceModel.class);
            if (model.getStatus() == 0 && statusUpdate.getStatus() == 0) {
                throw new PluginException(String.format("存在已经停用状态合同[%s]", model.getPriceName()));
            }
            if (model.getStatus() == 1 && statusUpdate.getStatus() == 1) {
                throw new PluginException(String.format("存在审核中或已启用状态合同[%s]", model.getPriceName()));
            }
            if (model.getStatus() == 2 && statusUpdate.getStatus() == 0) {
                throw new PluginException("仅支持价格表启用状态下停用！");
            }
            model.setStatus(statusUpdate.getStatus());
            model.setUpdateperson(user.getNickname());
            model.setUpdatetime(DateUtil.date());
            priceMapper.update(model);

            BmsLogOperationModel feeVo = new BmsLogOperationModel();
            feeVo.setCreatetime(DateUtil.date());
            feeVo.setCreateperson(user.getNickname());
            feeVo.setEnterpriseId(user.getEnterpriseId());
            feeVo.setEnterpriseName(user.getEnterpriseName());
            feeVo.setOrderNo(model.getContractNo());
            if (model.getStatus() == 0) {
                feeVo.setLogMemo("运费价格停用");
            } else {
                feeVo.setLogMemo("运费价格启用");
            }
            feeVo.setLogType(2);
            logOperationMapper.save(feeVo);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<StatusUpdate> vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        // 1 校验数据
        if (ObjectUtil.isEmpty(vo)) {
            throw new RuntimeException("请求参数不能为空");
        }
        // 判断是否启用
        for (StatusUpdate statusUpdate : vo) {
            BmsFreightPriceModel model = priceMapper.findById(statusUpdate.getId(), BmsFreightPriceModel.class);
            if (model.getStatus() == 1) {
                throw new PluginException(String.format("运费价格[%s],是启用状态不能删除", model.getPriceName()));
            }
            priceMapper.deleteById(statusUpdate.getId(), BmsFreightPriceModel.class);

            // 删除匹配条件
            Criteria criteria = Criteria.forClass(BmsFreightPriceConditionModel.class);
            Restriction r1 = Restrictions.eq("priceNo", model.getPriceNo());
            Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            criteria.setRestriction(Restrictions.and(r1, r2));
            conditionMapper.deleteByCriteria(criteria);

            // 删除阶梯
            Criteria criteria2 = Criteria.forClass(BmsFreightPriceLadderModel.class);
            criteria2.setRestriction(Restrictions.and(r1, r2));
            ladderMapper.deleteByCriteria(criteria2);

            BmsLogOperationModel feeVo = new BmsLogOperationModel();
            feeVo.setCreatetime(DateUtil.date());
            feeVo.setCreateperson(user.getNickname());
            feeVo.setEnterpriseId(user.getEnterpriseId());
            feeVo.setEnterpriseName(user.getEnterpriseName());
            feeVo.setOrderNo(model.getContractNo());
            feeVo.setLogMemo("运费价格删除");
            feeVo.setLogType(2);
            logOperationMapper.save(feeVo);
        }
    }

    @Override
    public Page<BaseFeeDTO> expensePop(ExpensePopDTO dto) {
        // 1.查询当前用户现在的基础费用
        RestMessage<Page<BaseFeeDTO>> message = this.findBaseFeePage(dto);
        return message.getData();
    }

    private RestMessage<Page<BaseFeeDTO>> findBaseFeePage(ExpensePopDTO dto) {
        return maindataTmsResource.findBaseFeePage(dto);
    }

    @Override
    public void importFreightPriceData(MultipartFile file) {
        // 导入文件判断
        FileUtils.multipartFileJudge(file);
        String importBatchNumber = ToolKits.getUUID();
        // 导入日志对象
        ImportLogAddVO logAddVO = new ImportLogAddVO();
        logAddVO.setImportObjNo(BmsConstant.BMS_FREIGHT_PRICE_IMPORT);
        logAddVO.setImportBatchNumber(importBatchNumber);
        try {
            // 导入执行
            int count = priceService.importProcess(file);
            logAddVO.setStatus(BmsConstant.IMPORT_STATUS_YES);
            logAddVO.setSuccessNum(count);
            logAddVO.setFailNum(0);
            maindataTmsResource.addImportLogExecute(logAddVO);
        } catch (Exception e) {
            e.printStackTrace();
            logAddVO.setStatus(BmsConstant.IMPORT_STATUS_NO);
            logAddVO.setSuccessNum(0);
            logAddVO.setFailNum(0);
            logAddVO.setFailReason(e.getMessage());
            maindataTmsResource.addImportLogExecute(logAddVO);
            throw new PrologException(e.getMessage());
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int importProcess(MultipartFile file) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        Properties properties = new Properties();
        Class<FreightPriceImportVO> importVOClass = FreightPriceImportVO.class;
        RestMessage<List<StandardTemplateDetailsListDTO>> restMessage = maindataTmsResource.listStandardTemplateDetailsExecute(BmsConstant.BMS_FREIGHT_PRICE_IMPORT);
        if (!restMessage.isSuccess()) {
            throw new PrologException("标准模板详情查询失败:" + restMessage.getMessage());
        }
        List<StandardTemplateDetailsListDTO> standardTemplateDetailsListDTOs = restMessage.getData();
        if (ObjectUtil.isEmpty(standardTemplateDetailsListDTOs)) {
            throw new PrologException("运单标准模板未配置");
        }
        for (StandardTemplateDetailsListDTO standardTemplateDetailsListDTO : standardTemplateDetailsListDTOs) {
            properties.setProperty(standardTemplateDetailsListDTO.getStdColNo(), standardTemplateDetailsListDTO.getCustColName());
        }
        ImportUtils.setHeaderValue(properties, importVOClass);
        List<FreightPriceImportVO> freightPriceImportVOS;
        try {
            freightPriceImportVOS = ExcelUtils.read(file, importVOClass);
        } catch (Exception e) {
            e.printStackTrace();
            throw new PrologException("EXCEL转对象失败:" + e.getMessage());
        }
        if (ObjectUtil.isEmpty(freightPriceImportVOS)) {
            throw new PrologException("EXCEL文件内容为空,请重新导入");
        }
        log.info("导入的数据:" + JSON.toJSONString(freightPriceImportVOS));
        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{
                BmsConstant.BMS_APPROVAL_CONDITION_TYPE,
                BmsConstant.DELIVERY_METHOD_TYPE,
                BmsConstant.SHIPPER_TYPE,
                BmsConstant.CONSIGNEE_TYPE,
                BmsConstant.ORDER_TYPE,
                BmsConstant.ORDER_BUSINESS_TYPE,
                BmsConstant.TRANSPORT_TYPE,
                BmsConstant.TEMPERATURE_REQUIREMENT,
                BmsConstant.LESS_THAN,
                BmsConstant.SECTION_SYMBOL,
        });
        preCheck(freightPriceImportVOS, dicData);
        Map<Integer, List<FreightPriceImportVO>> freightPriceMap = freightPriceImportVOS.stream().collect(Collectors.groupingBy(FreightPriceImportVO::getNumber));
        log.info("按序号分组后的数据:" + JSON.toJSONString(freightPriceMap));
        Map<String, String> zoneCodeMap = Maps.newHashMap();
        for (Integer obj : freightPriceMap.keySet()) {
            List<FreightPriceImportVO> freightPriceList = freightPriceMap.get(obj);
            FreightPriceImportVO freightPriceImportVO = freightPriceList.get(0);
            log.info("导入的价格数据开始处理:" + JSON.toJSONString(freightPriceList));
            // 1.运费价格
            BmsFreightPriceModel priceModel = new BmsFreightPriceModel();
            priceModel.setSettlementModel(Integer.valueOf(freightPriceImportVO.getSettlementModel()));
            priceModel.setSettlementOrderType(Integer.valueOf(freightPriceImportVO.getSettlementOrderType()));
            if (ObjectUtil.isNotEmpty(freightPriceImportVO.getSettlementType())) {
                priceModel.setSettlementType(Integer.valueOf(freightPriceImportVO.getSettlementType()));
            }
            if (ObjectUtil.isNotEmpty(freightPriceImportVO.getLadderType())) {
                priceModel.setLadderType(Integer.valueOf(freightPriceImportVO.getLadderType()));
            }
            if (freightPriceImportVO.getExpenseName().contains("支出运费")) {
                priceModel.setIsSurcharge(0);
            } else {
                priceModel.setIsSurcharge(1);
            }
            // 费用的校验
            Criteria aClass = Criteria.forClass(BmsExpenseManagementModel.class);
            Restriction r11 = Restrictions.eq(BmsExpenseManagementModel::getExpenseName, freightPriceImportVO.getExpenseName());
            Restriction r12 = Restrictions.eq(BmsExpenseManagementModel::getStatus, 1);
            Restriction r13 = Restrictions.eq(BmsExpenseManagementModel::getEnterpriseId, user.getEnterpriseId());
            aClass.setRestriction(Restrictions.and(r11, r12, r13));
            List<BmsExpenseManagementModel> expenseManagementModels = expenseManagementMapper.findByCriteria(aClass);
            if (ObjectUtil.isEmpty(expenseManagementModels)) {
                throw new PrologException(String.format("费用[%s]不存在,或者费用已停用，请先配置费用", freightPriceImportVO.getExpenseName()));
            }
            priceModel.setContractNo(freightPriceImportVO.getContractNo());
            priceModel.setAging(freightPriceImportVO.getAging());
            priceModel.setMileage(freightPriceImportVO.getMileage());
            priceModel.setMemo(freightPriceImportVO.getMemo());
            priceModel.setPriceNo(freightPriceImportVO.getPriceNo());
            priceModel.setPriceName(freightPriceImportVO.getPriceName());
            priceModel.setShipperProvinceName(freightPriceImportVO.getShipperProvinceName());
            priceModel.setShipperCityName(freightPriceImportVO.getShipperCityName());
            priceModel.setShipperDistrictName(freightPriceImportVO.getShipperDistrictName());
            priceModel.setConsigneeProvinceName(freightPriceImportVO.getConsigneeProvinceName());
            priceModel.setConsigneeCityName(freightPriceImportVO.getConsigneeCityName());
            priceModel.setConsigneeDistrictName(freightPriceImportVO.getConsigneeDistrictName());
            priceModel.setPrice(freightPriceImportVO.getPrice());
            priceModel.setCreateperson(user.getNickname());
            priceModel.setCreatetime(DateUtil.date());
            priceModel.setUpdatetime(DateUtil.date());
            priceModel.setUpdateperson(user.getNickname());
            priceModel.setEnterpriseId(user.getEnterpriseId());
            priceModel.setEnterpriseName(user.getEnterpriseName());
            priceModel.setExpenseId(expenseManagementModels.get(0).getId());
            priceModel.setExpenseName(freightPriceImportVO.getExpenseName());
            priceModel.setStatus(2);
            priceModel.setSource(2);
            parseZone(freightPriceImportVO, zoneCodeMap, priceModel);
            priceMapper.save(priceModel);
            parseCondition(freightPriceImportVO, dicData);
            saveLadder(freightPriceImportVO, freightPriceList, dicData);
        }
        freightPriceImportVOS.stream().map(FreightPriceImportVO::getContractNo).distinct().forEach(contractNo -> {
            BmsLogOperationModel feeVo = new BmsLogOperationModel();
            feeVo.setCreatetime(DateUtil.date());
            feeVo.setCreateperson(user.getNickname());
            feeVo.setEnterpriseId(user.getEnterpriseId());
            feeVo.setEnterpriseName(user.getEnterpriseName());
            feeVo.setOrderNo(contractNo);
            feeVo.setLogMemo("运费价格导入");
            feeVo.setLogType(2);
            logOperationMapper.save(feeVo);
        });
        return freightPriceImportVOS.size();
    }

    /**
     * 行政区域解析
     */
    private void parseZone(FreightPriceImportVO freightPriceImportVO, Map<String, String> zoneCodeMap, BmsFreightPriceModel priceModel) {
        List<String> shipperAds = Lists.newArrayList();
        if (ObjectUtil.isNotEmpty(freightPriceImportVO.getShipperProvinceName())) {
            shipperAds.add(freightPriceImportVO.getShipperProvinceName());
            String zoneCode = zoneCodeMap.get(shipperAds.stream().collect(Collectors.joining()));
            if (ObjectUtil.isEmpty(zoneCode)) {
                zoneCode = getZoneCode(freightPriceImportVO.getShipperProvinceName(), Integer.valueOf(2), "01");
                if (ObjectUtil.isEmpty(zoneCode)) {
                    throw new PrologException(String.format("始发地省的行政编码[%s]获取失败,", shipperAds.stream().collect(Collectors.joining())));
                }
                zoneCodeMap.put(shipperAds.stream().collect(Collectors.joining()), zoneCode);
            }
            priceModel.setShipperProvince(zoneCode);
        }
        if (ObjectUtil.isNotEmpty(freightPriceImportVO.getShipperCityName())) {
            shipperAds.add(freightPriceImportVO.getShipperCityName());
            String zoneCode = zoneCodeMap.get(shipperAds.stream().collect(Collectors.joining()));
            if (ObjectUtil.isEmpty(zoneCode)) {
                zoneCode = getZoneCode(freightPriceImportVO.getShipperCityName(), Integer.valueOf(3), priceModel.getShipperProvince());
                if (ObjectUtil.isEmpty(zoneCode)) {
                    throw new PrologException(String.format("始发地市的行政编码[%s]获取失败,", shipperAds.stream().collect(Collectors.joining())));
                }
                zoneCodeMap.put(shipperAds.stream().collect(Collectors.joining()), zoneCode);
            }
            priceModel.setShipperCity(zoneCode);
        }
        if (ObjectUtil.isNotEmpty(freightPriceImportVO.getShipperDistrictName())) {
            shipperAds.add(freightPriceImportVO.getShipperDistrictName());
            String zoneCode = zoneCodeMap.get(shipperAds.stream().collect(Collectors.joining()));
            if (ObjectUtil.isEmpty(zoneCode)) {
                zoneCode = getZoneCode(freightPriceImportVO.getShipperDistrictName(), Integer.valueOf(4), priceModel.getShipperCity());
                if (ObjectUtil.isEmpty(zoneCode)) {
                    throw new PrologException(String.format("始发地区的行政编码[%s]获取失败,", shipperAds.stream().collect(Collectors.joining())));
                }
                zoneCodeMap.put(shipperAds.stream().collect(Collectors.joining()), zoneCode);
            }
            priceModel.setShipperDistrict(zoneCode);
        }
        List<String> consigneeAds = Lists.newArrayList();
        if (ObjectUtil.isNotEmpty(freightPriceImportVO.getConsigneeProvinceName())) {
            consigneeAds.add(freightPriceImportVO.getConsigneeProvinceName());
            String zoneCode = zoneCodeMap.get(consigneeAds.stream().collect(Collectors.joining()));
            if (ObjectUtil.isEmpty(zoneCode)) {
                zoneCode = getZoneCode(freightPriceImportVO.getConsigneeProvinceName(), Integer.valueOf(2), "01");
                if (ObjectUtil.isEmpty(zoneCode)) {
                    throw new PrologException(String.format("目的地省的行政编码[%s]获取失败,", consigneeAds.stream().collect(Collectors.joining())));
                }
                zoneCodeMap.put(consigneeAds.stream().collect(Collectors.joining()), zoneCode);
            }
            priceModel.setConsigneeProvince(zoneCode);
        }
        if (ObjectUtil.isNotEmpty(freightPriceImportVO.getConsigneeCityName())) {
            consigneeAds.add(freightPriceImportVO.getConsigneeCityName());
            String zoneCode = zoneCodeMap.get(consigneeAds.stream().collect(Collectors.joining()));
            if (ObjectUtil.isEmpty(zoneCode)) {
                zoneCode = getZoneCode(freightPriceImportVO.getConsigneeCityName(), Integer.valueOf(3), priceModel.getConsigneeProvince());
                if (ObjectUtil.isEmpty(zoneCode)) {
                    throw new PrologException(String.format("目的地市的行政编码[%s]获取失败,", consigneeAds.stream().collect(Collectors.joining())));
                }
                zoneCodeMap.put(consigneeAds.stream().collect(Collectors.joining()), zoneCode);
            }
            priceModel.setConsigneeCity(zoneCode);
        }
        if (ObjectUtil.isNotEmpty(freightPriceImportVO.getConsigneeDistrictName())) {
            consigneeAds.add(freightPriceImportVO.getConsigneeDistrictName());
            String zoneCode = zoneCodeMap.get(consigneeAds.stream().collect(Collectors.joining()));
            if (ObjectUtil.isEmpty(zoneCode)) {
                zoneCode = getZoneCode(freightPriceImportVO.getConsigneeDistrictName(), Integer.valueOf(4), priceModel.getConsigneeCity());
                if (ObjectUtil.isEmpty(zoneCode)) {
                    throw new PrologException(String.format("目的地区的行政编码[%s]获取失败,", consigneeAds.stream().collect(Collectors.joining())));
                }
                zoneCodeMap.put(consigneeAds.stream().collect(Collectors.joining()), zoneCode);
            }
            priceModel.setConsigneeDistrict(zoneCode);
        }
        priceModel.setShipperAddress(shipperAds.stream().collect(Collectors.joining()));
        priceModel.setConsigneeAddress(consigneeAds.stream().collect(Collectors.joining()));
    }

    /**
     * 价格阶梯对象
     */
    private void saveLadder(FreightPriceImportVO freightPriceImportVO, List<FreightPriceImportVO> freightPriceList, List<SysRefdatadModel> dicData) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.LADDER_COST)) || freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.JD_LADDER_COST))) {
            List<BmsFreightPriceLadderModel> ladderModels = Lists.newArrayList();
            for (FreightPriceImportVO importPriceLadder : freightPriceList) {
                BmsFreightPriceLadderModel priceLadderModel = new BmsFreightPriceLadderModel();
                priceLadderModel.setPriceNo(importPriceLadder.getPriceNo());
                priceLadderModel.setSectionUpSymbol(Integer.valueOf(ConvertorUtil.getCode(dicData, BmsConstant.LESS_THAN, importPriceLadder.getSectionUpSymbol())));
                priceLadderModel.setSectionDownSymbol(Integer.valueOf(ConvertorUtil.getCode(dicData, BmsConstant.SECTION_SYMBOL, importPriceLadder.getSectionDownSymbol())));
                priceLadderModel.setSectionUp(importPriceLadder.getSectionUp());
                priceLadderModel.setSectionDown(importPriceLadder.getSectionDown());
                priceLadderModel.setPrice(importPriceLadder.getLadderPrice());
                priceLadderModel.setLadderType(importPriceLadder.getPriceLadderType());
                priceLadderModel.setInitialLadder(importPriceLadder.getInitialLadder());
                priceLadderModel.setInitialLadderPrice(importPriceLadder.getInitialLadderPrice());
                priceLadderModel.setCalculateRule(ObjectUtil.isEmpty(importPriceLadder.getCalculateRule()) ? null : Integer.valueOf(ConvertorUtil.getCode(dicData, BmsConstant.CALCULATE_RULE, importPriceLadder.getCalculateRule())));
                priceLadderModel.setStartingPrice(importPriceLadder.getStartingPrice());
                priceLadderModel.setCreateperson(user.getNickname());
                priceLadderModel.setCreatetime(DateUtil.date());
                priceLadderModel.setUpdatetime(DateUtil.date());
                priceLadderModel.setUpdateperson(user.getNickname());
                priceLadderModel.setEnterpriseId(user.getEnterpriseId());
                priceLadderModel.setEnterpriseName(user.getEnterpriseName());
                ladderModels.add(priceLadderModel);
            }
            ladderMapper.saveBatch(ladderModels);
        }
    }

    /**
     * 价格表匹配条件
     */
    private void parseCondition(FreightPriceImportVO freightPriceImportVO, List<SysRefdatadModel> dicData) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        String matchConditions = freightPriceImportVO.getMatchCondition();
        if (ObjectUtil.isNotEmpty(matchConditions)) {
            // 按条件类型分割 配送方式:配送;发货方类型:仓库 王侯仓库,高创仓库;部门:部门1,部门2
            String[] conditionTypes = matchConditions.split(";");
            if (ObjectUtil.isNotEmpty(conditionTypes)) {
                List<String> conditionTypeList = Arrays.stream(conditionTypes).collect(Collectors.toList());
                List<BmsFreightPriceConditionModel> conditionModels = Lists.newArrayList();
                for (String type : conditionTypeList) {
                    Integer conditionType = null;
                    String conditionValue = null;
                    String unitId = null;
                    String unitCode = null;
                    String unitName = null;
                    String[] conditions = type.split(":");
                    if (ObjectUtil.isEmpty(conditions) || 2 > conditions.length) {
                        throw new ParameterException("匹配条件数据格式不正确");
                    }
                    if (ObjectUtil.isNotEmpty(conditions)) {
                        String conditionKeyName = conditions[0];
                        String conditionValName = conditions[1];
                        List<SysRefdatadModel> cntTypeList = dicData.stream().filter(data -> BmsConstant.BMS_APPROVAL_CONDITION_TYPE.equals(data.getObjectcode()) && data.getName().equals(conditionKeyName)).collect(Collectors.toList());
                        if (0 >= cntTypeList.size()) {
                            throw new PrologException(String.format("匹配条件类型[%s]在数据字典中不存在", conditionKeyName));
                        }
                        String code = cntTypeList.get(0).getCode();
                        if (ObjectUtil.isEmpty(code)) {
                            throw new PrologException(String.format("匹配条件类型[%s]对应的数据字典code值不存在", conditionKeyName));
                        }
                        conditionType = Integer.valueOf(code);
                        // 校验条件类型的值，在数据字典中是否存在
                        List<SysRefdatadModel> restConditionValue = null;
                        if (8 > conditionType.intValue()) {
                            switch (conditionType.intValue()) {
                                case 1:
                                    restConditionValue = dicData.stream().filter(data -> BmsConstant.DELIVERY_METHOD_TYPE.equals(data.getObjectcode())).collect(Collectors.toList());
                                    break;
                                case 2:
                                    restConditionValue = dicData.stream().filter(data -> BmsConstant.SHIPPER_TYPE.equals(data.getObjectcode())).collect(Collectors.toList());
                                    break;
                                case 3:
                                    restConditionValue = dicData.stream().filter(data -> BmsConstant.CONSIGNEE_TYPE.equals(data.getObjectcode())).collect(Collectors.toList());
                                    break;
                                case 4:
                                    restConditionValue = dicData.stream().filter(data -> BmsConstant.ORDER_TYPE.equals(data.getObjectcode())).collect(Collectors.toList());
                                    break;
                                case 5:
                                    restConditionValue = dicData.stream().filter(data -> BmsConstant.ORDER_BUSINESS_TYPE.equals(data.getObjectcode())).collect(Collectors.toList());
                                    break;
                                case 6:
                                    restConditionValue = dicData.stream().filter(data -> BmsConstant.TRANSPORT_TYPE.equals(data.getObjectcode())).collect(Collectors.toList());
                                    break;
                                case 7:
                                    restConditionValue = dicData.stream().filter(data -> BmsConstant.TEMPERATURE_REQUIREMENT.equals(data.getObjectcode())).collect(Collectors.toList());
                                    break;
                            }
                            log.info("获取匹配条件类型value的数据字典数据:" + restConditionValue);
                            List<SysRefdatadModel> deliveryDataModels = restConditionValue;
                            String[] conditionValKeyName = conditionValName.split(" ");
                            List<SysRefdatadModel> conditionValDataList = deliveryDataModels.stream().filter(data -> data.getName().equals(conditionValKeyName[0])).collect(Collectors.toList());
                            if (ObjectUtil.isEmpty(conditionValDataList)) {
                                throw new PrologException(String.format("匹配条件类型[%s]对应值的数据字典不存在", conditionValKeyName[0]));
                            }
                            conditionValue = conditionValDataList.get(0).getCode();
                            if (conditionType.intValue() == 2 || conditionType.intValue() == 3) {
                                if (2 > conditionValKeyName.length && conditionType.intValue() == 2) {
                                    throw new PrologException(String.format("匹配条件中的发货方[%s]数据不正确", conditionValKeyName[0]));
                                }
                                if (2 > conditionValKeyName.length && conditionType.intValue() == 3) {
                                    throw new PrologException(String.format("匹配条件中的收货方[%s]数据不正确", conditionValKeyName[0]));
                                }
                                List<GetCodeByNameDTO> shippers = getShipperInfo(conditionValKeyName[1], conditionValue);
                                if (ObjectUtil.isNotEmpty(shippers)) {
                                    unitId = shippers.stream().map(GetCodeByNameDTO::getUnitId).collect(Collectors.joining(","));
                                    unitCode = shippers.stream().map(GetCodeByNameDTO::getUnitCode).collect(Collectors.joining(","));
                                    unitName = shippers.stream().map(GetCodeByNameDTO::getUnitName).collect(Collectors.joining(","));
                                }
                            }
                        } else if (conditionType.intValue() > 12) {
                            List<GetCodeByNameDTO> baseDataInfos = getCondition(conditionValName, conditionType, user);
                            if (ObjectUtil.isNotEmpty(baseDataInfos)) {
                                conditionValue = baseDataInfos.stream().map(GetCodeByNameDTO::getConditionValue).collect(Collectors.joining());
                                unitId = baseDataInfos.stream().map(GetCodeByNameDTO::getUnitId).collect(Collectors.joining(","));
                                unitCode = baseDataInfos.stream().map(GetCodeByNameDTO::getUnitCode).collect(Collectors.joining(","));
                                unitName = baseDataInfos.stream().map(GetCodeByNameDTO::getUnitName).collect(Collectors.joining(","));
                            }
                        } else {
                            List<GetCodeByNameDTO> baseDataInfos = getBaseDataInfo(conditionValName, conditionType, user);
                            if (ObjectUtil.isNotEmpty(baseDataInfos)) {
                                unitId = baseDataInfos.stream().map(GetCodeByNameDTO::getUnitId).collect(Collectors.joining(","));
                                unitCode = baseDataInfos.stream().map(GetCodeByNameDTO::getUnitCode).collect(Collectors.joining(","));
                                unitName = baseDataInfos.stream().map(GetCodeByNameDTO::getUnitName).collect(Collectors.joining(","));
                            }
                        }
                    }
                    // 保存价格表匹配条件
                    BmsFreightPriceConditionModel priceConditionModel = new BmsFreightPriceConditionModel();
                    priceConditionModel.setConditionType(conditionType);
                    priceConditionModel.setConditionValue(conditionValue);
                    priceConditionModel.setPriceNo(freightPriceImportVO.getPriceNo());
                    priceConditionModel.setUnitId(unitId);
                    priceConditionModel.setUnitCode(unitCode);
                    priceConditionModel.setUnitName(unitName);
                    priceConditionModel.setCreateperson(user.getNickname());
                    priceConditionModel.setCreatetime(DateUtil.date());
                    priceConditionModel.setUpdatetime(DateUtil.date());
                    priceConditionModel.setUpdateperson(user.getNickname());
                    priceConditionModel.setEnterpriseId(user.getEnterpriseId());
                    priceConditionModel.setEnterpriseName(user.getEnterpriseName());
                    priceConditionModel.setConditionTypeName(ConvertorUtil.getName(dicData, BmsConstant.BMS_APPROVAL_CONDITION_TYPE, String.valueOf(conditionType)));
                    priceConditionModel.setConditionName(priceConditionModel.getConditionTypeName());
                    conditionModels.add(priceConditionModel);
                }
                conditionMapper.saveBatch(conditionModels);
            }
        }
    }

    /**
     * 校验
     */
    private void preCheck(List<FreightPriceImportVO> freightPriceImportVOS, List<SysRefdatadModel> dicData) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        int i = 1;
        for (FreightPriceImportVO freightPriceImportVO : freightPriceImportVOS) {
            log.info("数据校验,导入的第" + i + "行数据:" + JSON.toJSONString(freightPriceImportVO));
            if (ObjectUtil.isEmpty(freightPriceImportVO.getContractNo())) {
                throw new PrologException("第" + i + "行导入数据,合同编号不为空");
            }
            if (ObjectUtil.isEmpty(freightPriceImportVO.getContractName())) {
                throw new PrologException("第" + i + "行导入数据,合同名称不为空");
            }
            if (ObjectUtil.isEmpty(freightPriceImportVO.getPriceNo())) {
                throw new PrologException("第" + i + "行导入数据,价格编号不为空");
            }
            if (ObjectUtil.isEmpty(freightPriceImportVO.getPriceName())) {
                throw new PrologException("第" + i + "行导入数据,价格名称不为空");
            }
            if (ObjectUtil.isEmpty(freightPriceImportVO.getExpenseName())) {
                throw new PrologException("第" + i + "行导入数据,费用不为空");
            }
            if (ObjectUtil.isEmpty(freightPriceImportVO.getSettlementOrderType())) {
                throw new PrologException("第" + i + "行导入数据,计费单据不为空");
            }
            if (ObjectUtil.isEmpty(freightPriceImportVO.getSettlementModel())) {
                throw new PrologException("第" + i + "行导入数据,计费模式不为空");
            }
            if (ObjectUtil.isEmpty(freightPriceImportVO.getNumber())) {
                throw new PrologException("第" + i + "行导入数据,序号不为空");
            }
            // 合同存在性校验
            Criteria criteriaContract = Criteria.forClass(BmsLogisticsContractModel.class);
            Restriction r1 = Restrictions.eq(BmsLogisticsContractModel::getContractNo, freightPriceImportVO.getContractNo());
            Restriction r2 = Restrictions.eq(BmsLogisticsContractModel::getContractName, freightPriceImportVO.getContractName());
            Restriction r3 = Restrictions.eq(BmsLogisticsContractModel::getEnterpriseId, user.getEnterpriseId());
            criteriaContract.setRestriction(Restrictions.and(r1, r2, r3));
            List<BmsLogisticsContractModel> models = contractMapper.findByCriteria(criteriaContract);
            if (ObjectUtil.isEmpty(models)) {
                throw new PrologException("第" + i + "行导入数据,合同在合同数据中不存在");
            }
            // 价格编号和价格名称重复校验
            Criteria criteriaPrice = Criteria.forClass(BmsFreightPriceModel.class);
            Restriction r4 = Restrictions.eq(BmsFreightPriceModel::getPriceNo, freightPriceImportVO.getPriceNo());
            criteriaPrice.setRestriction(Restrictions.and(r3, r4));
            List<BmsFreightPriceModel> priceModels = priceMapper.findByCriteria(criteriaPrice);
            if (ObjectUtil.isNotEmpty(priceModels)) {
                throw new PrologException(String.format("第" + i + "行导入数据, 价格编码[%s]在价格表中已存在，请不要重复添加", freightPriceImportVO.getPriceNo()));
            }
            // 价格编号和价格名称重复校验
            /*r4 = Restrictions.eq(BmsFreightPriceModel::getPriceName, freightPriceImportVO.getPriceName());
            criteriaPrice.setRestriction(Restrictions.and(r3, r4));
            priceModels = priceMapper.findByCriteria(criteriaPrice);
            if (ObjectUtil.isNotEmpty(priceModels)) {
                throw new PrologException(String.format("第" + i + "行导入数据, 价格名称[%s]在价格表中已存在，请不要重复添加", freightPriceImportVO.getPriceName()));
            }*/
            if (ObjectUtil.isNotEmpty(freightPriceImportVO.getPriceLadderType())) {
                Criteria criteriaPriceLadder = Criteria.forClass(BmsFreightPriceLadderModel.class);
                r4 = Restrictions.eq(BmsFreightPriceLadderModel::getLadderType, freightPriceImportVO.getPriceLadderType());
                criteriaPriceLadder.setRestriction(Restrictions.and(r3, r4));
                List<BmsFreightPriceLadderModel> priceLadderModels = ladderMapper.findByCriteria(criteriaPriceLadder);
                if (ObjectUtil.isNotEmpty(priceLadderModels)) {
                    throw new PrologException(String.format("第" + i + "行导入数据, 类别[%s]在阶梯表中已存在，请不要重复添加", freightPriceImportVO.getPriceLadderType()));
                }
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.LADDER_COST))
                    && ObjectUtil.isEmpty(freightPriceImportVO.getLadderType())) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为阶梯计费,则阶梯方式不为空");
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.LADDER_COST))
                    && ObjectUtil.isEmpty(freightPriceImportVO.getSettlementType())) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为阶梯计费,则计费方式不为空");
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.JD_LADDER_COST))
                    && !freightPriceImportVO.getSettlementOrderType().equals("3")) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为京东阶梯计费,只支持【运单包裹】计费单据");
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.JD_LADDER_COST))
                    && ObjectUtil.isEmpty(freightPriceImportVO.getLadderType())) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为京东阶梯计费,则阶梯方式不为空");
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.JD_LADDER_COST))
                    && !freightPriceImportVO.getLadderType().equals("1")) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为京东阶梯计费,只支持【按KG】阶梯方式");
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.JD_LADDER_COST))
                    && !freightPriceImportVO.getSettlementType().equals("2")) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为京东阶梯计费,只支持【元/千克】计费方式");
            }
            if (String.valueOf(BmsConstant.PRICE_MERGE_INCOME).equals(freightPriceImportVO.getSettlementModel())) {
                throw new PrologException(StrUtil.format("第{}行导入数据, 托运物流价格,计费模式不支持【单价-合并计费】的计费", i));
            }
            String matchConditions = freightPriceImportVO.getMatchCondition();
            if (ObjectUtil.isNotEmpty(matchConditions)) {
                List<String> names = dicData.stream().filter(m -> BmsConstant.BMS_APPROVAL_CONDITION_TYPE.equals(m.getObjectcode()) && String.valueOf(1).equals(m.getGroupcode1())).map(SysRefdatadModel::getName).collect(Collectors.toList());
                if (!checkCondition(matchConditions, names)) {
                    throw new PrologException(StrUtil.format("第{}行导入数据, 托运物流价格,匹配条件只支持:{}", i, names.stream().collect(Collectors.joining(","))));
                }
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.LADDER_COST))
                    && ObjectUtil.isEmpty(freightPriceImportVO.getSectionDown())
                    && ObjectUtil.isEmpty(freightPriceImportVO.getSectionUp())) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为阶梯计费,则区间下限,区间上限至少输入一个");
            }

            if (ObjectUtil.isNotEmpty(freightPriceImportVO.getSectionUp()) && ObjectUtil.isEmpty(freightPriceImportVO.getSectionUpSymbol())) {
                throw new PrologException("第" + i + "行导入数据, 则区间上限存在时,则区间上限符号不为空");
            }
            if (ObjectUtil.isNotEmpty(freightPriceImportVO.getSectionDown()) && ObjectUtil.isEmpty(freightPriceImportVO.getSectionDownSymbol())) {
                throw new PrologException("第" + i + "行导入数据, 则区间下限存在时,则区间下限符号不为空");
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.LADDER_COST))
                    && ObjectUtil.isNotEmpty(freightPriceImportVO.getSectionDown())
                    && ObjectUtil.isNotEmpty(freightPriceImportVO.getSectionUp())
                    && NumberUtil.isGreater(freightPriceImportVO.getSectionDown(), freightPriceImportVO.getSectionUp())) {
                throw new PrologException("第" + i + "行导入数据, 区间下限值不能大于区间上限值");
            }
            if ((freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.PRICE))
                    || freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.PRICE_NUM))
                    || freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.PRICE_MERGE_INCOME)))
                    && ObjectUtil.isEmpty(freightPriceImportVO.getPrice())) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为【一口价,按个计费,单价-合并计费】,则单价不为空");
            }
            if ((freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.PRICE_MERGE))
                    || freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.PRICE_TIME)))
                    && ObjectUtil.isEmpty(freightPriceImportVO.getPrice())) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为【一口价-合并计费,按时间计费】,则单价不为空");
            }
            if ((freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.PRICE_MERGE))
                    || freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.PRICE_MERGE_INCOME))
                    || freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.PRICE_TIME)))
                    && ObjectUtil.isEmpty(freightPriceImportVO.getStrategyName())) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为【一口价-合并计费,单价-合并计费,按时间计费】,则策略不为空");
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.PRICE_PROPORTION))
                    && ObjectUtil.isEmpty(freightPriceImportVO.getStrategyName())) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为比例计费,则策略不为空");
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.PRICE_TIME))
                    && ObjectUtil.isEmpty(freightPriceImportVO.getSettlementType())) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为按时间计费,则计费方式不为空");
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.JD_LADDER_COST))
                    && ObjectUtil.isEmpty(freightPriceImportVO.getSectionDown())
                    && ObjectUtil.isEmpty(freightPriceImportVO.getSectionUp())) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为京东阶梯计费,则区间下限,区间上限至少输入一个");
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.JD_LADDER_COST))
                    && ObjectUtil.isNotEmpty(freightPriceImportVO.getSectionDown())
                    && ObjectUtil.isNotEmpty(freightPriceImportVO.getSectionUp())
                    && NumberUtil.isGreater(freightPriceImportVO.getSectionDown(), freightPriceImportVO.getSectionUp())) {
                throw new PrologException("第" + i + "行导入数据, 区间下限值不能大于区间上限值");
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.JD_LADDER_COST))
                    && ObjectUtil.isEmpty(freightPriceImportVO.getLadderPrice())) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为按京东阶梯计费,则阶梯单价不为空");
            }
            if (freightPriceImportVO.getSettlementModel().equals(String.valueOf(BmsConstant.JD_LADDER_COST))
                    && ObjectUtil.isEmpty(freightPriceImportVO.getCalculateRule())) {
                throw new PrologException("第" + i + "行导入数据, 计费模式为按京东阶梯计费,则计算规则不为空");
            }
            i++;
        }
    }

    public String getZoneCode(String zoneName, Integer zlevel, String fatherId) {
        String zoneCode = null;
        List<LmsTmsZoneDTO> zoneList = Lists.newArrayList();
        if (ToolKits.isNotEmpty(zoneName)) {
            LmsTmsZoneQueryVO zoneQueryVO = new LmsTmsZoneQueryVO();
            zoneQueryVO.setZname(zoneName);
            zoneQueryVO.setZlevel(zlevel);
            zoneQueryVO.setFatherid(fatherId);
            RestMessage<List<LmsTmsZoneDTO>> zoneModelRestMessage = maindataTmsResource.getLmsTmsZoneByNameExecute(zoneQueryVO);
            if (zoneModelRestMessage.isSuccess()) {
                zoneList = zoneModelRestMessage.getData();
            } else {
                throw new ParameterException("行政编码获取失败");
            }
        }
        if (ObjectUtil.isNotEmpty(zoneList) && ObjectUtil.isNotEmpty(zoneList.get(0).getZoneid())) {
            zoneCode = zoneList.get(0).getZoneid();
        }
        return zoneCode;
    }

    public List<GetCodeByNameDTO> getShipperInfo(String unitName, String code) {
        if (ObjectUtil.isEmpty(unitName)) {
            throw new ParameterException("收,发货方名称为空");
        }
        List<GetCodeByNameDTO> codeByNameDTOList = Lists.newArrayList();
        List<String> keyNames = Arrays.stream(unitName.split(",")).collect(Collectors.toList());
        for (String keyName : keyNames) {
            GetCodeByNameDTO dto = new GetCodeByNameDTO();
            // 发货方信息匹配
            if (code.equals(BmsConstant.SHIPPER_TYPE_KH.toString())) {
                // 请求对象
                CustomerByEncodingNameVO customerVO = new CustomerByEncodingNameVO();
                customerVO.setName(keyName);
                RestMessage<CustomerByEncodingNameDTO> restMessageShipperUnit = maindataTmsResource.getCustomerByNameExecute(customerVO);
                if (!restMessageShipperUnit.isSuccess()) {
                    throw new ParameterException("调用客户查询服务失败:" + restMessageShipperUnit.getMessage());
                }
                if (ObjectUtil.isEmpty(restMessageShipperUnit.getData())) {
                    throw new PrologException(String.format("客户[%s]不存在", keyName));
                }
                dto.setUnitId(restMessageShipperUnit.getData().getId().toString());
                dto.setUnitCode(restMessageShipperUnit.getData().getCode());
                dto.setUnitName(keyName);
            } else if (code.equals(BmsConstant.SHIPPER_TYPE_CK.toString())) {
                // 请求对象
                BranchByNameVO branchByNameVO = new BranchByNameVO();
                branchByNameVO.setName(keyName);
                RestMessage<BranchByNameDTO> restMessageShipperUnit = maindataTmsResource.getBranchByNameExecute(branchByNameVO);
                if (!restMessageShipperUnit.isSuccess()) {
                    throw new ParameterException("调用仓库查询服务失败:" + restMessageShipperUnit.getMessage());
                }
                if (ObjectUtil.isEmpty(restMessageShipperUnit.getData())) {
                    throw new PrologException(String.format("仓库[%s]不存在", keyName));
                }
                dto.setUnitId(restMessageShipperUnit.getData().getId().toString());
                dto.setUnitCode(restMessageShipperUnit.getData().getCode());
                dto.setUnitName(keyName);
            } else {
                // 请求对象
                ProviderCheckVO providerCheckVO = new ProviderCheckVO();
                providerCheckVO.setName(keyName);
                RestMessage<ProviderCheckDTO> restMessageShipperUnit = maindataTmsResource.getProviderByNameExecute(providerCheckVO);
                if (!restMessageShipperUnit.isSuccess()) {
                    throw new ParameterException("调用供应商查询服务失败:" + restMessageShipperUnit.getMessage());
                }
                if (ObjectUtil.isEmpty(restMessageShipperUnit.getData())) {
                    throw new PrologException(String.format("供应商[%s]不存在", keyName));
                }
                dto.setUnitId(restMessageShipperUnit.getData().getId().toString());
                dto.setUnitCode(restMessageShipperUnit.getData().getCode());
                dto.setUnitName(keyName);
            }
            codeByNameDTOList.add(dto);
        }
        return codeByNameDTOList;
    }

    public List<GetCodeByNameDTO> getBaseDataInfo(String unitName, Integer conditionType, UserEntity user) {
        if (ObjectUtil.isEmpty(unitName)) {
            throw new ParameterException("匹配条件数据中,条件的名称为空");
        }
        List<GetCodeByNameDTO> codeByNameDTOList = Lists.newArrayList();
        List<String> keyNames = Arrays.stream(unitName.split(",")).collect(Collectors.toList());
        for (String keyName : keyNames) {
            GetCodeByNameDTO dto = new GetCodeByNameDTO();
            if (conditionType.intValue() == 8) {
                // 货主
                CargoOwnerCheckVO cargoOwnerVO = new CargoOwnerCheckVO();
                cargoOwnerVO.setCargoOwnerName(keyName);
                RestMessage<CargoOwnerCheckDTO> restMessageCargoOwnerUnit = maindataTmsResource.getCargoOwnerByNameExecute(cargoOwnerVO);
                if (!restMessageCargoOwnerUnit.isSuccess()) {
                    throw new ParameterException("调用货主查询服务失败:" + restMessageCargoOwnerUnit.getMessage());
                }
                if (ObjectUtil.isEmpty(restMessageCargoOwnerUnit.getData())) {
                    throw new PrologException(String.format("货主[%s]不存在", keyName));
                }
                dto.setUnitId(restMessageCargoOwnerUnit.getData().getCargoOwnerId().toString());
                dto.setUnitCode(restMessageCargoOwnerUnit.getData().getCargoOwnerCode());
                dto.setUnitName(keyName);
            } else if (conditionType.intValue() == 9) {
                // 部门
                RestMessage<List<Organization>> departMents = userFeign.search(null, keyName, null, String.valueOf(user.getEnterpriseId()));
                if (!departMents.isSuccess()) {
                    throw new RuntimeException("用户部门信息查询失败:" + departMents.getMessage());
                } else {
                    List<Organization> data1 = departMents.getData();
                    if (data1.size() == 0) {
                        throw new RuntimeException("部门【" + keyName + "】不存在!");
                    }
                    if (data1.size() > 1) {
                        throw new RuntimeException("部门名称【" + keyName + "】重复，请先维护部门!");
                    }
                    if (!user.getDepts().contains(data1.get(0).getId())) {
                        throw new RuntimeException("部门【" + keyName + "】不存在，请先维护部门!");
                    }
                    // 部门信息赋值
                    Organization organization = data1.get(0);
                    dto.setUnitId(organization.getId());
                    dto.setUnitCode(organization.getCode());
                    dto.setUnitName(keyName);
                }
            } else if (conditionType.intValue() == 10) {
                // 商品
                ItemCheckVO itemVO = new ItemCheckVO();
                itemVO.setItemName(keyName);
                RestMessage<ItemCheckDTO> restMessageItemUnit = maindataTmsResource.getItemByNameExecute(itemVO);
                if (!restMessageItemUnit.isSuccess()) {
                    throw new ParameterException("调用商品查询服务失败:" + restMessageItemUnit.getMessage());
                }
                if (ObjectUtil.isEmpty(restMessageItemUnit.getData())) {
                    throw new PrologException(String.format("商品[%s]不存在", keyName));
                }
                dto.setUnitId(restMessageItemUnit.getData().getItemId().toString());
                dto.setUnitCode(restMessageItemUnit.getData().getItemCode());
                dto.setUnitName(keyName);
            } else if (conditionType.intValue() == 11) {
                // 商品品类
                ItemCategoryCheckVO itemCategoryVO = new ItemCategoryCheckVO();
                itemCategoryVO.setItemCategoryName(keyName);
                RestMessage<ItemCategoryCheckDTO> restMessageItemCategoryUnit = maindataTmsResource.getItemCategoryByNameExecute(itemCategoryVO);
                if (!restMessageItemCategoryUnit.isSuccess()) {
                    throw new ParameterException("调用商品品类查询服务失败:" + restMessageItemCategoryUnit.getMessage());
                }
                if (ObjectUtil.isEmpty(restMessageItemCategoryUnit.getData())) {
                    throw new PrologException(String.format("商品品类[%s]不存在", keyName));
                }
                dto.setUnitId(restMessageItemCategoryUnit.getData().getItemCategoryId().toString());
                dto.setUnitCode(restMessageItemCategoryUnit.getData().getItemCategoryCode());
                dto.setUnitName(keyName);
            } else if (conditionType.intValue() == 12) {
                // 车型
                VehicleTypeCheckVO vehicleTypeVO = new VehicleTypeCheckVO();
                vehicleTypeVO.setVehicleTypeName(keyName);
                RestMessage<VehicleTypeCheckDTO> restMessageVehicleTypeUnit = maindataTmsResource.getVehicleTypeByNameExecute(vehicleTypeVO);
                if (!restMessageVehicleTypeUnit.isSuccess()) {
                    throw new ParameterException("调用车型查询服务失败:" + restMessageVehicleTypeUnit.getMessage());
                }
                if (ObjectUtil.isEmpty(restMessageVehicleTypeUnit.getData())) {
                    throw new PrologException(String.format("车型[%s]不存在", keyName));
                }
                dto.setUnitId(restMessageVehicleTypeUnit.getData().getId().toString());
                dto.setUnitCode(restMessageVehicleTypeUnit.getData().getCode());
                dto.setUnitName(keyName);
            }
            codeByNameDTOList.add(dto);
        }
        return codeByNameDTOList;
    }


    public List<GetCodeByNameDTO> getCondition(String conditionValName, Integer conditionType, UserEntity user) {
        if (ObjectUtil.isEmpty(conditionValName)) {
            throw new ParameterException("匹配条件数据中,条件的名称为空");
        }
        List<GetCodeByNameDTO> codeByNameDTOList = Lists.newArrayList();

        switch (conditionType.intValue()) {
            case 13:
            case 18:
            case 19:
            case 21:
                String[] conditionVal1 = conditionValName.split(",");
                if (ObjectUtil.isNotEmpty(conditionVal1)) {
                    GetCodeByNameDTO dto1 = new GetCodeByNameDTO();
                    dto1.setConditionValue(conditionVal1[0]);
                    dto1.setUnitId(conditionVal1[1]);
                    dto1.setUnitCode(conditionVal1[1]);
                    dto1.setUnitName(conditionVal1[1]);
                    codeByNameDTOList.add(dto1);
                }
                break;
            case 17:
                List<String> keyNames1 = Arrays.stream(conditionValName.split(",")).collect(Collectors.toList());
                for (String keyName : keyNames1) {
                    // 线路
                    TmsBaseTranslineVO translineVO = new TmsBaseTranslineVO();
                    translineVO.setLineName(keyName);
                    RestMessage<TmsBaseTranslineViewDTO> lineViewDTO = maindataTmsResource.viewLineByName(translineVO);
                    if (!lineViewDTO.isSuccess()) {
                        throw new ParameterException("调用线路查询服务失败:" + lineViewDTO.getMessage());
                    }
                    if (ObjectUtil.isEmpty(lineViewDTO.getData())) {
                        throw new PrologException(String.format("线路[%s]不存在", keyName));
                    }
                    GetCodeByNameDTO dto2 = new GetCodeByNameDTO();
                    dto2.setUnitId(lineViewDTO.getData().getLineId().toString());
                    dto2.setUnitCode(lineViewDTO.getData().getLineCode());
                    dto2.setUnitName(keyName);
                    codeByNameDTOList.add(dto2);
                }
                break;
            case 20:
                List<String> keyNames2 = Arrays.stream(conditionValName.split(",")).collect(Collectors.toList());
                for (String keyName : keyNames2) {
                    // 线路
                    StationQueryVO stationQueryVO = new StationQueryVO();
                    stationQueryVO.setName(keyName);
                    RestMessage<StationViewDTO> stationViewDTO = maindataTmsResource.viewStationByNameExecute(stationQueryVO);
                    if (!stationViewDTO.isSuccess()) {
                        throw new ParameterException("调用站点查询服务失败:" + stationViewDTO.getMessage());
                    }
                    if (ObjectUtil.isEmpty(stationViewDTO.getData())) {
                        throw new PrologException(String.format("站点[%s]不存在", keyName));
                    }
                    GetCodeByNameDTO dto3 = new GetCodeByNameDTO();
                    dto3.setUnitId(stationViewDTO.getData().getId().toString());
                    dto3.setUnitCode(stationViewDTO.getData().getCode());
                    dto3.setUnitName(keyName);
                    codeByNameDTOList.add(dto3);
                }
                break;
            default:
                GetCodeByNameDTO dto4 = new GetCodeByNameDTO();
                dto4.setConditionValue(conditionValName);
                codeByNameDTOList.add(dto4);
                break;
        }
        return codeByNameDTOList;
    }

    /**
     * 导出所有页数据
     *
     * @param vo
     * @return
     */
    @Override
    public List<FreightPriceExportDTO> exportAllPriceData(FreightPriceExportVO vo) {
        if (ObjectUtil.isEmpty(vo)) {
            throw new PrologException("导出请求不为空");
        }
        if (ObjectUtil.isEmpty(vo.getContractNo())) {
            throw new PrologException("合同编号不为空");
        }
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        Criteria criteria = Criteria.forClass(BmsFreightPriceModel.class);
        Restriction r1 = Restrictions.eq("contractNo", vo.getContractNo());
        Restriction r2 = Restrictions.eq("isSurcharge", vo.getIsSurcharge());
        Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2, r3));
        criteria.setOrder(Order.newInstance().desc("updatetime").asc("createtime"));
        List<BmsFreightPriceModel> models = priceMapper.findByCriteria(criteria);

        if (ObjectUtil.isNotEmpty(models)) {
            return getExportPriceDate(models, user);
        }
        return null;
    }

    /**
     * 导出当前数据
     *
     * @param vo
     * @return
     */
    @Override
    public List<FreightPriceExportDTO> exportPagePriceData(FreightPriceExportVO vo) {
        if (ObjectUtil.isEmpty(vo)) {
            throw new PrologException("导出请求不为空");
        }
        if (ObjectUtil.isEmpty(vo.getContractNo())) {
            throw new PrologException("合同编号不为空");
        }
        if (ObjectUtil.isEmpty(vo.getPageNum())) {
            throw new PrologException("当前页码不为空");
        }
        if (ObjectUtil.isEmpty(vo.getPageSize())) {
            throw new PrologException("每页条数不为空");
        }
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        Criteria criteria = Criteria.forClass(BmsFreightPriceModel.class);
        Restriction r1 = Restrictions.eq("contractNo", vo.getContractNo());
        Restriction r2 = Restrictions.eq("isSurcharge", vo.getIsSurcharge());
        Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2, r3));
        criteria.setOrder(Order.newInstance().desc("updatetime").asc("createtime"));
        PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
        List<BmsFreightPriceModel> models = priceMapper.findByCriteria(criteria);

        if (ObjectUtil.isNotEmpty(models)) {
            return getExportPriceDate(models, user);
        }
        return null;
    }

    /**
     * 导出选择数据
     *
     * @param ids
     * @return
     */
    @Override
    public List<FreightPriceExportDTO> exportChoosePriceData(List<String> ids) {
        if (ObjectUtil.isEmpty(ids)) {
            throw new PrologException("导出请求不为空");
        }
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        List<BmsFreightPriceModel> models = priceMapper.findByIds(BmsFreightPriceModel.class, ids.stream().toArray(), null);

        if (ObjectUtil.isNotEmpty(models)) {
            return getExportPriceDate(models, user);
        }
        return null;
    }

    public List<FreightPriceExportDTO> getExportPriceDate(List<BmsFreightPriceModel> models, UserEntity user) {
        if (ObjectUtil.isEmpty(models)) {
            return null;
        }
        List<FreightPriceExportDTO> dtos = Lists.newArrayList();
        List<SysRefdatadModel> dicData = convertorUtil.getDictionary(new String[]{
                BmsConstant.COST_TYPE,
                BmsConstant.SETTLEMENT_MODEL,
                BmsConstant.LADDER_TYPE,
                BmsConstant.CONTRACT_STATUS,
                BmsConstant.SOURCE,
                BmsConstant.SETTLEMENT_TYPE,
                BmsConstant.SECTION_SYMBOL,
                BmsConstant.LESS_THAN,
                BmsConstant.DELIVERY_METHOD_TYPE,
                BmsConstant.SHIPPER_TYPE,
                BmsConstant.CONSIGNEE_TYPE,
                BmsConstant.ORDER_TYPE,
                BmsConstant.ORDER_BUSINESS_TYPE,
                BmsConstant.TRANSPORT_TYPE,
                BmsConstant.TEMPERATURE_REQUIREMENT
        });
        int idx = 1;

        // 合同名称
        Criteria criteriaContract = Criteria.forClass(BmsLogisticsContractModel.class);
        Restriction r1 = Restrictions.eq(BmsLogisticsContractModel::getContractNo, models.get(0).getContractNo());
        Restriction r2 = Restrictions.eq(BmsLogisticsContractModel::getEnterpriseId, user.getEnterpriseId());
        criteriaContract.setRestriction(Restrictions.and(r1, r2));
        List<BmsLogisticsContractModel> contractmodels = contractMapper.findByCriteria(criteriaContract);
        if (ObjectUtil.isEmpty(contractmodels)) {
            throw new PrologException("合同【" + models.get(0).getContractNo() + "】不存在");
        }
        for (BmsFreightPriceModel model : models) {
            FreightPriceExportDTO dto = new FreightPriceExportDTO();
            BeanUtils.copyProperties(model, dto);
            dto.setSettlementModelName(ConvertorUtil.getName(dicData, BmsConstant.SETTLEMENT_MODEL, String.valueOf(model.getSettlementModel())));
            dto.setSettlementTypeName(ConvertorUtil.getName(dicData, BmsConstant.SETTLEMENT_TYPE, String.valueOf(model.getSettlementType())));
            dto.setLadderTypeName(ConvertorUtil.getName(dicData, BmsConstant.LADDER_TYPE, String.valueOf(model.getLadderType())));
            dto.setNumber(idx);
            dto.setContractName(contractmodels.get(0).getContractName());
            idx++;

            // 查询匹配条件
            Criteria aClass = Criteria.forClass(BmsFreightPriceConditionModel.class);
            Restriction r5 = Restrictions.eq("priceNo", model.getPriceNo());
            Restriction r6 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            aClass.setRestriction(Restrictions.and(r5, r6));
            List<BmsFreightPriceConditionModel> conditionModels = conditionMapper.findByCriteria(aClass);
            if (ObjectUtil.isNotEmpty(conditionModels)) {
                List<String> conditionListName = Lists.newArrayList();
                for (BmsFreightPriceConditionModel conditionModel : conditionModels) {
                    String conditionValueName = null;
                    switch (conditionModel.getConditionType().intValue()) {
                        case 1:
                            conditionValueName = ConvertorUtil.getName(dicData, BmsConstant.DELIVERY_METHOD_TYPE, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName);
                            break;
                        case 2:
                            conditionValueName = ConvertorUtil.getName(dicData, BmsConstant.SHIPPER_TYPE, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName + " " + conditionModel.getUnitName());
                            break;
                        case 3:
                            conditionValueName = ConvertorUtil.getName(dicData, BmsConstant.CONSIGNEE_TYPE, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName + " " + conditionModel.getUnitName());
                            break;
                        case 4:
                            conditionValueName = ConvertorUtil.getName(dicData, BmsConstant.ORDER_TYPE, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName);
                            break;
                        case 5:
                            conditionValueName = ConvertorUtil.getName(dicData, BmsConstant.ORDER_BUSINESS_TYPE, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName);
                            break;
                        case 6:
                            conditionValueName = ConvertorUtil.getName(dicData, BmsConstant.TRANSPORT_TYPE, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName);
                            break;
                        case 7:
                            conditionValueName = ConvertorUtil.getName(dicData, BmsConstant.TEMPERATURE_REQUIREMENT, String.valueOf(conditionModel.getConditionValue()));
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionValueName);
                            break;
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                        case 12:
                        case 17:
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionModel.getUnitName());
                            break;
                        case 13:
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionModel.getConditionValue() + " " + conditionModel.getUnitName());
                            break;
                        case 14:
                        case 15:
                        case 16:
                            conditionListName.add(conditionModel.getConditionTypeName() + ":" + conditionModel.getConditionValue());
                            break;
                        default:
                            break;
                    }
                }
                String join = Joiner.on(";").join(conditionListName);
                dto.setMatchCondition(join);
            }
            // 查询阶梯条件
            Criteria lClass = Criteria.forClass(BmsFreightPriceLadderModel.class);
            Restriction r7 = Restrictions.eq("priceNo", model.getPriceNo());
            Restriction r8 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
            lClass.setRestriction(Restrictions.and(r7, r8));
            List<BmsFreightPriceLadderModel> ladderModels = ladderMapper.findByCriteria(lClass);
            if (ObjectUtil.isNotEmpty(ladderModels)) {
                for (BmsFreightPriceLadderModel priceLadderModel : ladderModels) {
                    FreightPriceExportDTO ladderDTO = new FreightPriceExportDTO();
                    BeanUtils.copyProperties(dto, ladderDTO);
                    ladderDTO.setSectionDown(priceLadderModel.getSectionDown());
                    ladderDTO.setSectionUp(priceLadderModel.getSectionUp());
                    ladderDTO.setLadderPrice(priceLadderModel.getPrice());
                    ladderDTO.setPriceLadderType(priceLadderModel.getLadderType());
                    ladderDTO.setStartingPrice(priceLadderModel.getStartingPrice());
                    ladderDTO.setInitialLadder(priceLadderModel.getInitialLadder());
                    if (ObjectUtil.isNotEmpty(priceLadderModel.getSectionDownSymbol())) {
                        ladderDTO.setSectionDownSymbol(ConvertorUtil.getName(dicData, BmsConstant.SECTION_SYMBOL, String.valueOf(priceLadderModel.getSectionDownSymbol())));
                    }
                    if (ObjectUtil.isNotEmpty(priceLadderModel.getSectionUpSymbol())) {
                        ladderDTO.setSectionUpSymbol(ConvertorUtil.getName(dicData, BmsConstant.LESS_THAN, String.valueOf(priceLadderModel.getSectionUpSymbol())));
                    }

                    dtos.add(ladderDTO);
                }
            } else {
                dtos.add(dto);
            }

        }
        return dtos;
    }


    private boolean checkCondition(String matchConditions, List<String> codes) {
        String[] conditionTypes = matchConditions.split(";");
        if (ObjectUtil.isNotEmpty(conditionTypes)) {
            List<String> ctTypes = Lists.newArrayList();
            for (int idx = 0; idx < conditionTypes.length; idx++) {
                String[] types = conditionTypes[idx].split(":");
                if (ObjectUtil.isNotEmpty(types)) {
                    ctTypes.add(types[0]);
                }
            }
            if (ObjectUtil.isNotEmpty(ctTypes) && ctTypes.stream().anyMatch(type ->
                    !codes.contains(type))) {
                return false;
            }
        }
        return true;
    }
}