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

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.prolog.common.util.DateUtils;
import com.prolog.common.util.ToolKits;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Order;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.framework.dao.util.PageUtils;
import com.prolog.product.core.framework.entity.UserEntity;
import com.prolog.product.core.framework.util.PlgFxUsrUtils;
import com.prolog.rdc.tms.constant.BussinessConstant;
import com.prolog.rdc.tms.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.constant.SeriaNnumberConstant;
import com.prolog.rdc.tms.dao.mapper.TmsStrategyBusinessCntMapper;
import com.prolog.rdc.tms.dao.mapper.TmsStrategyBusinessMapper;
import com.prolog.rdc.tms.model.dto.basicConfigure.StrategyBusinessCntViewDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.StrategyBusinessMatchingDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.StrategyBusinessPageDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.StrategyBusinessViewDTO;
import com.prolog.rdc.tms.model.entity.LmsTmsZoneModel;
import com.prolog.rdc.tms.model.entity.SysParamConfigModel;
import com.prolog.rdc.tms.model.entity.TmsStrategyBusinessCntModel;
import com.prolog.rdc.tms.model.entity.TmsStrategyBusinessModel;
import com.prolog.rdc.tms.model.vo.basicConfigure.*;
import com.prolog.rdc.tms.service.LmsTmsZoneService;
import com.prolog.rdc.tms.service.SysCodeengineService;
import com.prolog.rdc.tms.service.SysRefdatadService;
import com.prolog.rdc.tms.service.basicConfigure.StrategyBusinessService;
import com.prolog.rdc.tms.service.basicConfigure.SysParamConfigService;
import com.prolog.rdc.tms.util.ConvertorUtil;
import com.prolog.rdc.tms.util.PublicMethods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 策略中心-业务规则策略实现层
 *
 * @author zhangsj
 * @since 2022/7/16 9:45
 */
@Service
@Slf4j
public class StrategyBusinessServiceImpl implements StrategyBusinessService {

    @Autowired
    private TmsStrategyBusinessMapper tmsStrategyBusinessMapper;

    @Autowired
    private TmsStrategyBusinessCntMapper tmsStrategyBusinessCntMapper;

    @Autowired
    private SysRefdatadService sysRefdatadService;

    @Autowired
    private SysCodeengineService sysCodeengineService;

    @Autowired
    private LmsTmsZoneService lmstmszoneservice;

    @Autowired
    private SysParamConfigService sysParamConfigService;

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

        List<String> params = Lists.newArrayList(DataDictionaryConstant.GENERAL_STATUS, // 业务规则策略状态
                DataDictionaryConstant.DELIVERY_METHOD_TYPE, //配送方式
                DataDictionaryConstant.CONSIGNEE_TYPE, // 收货方类型
                DataDictionaryConstant.SHIPPER_TYPE, // 发货方类型
                DataDictionaryConstant.ORDER_TYPE, //订单类型
                DataDictionaryConstant.ORDER_BUSINESS_TYPE, //订单业务类型
                DataDictionaryConstant.TRANSPORT_TYPE, //运输类型(运输模式)
                DataDictionaryConstant.TEMPERATURE_REQUIREMENT, //温度要求
                DataDictionaryConstant.CMP_SYMBOL, //比较符号
                DataDictionaryConstant.PRICE_PCD_MATCH_TYPE, // 价格表匹配方式
                DataDictionaryConstant.PROCESS_ENABLE, //是否处理
                DataDictionaryConstant.LINE_DIRECTION, //配送方向
                DataDictionaryConstant.WHETHER //是否回单
        );
        Map<String, Object> dicData = ConvertorUtil.listDropDownData(sysRefdatadService, params);

        Criteria criteria = Criteria.forClass(TmsStrategyBusinessModel.class);
        Restriction r1 = Restrictions.eq(TmsStrategyBusinessModel::getEnterpriseId, user.getEnterpriseId());
        Restriction r2 = ToolKits.isEmpty(strategyBusinessPageVO.getStatus()) ? null : Restrictions.eq(TmsStrategyBusinessModel::getStatus, strategyBusinessPageVO.getStatus());
        Restriction r3 = ToolKits.isEmpty(strategyBusinessPageVO.getName()) ? null : Restrictions.like(TmsStrategyBusinessModel::getName, "%" + strategyBusinessPageVO.getName() + "%");
        criteria.setRestriction(Restrictions.and(r1, r2, r3));
        criteria.setOrder(Order.newInstance().desc("updatetime"));

        PageUtils.startPage(strategyBusinessPageVO.getPageNum(), strategyBusinessPageVO.getPageSize());
        List<TmsStrategyBusinessModel> TmsStrategyBusinessModels = tmsStrategyBusinessMapper.findByCriteria(criteria);

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

        for (TmsStrategyBusinessModel businessModel : TmsStrategyBusinessModels) {
            StrategyBusinessPageDTO businessPageDTO = new StrategyBusinessPageDTO();
            BeanUtils.copyProperties(businessModel, businessPageDTO);
            // 状态翻译
            businessPageDTO.setStatusName(ConvertorUtil.getName(dicData, DataDictionaryConstant.GENERAL_STATUS, String.valueOf(businessPageDTO.getStatus())));
            StringBuffer rulesBuff = new StringBuffer();
            if (ToolKits.isNotEmpty(businessModel.getDeliveryMethodSelect()) && businessModel.getDeliveryMethodSelect().intValue() == 1) {
                rulesBuff.append("配送方式 " + ConvertorUtil.getName(dicData, DataDictionaryConstant.DELIVERY_METHOD_TYPE, String.valueOf(businessModel.getDeliveryMethodSelect())));
            }
            if (ToolKits.isNotEmpty(businessModel.getApplyPcsSelect()) && businessModel.getApplyPcsSelect().intValue() == 1) {
                rulesBuff.append(" 申请数量 " + ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(businessModel.getApplyPcsEnable())));
            }
            if (ToolKits.isNotEmpty(businessModel.getInventoryCheckSelect()) && businessModel.getInventoryCheckSelect().intValue() == 1) {
                rulesBuff.append(" 库存校验 " + ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(businessModel.getInventoryCheckEnable())));
            }
            if (ToolKits.isNotEmpty(businessModel.getPricePcdMatchTypeSelect()) && businessModel.getPricePcdMatchTypeSelect().intValue() == 1) {
                rulesBuff.append(" 价格表省市区匹配方式 " + ConvertorUtil.getName(dicData, DataDictionaryConstant.PRICE_PCD_MATCH_TYPE, String.valueOf(businessModel.getPricePcdMatchType())));
            }
            if (ToolKits.isNotEmpty(businessModel.getDepartureTemperatureSelect()) && businessModel.getDepartureTemperatureSelect().intValue() == 1) {
                rulesBuff.append(" 输入启运温度 " + ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(businessModel.getDepartureTemperatureEnable())));
            }
            if (ToolKits.isNotEmpty(businessModel.getDeliveryTemperatureSelect()) && businessModel.getDeliveryTemperatureSelect().intValue() == 1) {
                rulesBuff.append(" 输入送达温度 " + ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(businessModel.getDeliveryTemperatureEnable())));
            }
            if (ToolKits.isNotEmpty(businessModel.getRtnOrderPicSelect()) && businessModel.getRtnOrderPicSelect().intValue() == 1) {
                rulesBuff.append(" 回单图片 " + ConvertorUtil.getName(dicData, DataDictionaryConstant.WHETHER, String.valueOf(businessModel.getRtnOrderPicEnable())));
            }
            if (ToolKits.isNotEmpty(businessModel.getRtnOrderPaperSelect()) && businessModel.getRtnOrderPaperSelect().intValue() == 1) {
                rulesBuff.append(" 正本回单 " + ConvertorUtil.getName(dicData, DataDictionaryConstant.WHETHER, String.valueOf(businessModel.getRtnOrderPaperEnable())));
            }
            if (ToolKits.isNotEmpty(businessModel.getRtnOrderDeadlineSelect()) && businessModel.getRtnOrderDeadlineSelect().intValue() == 1) {
                rulesBuff.append(" 回单期限 " + businessModel.getRtnOrderDeadline());
            }
            if (ToolKits.isNotEmpty(businessModel.getDeliveryDirectionSelect()) && businessModel.getDeliveryDirectionSelect().intValue() == 1) {
                rulesBuff.append(" 配送方向 " + ConvertorUtil.getName(dicData, DataDictionaryConstant.LINE_DIRECTION, String.valueOf(businessModel.getDeliveryDirection())));
            }
            if (ToolKits.isNotEmpty(businessModel.getRecordTagSelect()) && businessModel.getRecordTagSelect().intValue() == 1) {
                rulesBuff.append(" 记录标记 " + businessModel.getRecordTagWord());
            }
            if (ToolKits.isNotEmpty(businessModel.getColorTagSelect()) && businessModel.getColorTagSelect().intValue() == 1) {
                rulesBuff.append(" 颜色标记 " + businessModel.getColorTagBgdColor() + " " + businessModel.getColorTagFontColor());
            }
            if (ToolKits.isNotEmpty(businessModel.getTransfiniteCmtDtSelect()) && businessModel.getTransfiniteCmtDtSelect().intValue() == 1) {
                rulesBuff.append(" 输入超限提交日期 " + ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(businessModel.getTransfiniteCmtDtEnable())));
            }
            if (ToolKits.isNotEmpty(businessModel.getTransfiniteDescriptionSelect()) && businessModel.getTransfiniteDescriptionSelect().intValue() == 1) {
                rulesBuff.append(" 输入超限说明 " + ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(businessModel.getTransfiniteDescriptionEnable())));
            }
            if (ToolKits.isNotEmpty(businessModel.getCarrierUploadTransfiniteSelect()) && businessModel.getCarrierUploadTransfiniteSelect().intValue() == 1) {
                rulesBuff.append(" 承运商上传超限证 " + ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(businessModel.getCarrierUploadTransfiniteEnable())));
            }
            if (ToolKits.isNotEmpty(businessModel.getLoadingLocationSelect()) && businessModel.getLoadingLocationSelect().intValue() == 1) {
                rulesBuff.append(" 输入装车地点 " + ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(businessModel.getLoadingLocationEnable())));
            }
            businessPageDTO.setBusinessRules(rulesBuff.toString());

            // 查询对应条件
            Criteria criteriaCondition = Criteria.forClass(TmsStrategyBusinessCntModel.class);
            r1 = Restrictions.eq(TmsStrategyBusinessCntModel::getEnterpriseId, user.getEnterpriseId());
            r2 = Restrictions.eq(TmsStrategyBusinessCntModel::getStrategyId, businessModel.getId());
            criteriaCondition.setRestriction(Restrictions.and(r1, r2));
            List<TmsStrategyBusinessCntModel> tmsStrategySplitConditionModels = tmsStrategyBusinessCntMapper.findByCriteria(criteriaCondition);
            // 不为空拼接条件
            if (ToolKits.isNotEmpty(tmsStrategySplitConditionModels)) {
                StringBuffer conditionsBuff = new StringBuffer();
                List<String> conditionIds = Lists.newArrayList();
                for (TmsStrategyBusinessCntModel conditionModel : tmsStrategySplitConditionModels) {
                    switch (conditionModel.getStrategyConditionType().intValue()) {
                        case 1:
                            // 1配送方式
                            conditionsBuff.append("配送方式 ");
                            for (String conditionValue : conditionModel.getStrategyConditionValue().split(",")) {
                                conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.DELIVERY_METHOD_TYPE, String.valueOf(conditionValue)) + " ");
                            }
                            break;
                        case 2:
                            // 2发货方类型
                            conditionsBuff.append("发货方类型 ");
                            conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.SHIPPER_TYPE, String.valueOf(conditionModel.getStrategyConditionValue())) + " " + conditionModel.getUnitName() + " ");
                            break;
                        case 3:
                            // 3收货方类型
                            conditionsBuff.append("收货方类型 ");
                            conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.CONSIGNEE_TYPE, String.valueOf(conditionModel.getStrategyConditionValue())) + " " + conditionModel.getUnitName() + " ");
                            break;
                        case 4:
                            // 订单类型
                            conditionsBuff.append("订单类型 ");
                            for (String conditionValue : conditionModel.getStrategyConditionValue().split(",")) {
                                conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.ORDER_TYPE, String.valueOf(conditionValue)) + " ");
                            }
                            break;
                        case 5:
                            // 订单业务类型
                            conditionsBuff.append("订单业务类型 ");
                            for (String conditionValue : conditionModel.getStrategyConditionValue().split(",")) {
                                conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.ORDER_BUSINESS_TYPE, String.valueOf(conditionValue)) + " ");
                            }
                            break;
                        case 6:
                            // 运输模式
                            conditionsBuff.append("运输模式 ");
                            for (String conditionValue : conditionModel.getStrategyConditionValue().split(",")) {
                                conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.TRANSPORT_TYPE, String.valueOf(conditionValue)) + " ");
                            }
                            break;
                        case 7:
                            // 温度要求
                            conditionsBuff.append("温度要求 ");
                            for (String conditionValue : conditionModel.getStrategyConditionValue().split(",")) {
                                conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.TEMPERATURE_REQUIREMENT, String.valueOf(conditionValue)) + " ");
                            }
                            break;
                        case 8:
                            // 货主
                            conditionsBuff.append("货主 ");
                            conditionsBuff.append(conditionModel.getUnitName() + " ");
                            break;
                        case 9:
                            // 部门
                            conditionsBuff.append("部门 ");
                            conditionsBuff.append(conditionModel.getUnitName() + " ");
                            break;
                        case 10:
                            // 商品
                            conditionsBuff.append("商品 ");
                            conditionsBuff.append(conditionModel.getUnitName() + " ");
                            break;
                        case 11:
                            // 商品品类
                            conditionsBuff.append("商品品类 ");
                            conditionsBuff.append(conditionModel.getUnitName() + " ");
                            break;
                        case 12:
                            // 商品件数
                            conditionsBuff.append("商品件数 ");
                            conditionsBuff.append(conditionModel.getUnitName() + " ");
                            if (ToolKits.isNotEmpty(conditionModel.getLowerLimitSymbol())) {
                                conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.CMP_SYMBOL, String.valueOf(conditionModel.getLowerLimitSymbol())) + " ");
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getLowerLimitValue())) {
                                conditionsBuff.append(conditionModel.getLowerLimitValue() + " ");
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getUpperLimitSymbol())) {
                                conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.CMP_SYMBOL, String.valueOf(conditionModel.getUpperLimitSymbol())) + " ");
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getUpperLimitValue())) {
                                conditionsBuff.append(conditionModel.getUpperLimitValue() + " ");
                            }
                            break;
                        case 13:
                            // 商品重量
                            conditionsBuff.append("商品重量 ");
                            conditionsBuff.append(conditionModel.getUnitName() + " ");
                            if (ToolKits.isNotEmpty(conditionModel.getLowerLimitSymbol())) {
                                conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.CMP_SYMBOL, String.valueOf(conditionModel.getLowerLimitSymbol())) + " ");
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getLowerLimitValue())) {
                                conditionsBuff.append(conditionModel.getLowerLimitValue() + " ");
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getUpperLimitSymbol())) {
                                conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.CMP_SYMBOL, String.valueOf(conditionModel.getUpperLimitSymbol())) + " ");
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getUpperLimitValue())) {
                                conditionsBuff.append(conditionModel.getUpperLimitValue() + " ");
                            }
                            break;
                        case 14:
                            // 商品总件数
                            conditionsBuff.append("商品总件数 ");
                            if (ToolKits.isNotEmpty(conditionModel.getLowerLimitSymbol())) {
                                conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.CMP_SYMBOL, String.valueOf(conditionModel.getLowerLimitSymbol())) + " ");
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getLowerLimitValue())) {
                                conditionsBuff.append(conditionModel.getLowerLimitValue() + " ");
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getUpperLimitSymbol())) {
                                conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.CMP_SYMBOL, String.valueOf(conditionModel.getUpperLimitSymbol())) + " ");
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getUpperLimitValue())) {
                                conditionsBuff.append(conditionModel.getUpperLimitValue() + " ");
                            }
                            break;
                        case 15:
                            // 商品总重量
                            conditionsBuff.append("商品总重量 ");
                            if (ToolKits.isNotEmpty(conditionModel.getLowerLimitSymbol())) {
                                conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.CMP_SYMBOL, String.valueOf(conditionModel.getLowerLimitSymbol())) + " ");
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getLowerLimitValue())) {
                                conditionsBuff.append(conditionModel.getLowerLimitValue() + " ");
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getUpperLimitSymbol())) {
                                conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.CMP_SYMBOL, String.valueOf(conditionModel.getUpperLimitSymbol())) + " ");
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getUpperLimitValue())) {
                                conditionsBuff.append(conditionModel.getUpperLimitValue() + " ");
                            }
                            break;
                        case 16:
                            // 发货方省市区
                            conditionsBuff.append("发货方省市区 ");
                            if (ToolKits.isNotEmpty(conditionModel.getShipperProvince())) {
                                String zoneName = getZoneNames(conditionModel.getShipperProvince());
                                if (ToolKits.isNotEmpty(zoneName)) {
                                    conditionsBuff.append(zoneName + " ");
                                }
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getShipperCity())) {
                                String zoneName = getZoneNames(conditionModel.getShipperCity());
                                if (ToolKits.isNotEmpty(zoneName)) {
                                    conditionsBuff.append(zoneName + " ");
                                }
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getShipperDistrict())) {
                                String zoneName = getZoneNames(conditionModel.getShipperDistrict());
                                if (ToolKits.isNotEmpty(zoneName)) {
                                    conditionsBuff.append(zoneName + " ");
                                }
                            }

                            break;
                        case 17:
                            // 收货方省市区
                            conditionsBuff.append("收货方省市区 ");
                            if (ToolKits.isNotEmpty(conditionModel.getConsigneeProvince())) {
                                String zoneName = getZoneNames(conditionModel.getConsigneeProvince());
                                if (ToolKits.isNotEmpty(zoneName)) {
                                    conditionsBuff.append(zoneName + " ");
                                }
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getConsigneeCity())) {
                                String zoneName = getZoneNames(conditionModel.getConsigneeCity());
                                if (ToolKits.isNotEmpty(zoneName)) {
                                    conditionsBuff.append(zoneName + " ");
                                }
                            }
                            if (ToolKits.isNotEmpty(conditionModel.getConsigneeDistrict())) {
                                String zoneName = getZoneNames(conditionModel.getConsigneeDistrict());
                                if (ToolKits.isNotEmpty(zoneName)) {
                                    conditionsBuff.append(zoneName + " ");
                                }
                            }
                            break;
                        case 18:
                            conditionsBuff.append("商品超限 ");
                            conditionsBuff.append(ConvertorUtil.getName(dicData, DataDictionaryConstant.WHETHER, String.valueOf(conditionModel.getStrategyConditionValue())) + " ");
                            break;
                    }
                    conditionIds.add(String.valueOf(conditionModel.getId()));
                }
                businessPageDTO.setConditionName(conditionsBuff.toString());
            }
            strategyBusinessPageDTOS.add(businessPageDTO);
        }
        // 分页重组
        Page<StrategyBusinessPageDTO> page = PageUtils.getPage(strategyBusinessPageDTOS);
        if (TmsStrategyBusinessModels instanceof com.github.pagehelper.Page) {
            com.github.pagehelper.Page<TmsStrategyBusinessModel> p0 = (com.github.pagehelper.Page<TmsStrategyBusinessModel>) TmsStrategyBusinessModels;
            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;
    }

    public String getZoneNames(String zoneId) {
        String name = "";
        if (ToolKits.isNotEmpty(zoneId)) {
            List<String> zoneNames = Lists.newArrayList();
            for (String provinceId : zoneId.split(",")) {
                LmsTmsZoneModel provinceModel = lmstmszoneservice.getZoneById(provinceId);
                if (ToolKits.isNotEmpty(provinceModel)) {
                    zoneNames.add(provinceModel.getZname());
                }
            }
            name = zoneNames.stream().collect(Collectors.joining(" "));
        }
        return name;
    }

    /**
     * 查看
     *
     * @param strategyBusinessViewVO
     * @return
     */
    @Override
    public StrategyBusinessViewDTO viewData(StrategyBusinessViewVO strategyBusinessViewVO) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");

        List<String> params = Lists.newArrayList(DataDictionaryConstant.BUSINESS_CONDITION_TYPE, // 业务规则策略条件类型
                DataDictionaryConstant.PROCESS_ENABLE, // 是否处理
                DataDictionaryConstant.CMP_SYMBOL, // 比较符号
                DataDictionaryConstant.DELIVERY_METHOD_TYPE, //配送方式
                DataDictionaryConstant.LINE_DIRECTION, //配送方向
                DataDictionaryConstant.CONSIGNEE_TYPE, // 收货方类型
                DataDictionaryConstant.SHIPPER_TYPE, // 发货方类型
                DataDictionaryConstant.PRICE_PCD_MATCH_TYPE, // 价格表匹配方式
                DataDictionaryConstant.ORDER_TYPE, //订单类型
                DataDictionaryConstant.ORDER_BUSINESS_TYPE, //订单业务类型
                DataDictionaryConstant.TRANSPORT_TYPE, //运输类型(运输模式)
                DataDictionaryConstant.TEMPERATURE_REQUIREMENT, //温度要求
                DataDictionaryConstant.WHETHER //是否回单
        );
        Map<String, Object> dicData = ConvertorUtil.listDropDownData(sysRefdatadService, params);

        TmsStrategyBusinessModel strategyBusinessModel = tmsStrategyBusinessMapper.findById(strategyBusinessViewVO.getId(), TmsStrategyBusinessModel.class);
        ToolKits.isParamNull(strategyBusinessModel, "策略ID[" + strategyBusinessViewVO.getId() + "]有误,查询为空!");

        // 返回数据
        StrategyBusinessViewDTO strategyBusinessViewDTO = new StrategyBusinessViewDTO();
        BeanUtils.copyProperties(strategyBusinessModel, strategyBusinessViewDTO);
        if (ToolKits.isNotEmpty(strategyBusinessModel.getDeliveryMethodType())) {
            strategyBusinessViewDTO.setDeliveryMethodTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.DELIVERY_METHOD_TYPE, String.valueOf(strategyBusinessModel.getDeliveryMethodType())));
        }
        if (ToolKits.isNotEmpty(strategyBusinessModel.getApplyPcsEnable())) {
            strategyBusinessViewDTO.setApplyPcsEnableName(ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(strategyBusinessModel.getApplyPcsEnable())));
        }
        if (ToolKits.isNotEmpty(strategyBusinessModel.getInventoryCheckEnable())) {
            strategyBusinessViewDTO.setInventoryCheckEnableName(ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(strategyBusinessModel.getInventoryCheckEnable())));
        }
        if (ToolKits.isNotEmpty(strategyBusinessModel.getDeliveryTemperatureEnable())) {
            strategyBusinessViewDTO.setDeliveryTemperatureEnableName(ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(strategyBusinessModel.getDeliveryTemperatureEnable())));
        }
        if (ToolKits.isNotEmpty(strategyBusinessModel.getDepartureTemperatureEnable())) {
            strategyBusinessViewDTO.setDepartureTemperatureEnableName(ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(strategyBusinessModel.getDepartureTemperatureEnable())));
        }
        // 正本回单
        if (ToolKits.isNotEmpty(strategyBusinessModel.getRtnOrderPaperEnable())) {
            strategyBusinessViewDTO.setRtnOrderPaperEnableName(ConvertorUtil.getName(dicData, DataDictionaryConstant.WHETHER, String.valueOf(strategyBusinessModel.getRtnOrderPaperEnable())));
        }
        // 图片回单
        if (ToolKits.isNotEmpty(strategyBusinessModel.getRtnOrderPicEnable())) {
            strategyBusinessViewDTO.setRtnOrderPicEnableName(ConvertorUtil.getName(dicData, DataDictionaryConstant.WHETHER, String.valueOf(strategyBusinessModel.getRtnOrderPicEnable())));
        }
        // 配送方向
        if (ToolKits.isNotEmpty(strategyBusinessModel.getDeliveryDirection())) {
            strategyBusinessViewDTO.setDeliveryDirectionName(ConvertorUtil.getName(dicData, DataDictionaryConstant.LINE_DIRECTION, String.valueOf(strategyBusinessModel.getDeliveryDirection())));
        }
        // 价格表
        if (ToolKits.isNotEmpty(strategyBusinessModel.getPricePcdMatchType())) {
            strategyBusinessViewDTO.setPricePcdMatchTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.PRICE_PCD_MATCH_TYPE, String.valueOf(strategyBusinessModel.getPricePcdMatchType())));
        }

        if (ToolKits.isNotEmpty(strategyBusinessModel.getTransfiniteCmtDtEnable())) {
            strategyBusinessViewDTO.setTransfiniteCmtDtEnableName(ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(strategyBusinessModel.getTransfiniteCmtDtEnable())));
        }
        if (ToolKits.isNotEmpty(strategyBusinessModel.getTransfiniteDescriptionEnable())) {
            strategyBusinessViewDTO.setTransfiniteDescriptionEnableName(ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(strategyBusinessModel.getTransfiniteDescriptionEnable())));
        }
        if (ToolKits.isNotEmpty(strategyBusinessModel.getCarrierUploadTransfiniteEnable())) {
            strategyBusinessViewDTO.setCarrierUploadTransfiniteEnableName(ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(strategyBusinessModel.getCarrierUploadTransfiniteEnable())));
        }
        if (ToolKits.isNotEmpty(strategyBusinessModel.getLoadingLocationEnable())) {
            strategyBusinessViewDTO.setLoadingLocationEnableName(ConvertorUtil.getName(dicData, DataDictionaryConstant.PROCESS_ENABLE, String.valueOf(strategyBusinessModel.getLoadingLocationEnable())));
        }
        // 查询对应条件
        Criteria criteria = Criteria.forClass(TmsStrategyBusinessCntModel.class);
        Restriction r1 = Restrictions.eq(TmsStrategyBusinessCntModel::getStrategyId, strategyBusinessModel.getId());
        criteria.setRestriction(r1);
        List<TmsStrategyBusinessCntModel> strategyBusinessCntModels = tmsStrategyBusinessCntMapper.findByCriteria(criteria);

        // 条件集合
        List<StrategyBusinessCntViewDTO> strategyBusinessCntViewDTOS = Lists.newArrayList();
        if (ToolKits.isNotEmpty(strategyBusinessCntModels)) {
            for (TmsStrategyBusinessCntModel conditionModel : strategyBusinessCntModels) {
                StrategyBusinessCntViewDTO strategySplitConditionViewDTO = new StrategyBusinessCntViewDTO();
                BeanUtils.copyProperties(conditionModel, strategySplitConditionViewDTO);

                strategySplitConditionViewDTO.setStrategyConditionTypeName(ConvertorUtil.getName(dicData, DataDictionaryConstant.BUSINESS_CONDITION_TYPE, String.valueOf(conditionModel.getStrategyConditionType())));
                strategySplitConditionViewDTO.setLowerLimitSymbolName(ConvertorUtil.getName(dicData, DataDictionaryConstant.CMP_SYMBOL, String.valueOf(conditionModel.getLowerLimitSymbol())));
                strategySplitConditionViewDTO.setUpperLimitSymbolName(ConvertorUtil.getName(dicData, DataDictionaryConstant.CMP_SYMBOL, String.valueOf(conditionModel.getUpperLimitSymbol())));
                List<String> conditionValues = Lists.newArrayList();
                switch (conditionModel.getStrategyConditionType().intValue()) {
                    case 1:
                        // 1配送方式
                        for (String conditionValue : conditionModel.getStrategyConditionValue().split(",")) {
                            conditionValues.add(ConvertorUtil.getName(dicData, DataDictionaryConstant.DELIVERY_METHOD_TYPE, String.valueOf(conditionValue)));
                        }
                        break;
                    case 2:
                        // 2发货方类型
                        conditionValues.add(ConvertorUtil.getName(dicData, DataDictionaryConstant.SHIPPER_TYPE, String.valueOf(conditionModel.getStrategyConditionValue())));
                        break;
                    case 3:
                        // 3收货方类型
                        conditionValues.add(ConvertorUtil.getName(dicData, DataDictionaryConstant.CONSIGNEE_TYPE, String.valueOf(conditionModel.getStrategyConditionValue())));
                        break;
                    case 4:
                        // 订单类型
                        for (String conditionValue : conditionModel.getStrategyConditionValue().split(",")) {
                            conditionValues.add(ConvertorUtil.getName(dicData, DataDictionaryConstant.ORDER_TYPE, String.valueOf(conditionValue)));
                        }
                        break;
                    case 5:
                        // 订单业务类型
                        for (String conditionValue : conditionModel.getStrategyConditionValue().split(",")) {
                            conditionValues.add(ConvertorUtil.getName(dicData, DataDictionaryConstant.ORDER_BUSINESS_TYPE, String.valueOf(conditionValue)));
                        }
                        break;
                    case 6:
                        // 运输模式
                        for (String conditionValue : conditionModel.getStrategyConditionValue().split(",")) {
                            conditionValues.add(ConvertorUtil.getName(dicData, DataDictionaryConstant.TRANSPORT_TYPE, String.valueOf(conditionValue)));
                        }
                        break;
                    case 7:
                        // 温度要求
                        for (String conditionValue : conditionModel.getStrategyConditionValue().split(",")) {
                            conditionValues.add(ConvertorUtil.getName(dicData, DataDictionaryConstant.TEMPERATURE_REQUIREMENT, String.valueOf(conditionValue)));
                        }
                        break;
                }
                if (ToolKits.isNotEmpty(conditionValues)) {
                    strategySplitConditionViewDTO.setStrategyConditionValueName(conditionValues.stream().collect(Collectors.joining(",")));
                }
                strategyBusinessCntViewDTOS.add(strategySplitConditionViewDTO);
            }

        }
        strategyBusinessViewDTO.setStrategyBusinessCntViewDTOS(strategyBusinessCntViewDTOS);
        return strategyBusinessViewDTO;
    }

    /**
     * 新增
     *
     * @param strategyBusinessSaveVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveData(StrategyBusinessSaveVO strategyBusinessSaveVO) {
        ToolKits.isParamNull(strategyBusinessSaveVO, "业务规则策略保存请求不为空");
        ToolKits.isParamNull(strategyBusinessSaveVO.getName(), "策略名称不为空");
        ToolKits.isParamNull(strategyBusinessSaveVO.getPriorityLevel(), "策略优先级不为空");
        ToolKits.isParamNull(strategyBusinessSaveVO.getStrategyBusinessCntSaveVOS(), "业务规则策略条件不为空");

        if (strategyBusinessSaveVO.getDeliveryMethodSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getApplyPcsSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getInventoryCheckSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getDeliveryTemperatureSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getDepartureTemperatureSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getRtnOrderPicSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getRtnOrderPaperSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getRtnOrderDeadlineSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getPricePcdMatchTypeSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getDeliveryDirectionSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getRecordTagSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getColorTagSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getTransfiniteCmtDtSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getTransfiniteDescriptionSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getCarrierUploadTransfiniteSelect().intValue() == 0 &&
                strategyBusinessSaveVO.getLoadingLocationSelect().intValue() == 0) {
            throw new PrologException("业务规则必须选择一个");
        }

        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        // 当前时间
        Date date = DateUtils.nowDate();

        // 判定是否有重复条件流程
        Criteria criteria = Criteria.forClass(TmsStrategyBusinessModel.class);
        Restriction r1 = Restrictions.eq(TmsStrategyBusinessModel::getName, strategyBusinessSaveVO.getName());
        Restriction r2 = Restrictions.eq(TmsStrategyBusinessModel::getEnterpriseId, user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        List<TmsStrategyBusinessModel> strategyBusinessModels = tmsStrategyBusinessMapper.findByCriteria(criteria);
        if (ToolKits.isNotEmpty(strategyBusinessModels)) {
            throw new RuntimeException("策略名称【" + strategyBusinessSaveVO.getName() + "】已存在");
        }

        r1 = Restrictions.eq(TmsStrategyBusinessModel::getPriorityLevel, strategyBusinessSaveVO.getPriorityLevel());
        r2 = Restrictions.eq(TmsStrategyBusinessModel::getEnterpriseId, user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        List<TmsStrategyBusinessModel> priorityStrategyBusinessModels = tmsStrategyBusinessMapper.findByCriteria(criteria);
        if (ToolKits.isNotEmpty(priorityStrategyBusinessModels)) {
            throw new RuntimeException("优先级为【" + strategyBusinessSaveVO.getPriorityLevel() + "】的策略已存在,请重新设定优先级");
        }

        // 保存策略表
        String id = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_STRATEGY_BUSINESS_ID, "L");
        ToolKits.isParamNull(id, "获取业务规则策略表ID失败！");

        TmsStrategyBusinessModel strategyBusinessModel = new TmsStrategyBusinessModel();
        BeanUtils.copyProperties(strategyBusinessSaveVO, strategyBusinessModel);

        strategyBusinessModel.setId(Long.valueOf(id));
        strategyBusinessModel.setStatus(DataDictionaryConstant.GENERAL_STATUS_ENABLE);

        strategyBusinessModel.setEnterpriseId(user.getEnterpriseId());
        strategyBusinessModel.setEnterpriseName(user.getEnterpriseName());

        strategyBusinessModel.setCreatetime(date);
        strategyBusinessModel.setCreateperson(user.getNickname());
        strategyBusinessModel.setUpdatetime(date);
        strategyBusinessModel.setUpdateperson(user.getNickname());

        tmsStrategyBusinessMapper.save(strategyBusinessModel);

        // 保存策略条件表
        for (StrategyBusinessCntSaveVO businessCntSaveVO : strategyBusinessSaveVO.getStrategyBusinessCntSaveVOS()) {
            String conditionId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_STRATEGY_BUSINESS_CNT_ID, "L");
            ToolKits.isParamNull(id, "获取业务规则策略条件表ID失败！");

            TmsStrategyBusinessCntModel strategyBusinessCntModel = new TmsStrategyBusinessCntModel();
            BeanUtils.copyProperties(businessCntSaveVO, strategyBusinessCntModel);

            strategyBusinessCntModel.setId(Long.valueOf(conditionId));
            strategyBusinessCntModel.setStrategyId(Long.valueOf(id));

            strategyBusinessCntModel.setEnterpriseId(user.getEnterpriseId());
            strategyBusinessCntModel.setEnterpriseName(user.getEnterpriseName());

            strategyBusinessCntModel.setCreatetime(date);
            strategyBusinessCntModel.setCreateperson(user.getNickname());

            tmsStrategyBusinessCntMapper.save(strategyBusinessCntModel);
        }
    }

    /**
     * 修改
     *
     * @param strategyBusinessUpdateVO
     */
    @Override

    public void updateData(StrategyBusinessUpdateVO strategyBusinessUpdateVO) {
        ToolKits.isParamNull(strategyBusinessUpdateVO, "业务规则策略修改请求不为空");
        ToolKits.isParamNull(strategyBusinessUpdateVO.getPriorityLevel(), "策略优先级不为空");
        ToolKits.isParamNull(strategyBusinessUpdateVO.getStrategyBusinessCntUpdateVOS(), "业务规则策略条件不为空");

        if (strategyBusinessUpdateVO.getDeliveryMethodSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getApplyPcsSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getInventoryCheckSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getDeliveryTemperatureSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getDepartureTemperatureSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getRtnOrderPicSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getPricePcdMatchTypeSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getRtnOrderPaperSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getRtnOrderDeadlineSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getDeliveryDirectionSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getRecordTagSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getColorTagSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getTransfiniteCmtDtSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getTransfiniteDescriptionSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getCarrierUploadTransfiniteSelect().intValue() == 0 &&
                strategyBusinessUpdateVO.getLoadingLocationSelect().intValue() == 0) {
            throw new PrologException("业务规则必须选择一个");
        }

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

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

        TmsStrategyBusinessModel TmsStrategyBusinessModel = tmsStrategyBusinessMapper.findById(strategyBusinessUpdateVO.getId(), TmsStrategyBusinessModel.class);
        ToolKits.isParamNull(TmsStrategyBusinessModel, "策略ID【" + strategyBusinessUpdateVO.getId() + "】有误,查询为空!");

        Criteria criteria = Criteria.forClass(TmsStrategyBusinessModel.class);
        Restriction r1 = Restrictions.eq(TmsStrategyBusinessModel::getPriorityLevel, strategyBusinessUpdateVO.getPriorityLevel());
        Restriction r2 = Restrictions.eq(TmsStrategyBusinessModel::getEnterpriseId, user.getEnterpriseId());
        Restriction r3 = Restrictions.ne(TmsStrategyBusinessModel::getId, TmsStrategyBusinessModel.getId());
        criteria.setRestriction(Restrictions.and(r1, r2, r3));
        List<TmsStrategyBusinessModel> priorityStrategyBusinessModels = tmsStrategyBusinessMapper.findByCriteria(criteria);
        if (ToolKits.isNotEmpty(priorityStrategyBusinessModels)) {
            throw new RuntimeException("优先级为【" + strategyBusinessUpdateVO.getPriorityLevel() + "】的策略已存在,请重新设定优先级");
        }

        BeanUtils.copyProperties(strategyBusinessUpdateVO, TmsStrategyBusinessModel);

        TmsStrategyBusinessModel.setUpdatetime(date);
        TmsStrategyBusinessModel.setUpdateperson(user.getNickname());

        // 修改策略表
        tmsStrategyBusinessMapper.update(TmsStrategyBusinessModel);

        // 删除条件
        Criteria conditionCriteria = Criteria.forClass(TmsStrategyBusinessCntModel.class);
        r2 = Restrictions.eq(TmsStrategyBusinessCntModel::getStrategyId, strategyBusinessUpdateVO.getId());
        conditionCriteria.setRestriction(Restrictions.and(r2));
        tmsStrategyBusinessCntMapper.deleteByCriteria(conditionCriteria);
        // 修改策略条件表
        for (StrategyBusinessCntUpdateVO businessCntUpdateVO : strategyBusinessUpdateVO.getStrategyBusinessCntUpdateVOS()) {
            String conditionId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_STRATEGY_BUSINESS_CNT_ID, "L");
            ToolKits.isParamNull(conditionId, "获取业务规则策略条件表ID失败！");
            TmsStrategyBusinessCntModel businessCntModel = new TmsStrategyBusinessCntModel();
            BeanUtils.copyProperties(businessCntUpdateVO, businessCntModel);

            businessCntModel.setId(Long.valueOf(conditionId));
            businessCntModel.setStrategyId(TmsStrategyBusinessModel.getId());

            businessCntModel.setEnterpriseId(user.getEnterpriseId());
            businessCntModel.setEnterpriseName(user.getEnterpriseName());

            businessCntModel.setCreatetime(date);
            businessCntModel.setCreateperson(user.getNickname());
            businessCntModel.setUpdatetime(date);
            businessCntModel.setUpdateperson(user.getNickname());
            tmsStrategyBusinessCntMapper.save(businessCntModel);
        }
    }

    /**
     * 停用
     *
     * @param ids
     */
    @Override
    public void disableData(List<Long> ids) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");

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

        // 封装修改参数
        Map<String, Object> mapUpdate = Maps.newHashMap();
        mapUpdate.put("status", DataDictionaryConstant.GENERAL_STATUS_STOP);
        mapUpdate.put("updateperson", user.getNickname());
        mapUpdate.put("updatetime", date);

        Criteria criteria = Criteria.forClass(TmsStrategyBusinessModel.class);
        Restriction r1 = Restrictions.in(TmsStrategyBusinessModel::getId, ids.stream().toArray());
        Restriction r2 = Restrictions.eq(TmsStrategyBusinessModel::getEnterpriseId, user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));

        tmsStrategyBusinessMapper.updateMapByCriteria(mapUpdate, criteria);
    }

    /**
     * 启用
     *
     * @param ids
     */
    @Override
    public void activeData(List<Long> ids) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "没有操作权限！");
        // 当前时间
        Date date = DateUtils.nowDate();
        // 封装修改参数
        Map<String, Object> mapUpdate = Maps.newHashMap();
        mapUpdate.put("status", DataDictionaryConstant.GENERAL_STATUS_ENABLE);
        mapUpdate.put("updateperson", user.getNickname());
        mapUpdate.put("updatetime", date);

        Criteria criteria = Criteria.forClass(TmsStrategyBusinessModel.class);
        Restriction r1 = Restrictions.in(TmsStrategyBusinessModel::getId, ids.stream().toArray());
        Restriction r2 = Restrictions.eq(TmsStrategyBusinessModel::getEnterpriseId, user.getEnterpriseId());
        criteria.setRestriction(Restrictions.and(r1, r2));
        tmsStrategyBusinessMapper.updateMapByCriteria(mapUpdate, criteria);
    }

    /**
     * 匹配
     *
     * @param businessMatchingVO
     * @return
     */
    @Override
    public List<StrategyBusinessMatchingDTO> matchingData(StrategyBusinessMatchingVO businessMatchingVO) {
        log.info("运单匹配业务规则开始:" + JSON.toJSONString(businessMatchingVO));
        ToolKits.isParamNull(businessMatchingVO, "运单匹配业务规则策略请求不为空");
        UserEntity user;
        if (ObjectUtil.isNotNull(businessMatchingVO.getUser())) {
            user = businessMatchingVO.getUser();
        } else {
            user = PlgFxUsrUtils.getUserEntity();
        }
        ToolKits.isParamNull(user, "当前人员没有操作权限");

        List<StrategyBusinessMatchingDTO> list = Lists.newArrayList();

        Criteria carrierCriteria = Criteria.forClass(TmsStrategyBusinessModel.class);
        Restriction r1 = Restrictions.eq(TmsStrategyBusinessModel::getEnterpriseId, user.getEnterpriseId());
        Restriction r2 = Restrictions.eq(TmsStrategyBusinessModel::getStatus, DataDictionaryConstant.GENERAL_STATUS_ENABLE);
        carrierCriteria.setRestriction(Restrictions.and(r1, r2));
        carrierCriteria.setOrder(Order.newInstance().asc(new String[]{"priorityLevel"}));
        List<TmsStrategyBusinessModel> TmsStrategyBusinessModels = tmsStrategyBusinessMapper.findByCriteria(carrierCriteria);

        if (ToolKits.isEmpty(TmsStrategyBusinessModels)) {
            log.info("运单匹配业务规则结束:" + JSON.toJSONString(list));
            return list;
        }
        // 运单匹配条件集合
        Map<Integer, String> conditionMap = Maps.newHashMap();
        // 配送方式
        if (ToolKits.isNotEmpty(businessMatchingVO.getDeliveryMethodType())) {
            conditionMap.put(DataDictionaryConstant.STRATEGY_CONDITION_TYPE_DELIVERY, DataDictionaryConstant.STRATEGY_CONDITION_TYPE_DELIVERY + "_" + String.valueOf(businessMatchingVO.getDeliveryMethodType()));
        }
        // 订单类型
        if (ToolKits.isNotEmpty(businessMatchingVO.getOrderType())) {
            conditionMap.put(DataDictionaryConstant.STRATEGY_CONDITION_TYPE_ORDER, DataDictionaryConstant.STRATEGY_CONDITION_TYPE_ORDER + "_" + String.valueOf(businessMatchingVO.getOrderType()));
        }
        // 订单业务类型
        if (ToolKits.isNotEmpty(businessMatchingVO.getOrderBusinessType())) {
            conditionMap.put(DataDictionaryConstant.STRATEGY_CONDITION_TYPE_ORDER_BUSINESS, DataDictionaryConstant.STRATEGY_CONDITION_TYPE_ORDER_BUSINESS + "_" + String.valueOf(businessMatchingVO.getOrderBusinessType()));
        }
        // 运输模式
        if (ToolKits.isNotEmpty(businessMatchingVO.getTransportType())) {
            conditionMap.put(DataDictionaryConstant.STRATEGY_CONDITION_TYPE_TRANSPORT, DataDictionaryConstant.STRATEGY_CONDITION_TYPE_TRANSPORT + "_" + String.valueOf(businessMatchingVO.getTransportType()));
        }
        // 温度要求
        if (ToolKits.isNotEmpty(businessMatchingVO.getTemperatureRequirement())) {
            conditionMap.put(DataDictionaryConstant.STRATEGY_CONDITION_TYPE_TEMPERATURE, DataDictionaryConstant.STRATEGY_CONDITION_TYPE_TEMPERATURE + "_" + String.valueOf(businessMatchingVO.getTemperatureRequirement()));
        }
        // 货主ID
        if (ToolKits.isNotEmpty(businessMatchingVO.getCargoOwnerId())) {
            conditionMap.put(DataDictionaryConstant.STRATEGY_CONDITION_TYPE_OWNER, String.valueOf(businessMatchingVO.getCargoOwnerId()));
        }

        // 部门ID
        if (ToolKits.isNotEmpty(businessMatchingVO.getDepartmentId())) {
            conditionMap.put(DataDictionaryConstant.STRATEGY_CONDITION_TYPE_DEPARTMENT, String.valueOf(businessMatchingVO.getDepartmentId()));
        }

        // 发货方类型
        if (ToolKits.isNotEmpty(businessMatchingVO.getShipperType())) {
            conditionMap.put(DataDictionaryConstant.STRATEGY_CONDITION_TYPE_SHIPPER, String.valueOf(businessMatchingVO.getShipperType()) + "," + String.valueOf(businessMatchingVO.getShipperUnitId()));
        }
        // 收货方类型
        if (ToolKits.isNotEmpty(businessMatchingVO.getConsigneeType())) {
            conditionMap.put(DataDictionaryConstant.STRATEGY_CONDITION_TYPE_CONSIGNEE, String.valueOf(businessMatchingVO.getConsigneeType()) + "," + String.valueOf(businessMatchingVO.getConsigneeUnitId()));
        }
        List<StrategyBusinessItemVO> businessItems = businessMatchingVO.getBusinessItemVOS();

        String goodsTransfiniteEnabled = null;
        try {
            SysParamConfigModel sysParamConfig = sysParamConfigService.getValue(BussinessConstant.GOODS_TRANSFINITE_ENABLED);
            goodsTransfiniteEnabled = sysParamConfig.getValue();
        } catch (Exception e) {
            throw new PrologException("获取是否启用商品超限系统参数失败");
        }

        for (TmsStrategyBusinessModel tmsStrategyBusinessModel : TmsStrategyBusinessModels) {
            StrategyBusinessMatchingDTO businessMatchingDTO = new StrategyBusinessMatchingDTO();
            BeanUtils.copyProperties(tmsStrategyBusinessModel, businessMatchingDTO);

            // 满足条件
            Criteria carrierCtCriteria = Criteria.forClass(TmsStrategyBusinessCntModel.class);
            Restriction r3 = Restrictions.eq(TmsStrategyBusinessCntModel::getStrategyId, tmsStrategyBusinessModel.getId());
            Restriction r4 = Restrictions.eq(TmsStrategyBusinessCntModel::getEnterpriseId, user.getEnterpriseId());
            carrierCtCriteria.setRestriction(Restrictions.and(r3, r4));
            carrierCtCriteria.setOrder(Order.newInstance().asc(new String[]{"strategyConditionType"}));
            List<TmsStrategyBusinessCntModel> tmsStrategySplitConditionModels = tmsStrategyBusinessCntMapper.findByCriteria(carrierCtCriteria);

            if (ToolKits.isEmpty(tmsStrategySplitConditionModels)) {
                continue;
            }
            // 判定满足条件
            int fitCnt = 0;
            for (TmsStrategyBusinessCntModel conditionModel : tmsStrategySplitConditionModels) {
                switch (conditionModel.getStrategyConditionType().intValue()) {
                    case 2: // 发货方类型
                        String shipperStr = conditionMap.get(DataDictionaryConstant.STRATEGY_CONDITION_TYPE_SHIPPER);
                        if (ToolKits.isNotEmpty(shipperStr)) {
                            String[] shipper = shipperStr.split(",");
                            if (conditionModel.getStrategyConditionValue().contains(shipper[0]) && conditionModel.getUnitId().contains(shipper[1])) {
                                fitCnt++;
                            }
                        }
                        break;
                    case 3: // 收货方类型
                        String consigneeStr = conditionMap.get(DataDictionaryConstant.STRATEGY_CONDITION_TYPE_CONSIGNEE);
                        if (ToolKits.isNotEmpty(consigneeStr)) {
                            String[] consignee = consigneeStr.split(",");
                            if (conditionModel.getStrategyConditionValue().contains(consignee[0]) && conditionModel.getUnitId().contains(consignee[1])) {
                                fitCnt++;
                            }
                        }
                        break;
                    case 8: // 货主
                        String owner = conditionMap.get(DataDictionaryConstant.STRATEGY_CONDITION_TYPE_OWNER);
                        if (ToolKits.isNotEmpty(owner)) {
                            if (conditionModel.getUnitId().contains(owner)) {
                                fitCnt++;
                            }
                        }
                        break;
                    case 9: // 部门
                        String department = conditionMap.get(DataDictionaryConstant.STRATEGY_CONDITION_TYPE_DEPARTMENT);
                        if (ToolKits.isNotEmpty(department)) {
                            if (conditionModel.getUnitId().contains(department)) {
                                fitCnt++;
                            }
                        }
                        break;
                    case 10: // 商品
                        if (ToolKits.isNotEmpty(businessItems)) {
                            long cnt = businessItems.stream().filter(itemId -> conditionModel.getUnitId().contains(String.valueOf(itemId.getItemId()))).count();
                            if (cnt > 0) {
                                fitCnt++;
                            }
                        }
                        break;
                    case 11: // 商品品类
                        if (ToolKits.isNotEmpty(businessItems)) {
                            long cnt = businessItems.stream().filter(itemId -> conditionModel.getUnitId().contains(String.valueOf(itemId.getItemCategoryId()))).count();
                            if (cnt > 0) {
                                fitCnt++;
                            }
                        }
                        break;
                    case 12: //商品件数
                        if (ToolKits.isNotEmpty(businessItems)) {
                            List<StrategyBusinessItemVO> itemCountList = businessItems.stream().filter(itemId -> conditionModel.getUnitId().contains(String.valueOf(itemId.getItemId()))).collect(Collectors.toList());
                            if (ToolKits.isEmpty(itemCountList)) {
                                break;
                            }
                            for (StrategyBusinessItemVO itemVO : itemCountList) {
                                if (ToolKits.isNotEmpty(conditionModel.getLowerLimitValue()) && ToolKits.isNotEmpty(conditionModel.getUpperLimitValue())) {
                                    if (NumberUtil.isGreater(itemVO.getPcs(), conditionModel.getLowerLimitValue()) &&
                                            NumberUtil.isLess(itemVO.getPcs(), conditionModel.getUpperLimitValue())) {
                                        fitCnt++;
                                        break;
                                    }
                                } else if (ToolKits.isNotEmpty(conditionModel.getLowerLimitValue())) {
                                    if (conditionModel.getLowerLimitSymbol().equals(DataDictionaryConstant.CMP_SYMBOL_GT)) {
                                        if (NumberUtil.isGreater(itemVO.getPcs(), conditionModel.getLowerLimitValue())) {
                                            fitCnt++;
                                            break;
                                        }
                                    } else {
                                        if (NumberUtil.isLess(itemVO.getPcs(), conditionModel.getUpperLimitValue())) {
                                            fitCnt++;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    case 13: // 商品重量
                        if (ToolKits.isNotEmpty(businessItems)) {
                            List<StrategyBusinessItemVO> itemWeightList = businessItems.stream().filter(itemId -> conditionModel.getUnitId().contains(String.valueOf(itemId.getItemId()))).collect(Collectors.toList());
                            if (ToolKits.isEmpty(itemWeightList)) {
                                break;
                            }
                            for (StrategyBusinessItemVO itemVO : itemWeightList) {
                                if (ToolKits.isNotEmpty(conditionModel.getLowerLimitValue()) && ToolKits.isNotEmpty(conditionModel.getUpperLimitValue())) {
                                    if (NumberUtil.isGreater(itemVO.getWeight(), conditionModel.getLowerLimitValue()) &&
                                            NumberUtil.isLess(itemVO.getWeight(), conditionModel.getUpperLimitValue())) {
                                        fitCnt++;
                                        break;
                                    }
                                } else if (ToolKits.isNotEmpty(conditionModel.getLowerLimitValue())) {
                                    if (conditionModel.getLowerLimitSymbol().equals(DataDictionaryConstant.CMP_SYMBOL_GT)) {
                                        if (NumberUtil.isGreater(itemVO.getWeight(), conditionModel.getLowerLimitValue())) {
                                            fitCnt++;
                                            break;
                                        }
                                    } else {
                                        if (NumberUtil.isLess(itemVO.getWeight(), conditionModel.getUpperLimitValue())) {
                                            fitCnt++;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    case 14: // 商品总件数
                        if (ToolKits.isNotEmpty(conditionModel.getLowerLimitValue()) && ToolKits.isNotEmpty(conditionModel.getUpperLimitValue())) {
                            if (NumberUtil.isGreater(businessMatchingVO.getTotalPcs(), conditionModel.getLowerLimitValue()) &&
                                    NumberUtil.isLess(businessMatchingVO.getTotalPcs(), conditionModel.getUpperLimitValue())) {
                                fitCnt++;
                                break;
                            }
                        } else if (ToolKits.isNotEmpty(conditionModel.getLowerLimitValue())) {
                            if (conditionModel.getLowerLimitSymbol().equals(DataDictionaryConstant.CMP_SYMBOL_GT)) {
                                if (NumberUtil.isGreater(businessMatchingVO.getTotalPcs(), conditionModel.getLowerLimitValue())) {
                                    fitCnt++;
                                    break;
                                }
                            } else {
                                if (NumberUtil.isLess(businessMatchingVO.getTotalPcs(), conditionModel.getUpperLimitValue())) {
                                    fitCnt++;
                                    break;
                                }
                            }
                        }
                        break;
                    case 15: // 商品总重量
                        if (ToolKits.isNotEmpty(conditionModel.getLowerLimitValue()) && ToolKits.isNotEmpty(conditionModel.getUpperLimitValue())) {
                            if (NumberUtil.isGreater(businessMatchingVO.getTotalWeight(), conditionModel.getLowerLimitValue()) &&
                                    NumberUtil.isLess(businessMatchingVO.getTotalWeight(), conditionModel.getUpperLimitValue())) {
                                fitCnt++;
                                break;
                            }
                        } else if (ToolKits.isNotEmpty(conditionModel.getLowerLimitValue())) {
                            if (conditionModel.getLowerLimitSymbol().equals(DataDictionaryConstant.CMP_SYMBOL_GT)) {
                                if (NumberUtil.isGreater(businessMatchingVO.getTotalWeight(), conditionModel.getLowerLimitValue())) {
                                    fitCnt++;
                                    break;
                                }
                            } else {
                                if (NumberUtil.isLess(businessMatchingVO.getTotalWeight(), conditionModel.getUpperLimitValue())) {
                                    fitCnt++;
                                    break;
                                }
                            }
                        }
                        break;
                    case 16: // 发货方省市区
                        List<String> shipperZoneCode = Lists.newArrayList();
                        List<String> shipperZoneCodeMatched = Lists.newArrayList();
                        if (ToolKits.isNotEmpty(businessMatchingVO.getShipperProvince())) {
                            shipperZoneCode.add(businessMatchingVO.getShipperProvince());
                            if (ToolKits.isEmpty(conditionModel.getShipperProvince())) {
                                break;
                            }
                            if (conditionModel.getShipperProvince().contains(businessMatchingVO.getShipperProvince())) {
                                shipperZoneCodeMatched.add(businessMatchingVO.getShipperProvince());
                            }
                        }
                        if (ToolKits.isNotEmpty(businessMatchingVO.getShipperCity())) {
                            shipperZoneCode.add(businessMatchingVO.getShipperCity());
                            if (ToolKits.isEmpty(conditionModel.getShipperCity())) {
                                break;
                            }
                            if (conditionModel.getShipperCity().contains(businessMatchingVO.getShipperCity())) {
                                shipperZoneCodeMatched.add(businessMatchingVO.getShipperCity());
                            }
                        }
                        if (ToolKits.isNotEmpty(businessMatchingVO.getShipperDistrict())) {
                            shipperZoneCode.add(businessMatchingVO.getShipperDistrict());
                            if (ToolKits.isEmpty(conditionModel.getShipperDistrict())) {
                                break;
                            }
                            if (conditionModel.getShipperDistrict().contains(businessMatchingVO.getShipperDistrict())) {
                                shipperZoneCodeMatched.add(businessMatchingVO.getShipperDistrict());
                            }
                        }
                        if (shipperZoneCodeMatched.size() > 0 && shipperZoneCode.size() == shipperZoneCodeMatched.size()) {
                            fitCnt++;
                        }
                        break;
                    case 17: // 收货方省市区
                        List<String> consigneeZoneCode = Lists.newArrayList();
                        List<String> consigneeZoneCodeMatched = Lists.newArrayList();
                        if (ToolKits.isNotEmpty(businessMatchingVO.getConsigneeProvince())) {
                            consigneeZoneCode.add(businessMatchingVO.getConsigneeProvince());
                            if (ToolKits.isEmpty(conditionModel.getConsigneeProvince())) {
                                break;
                            }
                            if (conditionModel.getConsigneeProvince().contains(businessMatchingVO.getConsigneeProvince())) {
                                consigneeZoneCodeMatched.add(businessMatchingVO.getConsigneeProvince());
                            }
                        }
                        if (ToolKits.isNotEmpty(businessMatchingVO.getConsigneeCity())) {
                            consigneeZoneCode.add(businessMatchingVO.getConsigneeCity());
                            if (ToolKits.isEmpty(conditionModel.getConsigneeCity())) {
                                break;
                            }
                            if (conditionModel.getConsigneeCity().contains(businessMatchingVO.getConsigneeCity())) {
                                consigneeZoneCodeMatched.add(businessMatchingVO.getConsigneeCity());
                            }
                        }
                        if (ToolKits.isNotEmpty(businessMatchingVO.getConsigneeDistrict())) {
                            consigneeZoneCode.add(businessMatchingVO.getConsigneeDistrict());
                            if (ToolKits.isEmpty(conditionModel.getConsigneeDistrict())) {
                                break;
                            }
                            if (conditionModel.getConsigneeDistrict().contains(businessMatchingVO.getConsigneeDistrict())) {
                                consigneeZoneCodeMatched.add(businessMatchingVO.getConsigneeDistrict());
                            }
                        }
                        if (consigneeZoneCodeMatched.size() > 0 && consigneeZoneCode.size() == consigneeZoneCodeMatched.size()) {
                            fitCnt++;
                        }
                        break;
                    case 18:
                        if (ToolKits.isNotEmpty(conditionModel.getStrategyConditionValue()) &&
                                ToolKits.isNotEmpty(goodsTransfiniteEnabled) &&
                                conditionModel.getStrategyConditionValue().equals(goodsTransfiniteEnabled)) {
                            fitCnt++;
                        }
                        break;
                    default:
                        String conditionValues = conditionModel.getStrategyConditionValue();
                        if (ToolKits.isNotEmpty(conditionValues)) {
                            String[] conditionValueArr = conditionValues.split(",");
                            for (String conditionValue : conditionValueArr) {
                                if (conditionMap.containsValue(conditionModel.getStrategyConditionType() + "_" + conditionValue)) {
                                    fitCnt++;
                                    break;
                                }
                            }
                        }
                        break;
                }
            }

            // 匹配到了业务规则策略
            if (fitCnt == tmsStrategySplitConditionModels.size()) {
                list.add(businessMatchingDTO);
                log.info("运单匹配到{}业务规则,规则数据{}", tmsStrategyBusinessModel.getName(), JSON.toJSONString(list));
                return list;
            }
        }
        log.info("运单匹配到{}业务规则,规则数据{}", " ", JSON.toJSONString(list));
        return list;
    }
}
