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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.prolog.common.util.ToolKits;
import com.prolog.framework.core.exception.BizException;
import com.prolog.framework.core.exception.ParameterException;
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.RestrictionBuilder;
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.config.enums.MessageConfigConditionEnum;
import com.prolog.rdc.tms.config.enums.MessageConfigSendTypeEnum;
import com.prolog.rdc.tms.config.enums.MessageConfigStatusEnum;
import com.prolog.rdc.tms.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.constant.SeriaNnumberConstant;
import com.prolog.rdc.tms.dao.mapper.TmsMessageConfigConditionMapper;
import com.prolog.rdc.tms.dao.mapper.TmsMessageConfigMapper;
import com.prolog.rdc.tms.dao.mapper.TmsMessageConfigNoticeToMapper;
import com.prolog.rdc.tms.model.dto.message.MessageConfigConditionDTO;
import com.prolog.rdc.tms.model.dto.message.MessageConfigDTO;
import com.prolog.rdc.tms.model.dto.message.MessageConfigNoticeToDTO;
import com.prolog.rdc.tms.model.entity.message.TmsMessageConfigCondition;
import com.prolog.rdc.tms.model.entity.message.TmsMessageConfigModel;
import com.prolog.rdc.tms.model.entity.message.TmsMessageConfigNoticeTo;
import com.prolog.rdc.tms.model.enums.MessageAlarmTypeEnum;
import com.prolog.rdc.tms.model.enums.MessageNoticeTypeEnum;
import com.prolog.rdc.tms.model.vo.message.DeleteMessageConfigVO;
import com.prolog.rdc.tms.model.vo.message.MessageConfigQueryVO;
import com.prolog.rdc.tms.model.vo.message.SaveMessageConfigVO;
import com.prolog.rdc.tms.model.vo.message.UpdateMessageConfigStatusVO;
import com.prolog.rdc.tms.service.SysCodeengineService;
import com.prolog.rdc.tms.service.SysRefdatadService;
import com.prolog.rdc.tms.service.message.MessageConfigService;
import com.prolog.rdc.tms.util.PublicMethods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author hongbo.pan
 * @date 2022/11/15
 */
@Slf4j
@Service
public class MessageConfigServiceImpl implements MessageConfigService {

    @Autowired
    private SysCodeengineService sysCodeengineService;

    @Autowired
    private TmsMessageConfigConditionMapper tmsMessageConfigConditionMapper;

    @Autowired
    private TmsMessageConfigMapper tmsMessageConfigMapper;

    @Autowired
    private TmsMessageConfigNoticeToMapper tmsMessageConfigNoticeToMapper;

    @Autowired
    private SysRefdatadService sysRefdatadService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(SaveMessageConfigVO vo) {
        ToolKits.isParamNull(vo, "入参不能为空");
        ToolKits.isParamNull(vo.getName(), "消息名称不能为空");
        ToolKits.isParamNull(vo.getType(), "消息类型不能为空");
        ToolKits.isParamNull(vo.getSendType(), "推送方式不能为空");
        ToolKits.isParamNull(vo.getContent(), "消息内容不能为空");
        if (StrUtil.isBlank(vo.getNoticeType())) {
            vo.setNoticeType(MessageNoticeTypeEnum.BUSINESS.getCode());
        }
        if (vo.getSendType().contains(MessageConfigSendTypeEnum.QW.getCode()) && StrUtil.isBlank(vo.getQwWebhook())) {
            throw new ParameterException("企业微信webhook不能为空");
        }
        if (vo.getSendType().contains(MessageConfigSendTypeEnum.DINGDING.getCode()) && StrUtil.isBlank(vo.getDdWebhook())) {
            throw new ParameterException("钉钉webhook不能为空");
        }
        if (CollectionUtil.isNotEmpty(vo.getMessageConfigConditionVOList())) {
            vo.getMessageConfigConditionVOList().forEach(saveMessageConfigConditionVO -> {
                ToolKits.isParamNull(saveMessageConfigConditionVO.getConditionType(), "消息条件type不能为空");
                if (MessageConfigConditionEnum.CARGO_OWNER.getCode().equals(saveMessageConfigConditionVO.getConditionType()) ||
                        MessageConfigConditionEnum.DEPARTMENT.getCode().equals(saveMessageConfigConditionVO.getConditionType())) {
                    ToolKits.isParamNull(saveMessageConfigConditionVO.getUnitId(), "消息条件unitId不能为空");
                    ToolKits.isParamNull(saveMessageConfigConditionVO.getUnitCode(), "消息条件unitCode不能为空");
                    ToolKits.isParamNull(saveMessageConfigConditionVO.getUnitName(), "消息条件unitName不能为空");
                } else {
                    ToolKits.isParamNull(saveMessageConfigConditionVO.getConditionValue(), "消息条件value不能为空");
                }
            });
        }
        if (CollectionUtil.isNotEmpty(vo.getMessageConfigNoticeToVOList())) {
            vo.getMessageConfigNoticeToVOList().forEach(saveMessageConfigNoticeToVO -> {
                ToolKits.isParamNull(saveMessageConfigNoticeToVO.getType(), "对象type不能为空");
                ToolKits.isParamNull(saveMessageConfigNoticeToVO.getNoticeToId(), "对象id不能为空");
                ToolKits.isParamNull(saveMessageConfigNoticeToVO.getNoticeToName(), "对象名称不能为空");
            });
        }
        if (MessageNoticeTypeEnum.ALARM.getCode().equals(vo.getNoticeType())) {
            ToolKits.isParamNull(vo.getAlarmStartOffset(), "开始预警偏差不能为空");
            ToolKits.isParamNull(vo.getAlarmStartOffsetUnit(), "开始预警偏差单位不能为空");
            ToolKits.isParamNull(vo.getAlarmEndOffset(), "结束预警偏差不能为空");
            ToolKits.isParamNull(vo.getAlarmEndOffsetUnit(), "结束预警偏差单位不能为空");
            ToolKits.isParamNull(vo.getAlarmInterval(), "预警间隔不能为空");
            ToolKits.isParamNull(vo.getAlarmIntervalUnit(), "预警间隔单位不能为空");
            ToolKits.isParamNull(vo.getAlarmVoice(), "语音播报不能为空");
        } else {
            vo.setAlarmVoice(DataDictionaryConstant.NOTICE_TO_N);
        }
        if (ObjectUtil.isNull(vo.getId())) {
            addMessageConfig(vo);
        } else {
            updateMessageConfig(vo);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStatus(UpdateMessageConfigStatusVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(vo, "入参不能为空");
        ToolKits.isParamNull(vo.getIdList(), "主键集合不能为空");
        ToolKits.isParamNull(vo.getStatus(), "状态不能为空");
        List<TmsMessageConfigModel> tmsMessageConfigModelList =
                tmsMessageConfigMapper.findByIds(TmsMessageConfigModel.class, vo.getIdList().toArray(new Long[0]), null);
        if (CollectionUtil.isEmpty(tmsMessageConfigModelList)) {
            throw new BizException("配置不存在");
        }
        if (tmsMessageConfigModelList.stream().anyMatch(tmsMessageConfigModel -> tmsMessageConfigModel.getStatus().equals(vo.getStatus()))) {
            throw new BizException("状态不匹配");
        }
        tmsMessageConfigModelList.forEach(tmsMessageConfigModel -> {
            tmsMessageConfigModel.setUpdatetime(new Date());
            tmsMessageConfigModel.setUpdateperson(user.getNickname());
            tmsMessageConfigModel.setStatus(vo.getStatus());
            tmsMessageConfigMapper.update(tmsMessageConfigModel);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(DeleteMessageConfigVO vo) {
        ToolKits.isParamNull(vo, "入参不能为空");
        ToolKits.isParamNull(vo.getIdList(), "主键集合不能为空");
        tmsMessageConfigMapper.deleteByIds(vo.getIdList().toArray(new Long[0]), TmsMessageConfigModel.class);
        deleteByConfigId(vo.getIdList());
    }

    @Override
    public Page<MessageConfigDTO> query(MessageConfigQueryVO vo) {
        if (StrUtil.isBlank(vo.getNoticeType())) {
            vo.setNoticeType(MessageNoticeTypeEnum.BUSINESS.getCode());
        }
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        Criteria criteria = Criteria.forClass(TmsMessageConfigModel.class);
        Restriction r1 = StrUtil.isBlank(vo.getName())?null: Restrictions.like("name", "%"+vo.getName()+"%");
        Restriction r2 = StrUtil.isBlank(vo.getType())?null:Restrictions.eq("type", vo.getType());
        Restriction r3 = StrUtil.isBlank(vo.getStatus())?null:Restrictions.eq("status", vo.getStatus());
        Restriction r4 = StrUtil.isBlank(vo.getSendType())?null:Restrictions.like("sendType", "%"+vo.getSendType()+"%");
        Restriction r5 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
        Restriction r6 = StrUtil.isBlank(vo.getNoticeType())?null:Restrictions.eq(TmsMessageConfigModel::getNoticeType, vo.getNoticeType());
        criteria.setRestriction(Restrictions.and(r1,r2,r3,r4,r5,r6));
        criteria.setOrder(Order.newInstance().desc("updatetime"));
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<TmsMessageConfigModel> tmsMessageConfigModelList = tmsMessageConfigMapper.findByCriteria(criteria);
        List<MessageConfigDTO> result = Lists.newArrayList();
        if (CollectionUtil.isNotEmpty(tmsMessageConfigModelList)) {
            // 消息配置状态
            List<Map<String, Object>> messageStatus = sysRefdatadService.getDropDownById(DataDictionaryConstant.MESSAGE_CONFIG_STATUS, null, null, null);
            // 消息类型
            List<Map<String, Object>> messageType = sysRefdatadService.getDropDownById(DataDictionaryConstant.MESSAGE_TYPE, null, null, null);
            // 预警消息类型
            List<Map<String, Object>> messageAlarmType = sysRefdatadService.getDropDownById(MessageAlarmTypeEnum.MESSAGE_ALARM_TYPE, null, null, null);
            // 消息推送方式
            List<Map<String, Object>> messageSendType = sysRefdatadService.getDropDownById(DataDictionaryConstant.MESSAGE_SEND_TYPE, null, null, null);
            // 时间类型
            List<Map<String, Object>> timeUnit = sysRefdatadService.getDropDownById(DataDictionaryConstant.MESSAGE_TIME_UNIT, null, null, null);
            result = tmsMessageConfigModelList.stream().map(tmsMessageConfigModel -> convertToMessageConfigDTO(tmsMessageConfigModel,
                    messageStatus, messageType, messageSendType, messageAlarmType, timeUnit)).collect(Collectors.toList());
        }
        Page<MessageConfigDTO> page = PageUtils.getPage(result);
        if (tmsMessageConfigModelList instanceof com.github.pagehelper.Page) {
            com.github.pagehelper.Page<TmsMessageConfigModel> p0 = (com.github.pagehelper.Page<TmsMessageConfigModel>) tmsMessageConfigModelList;
            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 MessageConfigDTO findById(Long messageConfigId) {
        TmsMessageConfigModel messageConfigModel = tmsMessageConfigMapper.findById(messageConfigId, TmsMessageConfigModel.class);
        if (ObjectUtil.isNull(messageConfigModel)) {
            throw new BizException("消息配置不存在，id=" + messageConfigId);
        }
        // 消息配置状态
        List<Map<String, Object>> messageStatus = sysRefdatadService.getDropDownById(DataDictionaryConstant.MESSAGE_CONFIG_STATUS, null, null, null);
        // 消息类型
        List<Map<String, Object>> messageType = sysRefdatadService.getDropDownById(DataDictionaryConstant.MESSAGE_TYPE, null, null, null);
        // 预警消息类型
        List<Map<String, Object>> messageAlarmType = sysRefdatadService.getDropDownById(MessageAlarmTypeEnum.MESSAGE_ALARM_TYPE, null, null, null);
        // 时间类型
        List<Map<String, Object>> timeUnit = sysRefdatadService.getDropDownById(DataDictionaryConstant.MESSAGE_TIME_UNIT, null, null, null);
        // 消息推送方式
        List<Map<String, Object>> messageSendType = sysRefdatadService.getDropDownById(DataDictionaryConstant.MESSAGE_SEND_TYPE, null, null, null);
        MessageConfigDTO messageConfigDTO = convertToMessageConfigDTO(messageConfigModel, messageStatus, messageType, messageSendType, messageAlarmType, timeUnit);
        Criteria criteria1 = Criteria.forClass(TmsMessageConfigCondition.class);
        Restriction restriction = new RestrictionBuilder()
                .eq("messageConfigId",messageConfigDTO.getId())
                .eq("enterpriseId",messageConfigDTO.getEnterpriseId())
                .build();
        criteria1.setRestriction(restriction);
        List<TmsMessageConfigCondition> messageConfigConditionModelList =
                tmsMessageConfigConditionMapper.findByCriteria(criteria1);
        if (CollectionUtil.isNotEmpty(messageConfigConditionModelList)) {
            messageConfigDTO.setConfigConditionDTOList(messageConfigConditionModelList.stream().map(messageConfigConditionModel ->
                    BeanUtil.copyProperties(messageConfigConditionModel, MessageConfigConditionDTO.class)).collect(Collectors.toList()));
        }
        criteria1 = Criteria.forClass(TmsMessageConfigNoticeTo.class);
        restriction = new RestrictionBuilder()
                .eq("messageConfigId",messageConfigDTO.getId())
                .eq("enterpriseId",messageConfigDTO.getEnterpriseId())
                .build();
        criteria1.setRestriction(restriction);
        List<TmsMessageConfigNoticeTo> messageConfigNoticeToModelList =
                tmsMessageConfigNoticeToMapper.findByCriteria(criteria1);
        if (CollectionUtil.isNotEmpty(messageConfigNoticeToModelList)) {
            messageConfigDTO.setConfigNoticeToDTOList(messageConfigNoticeToModelList.stream().map(messageConfigNoticeToModel ->
                    BeanUtil.copyProperties(messageConfigNoticeToModel, MessageConfigNoticeToDTO.class)).collect(Collectors.toList()));
        }
        return messageConfigDTO;
    }

    /**
     * 翻译转换
     * @param tmsMessageConfigModel
     * @param messageStatus
     * @param messageType
     * @param messageSendType
     * @param messageAlarmType
     * @return
     */
    private MessageConfigDTO convertToMessageConfigDTO(TmsMessageConfigModel tmsMessageConfigModel,
                                                       List<Map<String, Object>> messageStatus,
                                                       List<Map<String, Object>> messageType,
                                                       List<Map<String, Object>> messageSendType,
                                                       List<Map<String, Object>> messageAlarmType,
                                                       List<Map<String, Object>> timeUnit) {
        MessageConfigDTO messageConfigDTO = BeanUtil.copyProperties(tmsMessageConfigModel, MessageConfigDTO.class);
        messageConfigDTO.setTypeName(PublicMethods.change(messageType, messageConfigDTO.getType()));
        if (StrUtil.isBlank(messageConfigDTO.getTypeName())) {
            messageConfigDTO.setTypeName(PublicMethods.change(messageAlarmType, messageConfigDTO.getType()));
        }
        messageConfigDTO.setSendTypeName(Arrays.stream(messageConfigDTO.getSendType().split(",")).map(sendType ->
                PublicMethods.change(messageSendType, sendType)).collect(Collectors.joining(",")));
        messageConfigDTO.setStatusName(PublicMethods.change(messageStatus, messageConfigDTO.getStatus()));
        if (ObjectUtil.isNotNull(tmsMessageConfigModel.getAlarmStartOffset())) {
            messageConfigDTO.setAlarmStartOffsetName(tmsMessageConfigModel.getAlarmStartOffset() + PublicMethods.change(timeUnit, messageConfigDTO.getAlarmStartOffsetUnit()));
        }
        if (ObjectUtil.isNotNull(tmsMessageConfigModel.getAlarmEndOffset())) {
            messageConfigDTO.setAlarmEndOffsetName(tmsMessageConfigModel.getAlarmEndOffset() + PublicMethods.change(timeUnit, messageConfigDTO.getAlarmEndOffsetUnit()));
        }
        if (ObjectUtil.isNotNull(tmsMessageConfigModel.getAlarmInterval())) {
            messageConfigDTO.setAlarmIntervalName(tmsMessageConfigModel.getAlarmInterval() + PublicMethods.change(timeUnit, messageConfigDTO.getAlarmIntervalUnit()));
        }
        //预留角色用户
//        Criteria criteria1 = Criteria.forClass(TmsMessageConfigNoticeToModel.class);
//        Restriction restriction = new RestrictionBuilder()
//                .eq("messageConfigId",messageConfigDTO.getId())
//                .eq("enterpriseId",messageConfigDTO.getEnterpriseId())
//                .build();
//        criteria1.setRestriction(restriction);
//        List<TmsMessageConfigNoticeToModel> messageConfigNoticeToModelList =
//                tmsMessageConfigNoticeToMapper.findByCriteria(criteria1);
//        String roleName = messageConfigNoticeToModelList.stream().filter(tmsMessageConfigNoticeToModel ->
//                        MessageConfigNoticeToTypeEnum.ROLE.getCode().equals(tmsMessageConfigNoticeToModel.getType())).
//                map(TmsMessageConfigNoticeToModel::getNoticeToName).collect(Collectors.joining(","));
//        if (StrUtil.isNotBlank(roleName)) {
//            roleName = Arrays.stream(roleName.split(",")).distinct().collect(Collectors.joining(","));
//        }
//        messageConfigDTO.setRoleName(roleName);
//        String userName = messageConfigNoticeToModelList.stream().filter(tmsMessageConfigNoticeToModel ->
//                        MessageConfigNoticeToTypeEnum.USER.getCode().equals(tmsMessageConfigNoticeToModel.getType())).
//                map(TmsMessageConfigNoticeToModel::getNoticeToName).collect(Collectors.joining(","));
//        if (StrUtil.isNotBlank(userName)) {
//            userName = Arrays.stream(userName.split(",")).distinct().collect(Collectors.joining(","));
//        }
//        messageConfigDTO.setUserName(userName);
        return messageConfigDTO;
    }

    /**
     * 新增消息配置
     * @param vo
     */
    private void addMessageConfig(SaveMessageConfigVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        TmsMessageConfigModel messageConfigModel = BeanUtil.copyProperties(vo, TmsMessageConfigModel.class);
        messageConfigModel.setId(Long.valueOf(sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_MESSAGE_CONFIG_ID, "L")));
        messageConfigModel.setStatus(MessageConfigStatusEnum.ENABLE.getCode());
        messageConfigModel.setEnterpriseId(user.getEnterpriseId());
        messageConfigModel.setEnterpriseName(user.getEnterpriseName());
        messageConfigModel.setCreatetime(new Date());
        messageConfigModel.setCreateperson(user.getNickname());
        messageConfigModel.setUpdatetime(new Date());
        messageConfigModel.setUpdateperson(user.getNickname());
        messageConfigModel.setNoticeCargoowner(StrUtil.isNotBlank(vo.getNoticeCargoowner()) ? vo.getNoticeCargoowner() : DataDictionaryConstant.NOTICE_TO_N);
        messageConfigModel.setNoticeShipper(StrUtil.isNotBlank(vo.getNoticeShipper()) ? vo.getNoticeShipper() : DataDictionaryConstant.NOTICE_TO_N);
        messageConfigModel.setNoticeConsignee(StrUtil.isNotBlank(vo.getNoticeConsignee()) ? vo.getNoticeConsignee() : DataDictionaryConstant.NOTICE_TO_N);
        messageConfigModel.setNoticeCarrier(StrUtil.isNotBlank(vo.getNoticeCarrier()) ? vo.getNoticeCarrier() : DataDictionaryConstant.NOTICE_TO_N);
        messageConfigModel.setNoticeDriver(StrUtil.isNotBlank(vo.getNoticeDriver()) ? vo.getNoticeDriver() : DataDictionaryConstant.NOTICE_TO_N);
        messageConfigModel.setConditionName(getConditionName(vo));
        messageConfigModel.setAlarmStartOffset(vo.getAlarmStartOffset());
        messageConfigModel.setAlarmStartOffsetUnit(vo.getAlarmStartOffsetUnit());
        messageConfigModel.setAlarmEndOffset(vo.getAlarmEndOffset());
        messageConfigModel.setAlarmEndOffsetUnit(vo.getAlarmEndOffsetUnit());
        messageConfigModel.setAlarmInterval(vo.getAlarmInterval());
        messageConfigModel.setAlarmIntervalUnit(vo.getAlarmIntervalUnit());
        messageConfigModel.setAlarmVoice(vo.getAlarmVoice());
        messageConfigModel.setNoticeType(vo.getNoticeType());
        tmsMessageConfigMapper.save(messageConfigModel);
        checkConfigName(messageConfigModel);
        addByConfigId(messageConfigModel.getId(), vo);
    }

    /**
     * 更新消息配置
     * @param vo
     */
    private void updateMessageConfig(SaveMessageConfigVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        TmsMessageConfigModel messageConfigModel = tmsMessageConfigMapper.findById(vo.getId(), TmsMessageConfigModel.class);
        if (ObjectUtil.isNull(messageConfigModel)) {
            throw new BizException("消息配置不存在，id=" + vo.getId());
        }
        messageConfigModel.setType(vo.getType());
        messageConfigModel.setSendType(vo.getSendType());
        messageConfigModel.setContent(vo.getContent());
        messageConfigModel.setNoticeType(vo.getNoticeType());
        messageConfigModel.setNoticeCargoowner(vo.getNoticeCargoowner());
        messageConfigModel.setNoticeShipper(vo.getNoticeShipper());
        messageConfigModel.setNoticeConsignee(vo.getNoticeConsignee());
        messageConfigModel.setNoticeCarrier(vo.getNoticeCarrier());
        messageConfigModel.setNoticeDriver(vo.getNoticeDriver());
        messageConfigModel.setQwWebhook(vo.getQwWebhook());
        messageConfigModel.setDdWebhook(vo.getDdWebhook());
        messageConfigModel.setUpdatetime(new Date());
        messageConfigModel.setUpdateperson(user.getNickname());
        messageConfigModel.setNoticeCargoowner(StrUtil.isNotBlank(vo.getNoticeCargoowner()) ? vo.getNoticeCargoowner() : DataDictionaryConstant.NOTICE_TO_N);
        messageConfigModel.setNoticeShipper(StrUtil.isNotBlank(vo.getNoticeShipper()) ? vo.getNoticeShipper() : DataDictionaryConstant.NOTICE_TO_N);
        messageConfigModel.setNoticeConsignee(StrUtil.isNotBlank(vo.getNoticeConsignee()) ? vo.getNoticeConsignee() : DataDictionaryConstant.NOTICE_TO_N);
        messageConfigModel.setNoticeCarrier(StrUtil.isNotBlank(vo.getNoticeCarrier()) ? vo.getNoticeCarrier() : DataDictionaryConstant.NOTICE_TO_N);
        messageConfigModel.setNoticeDriver(StrUtil.isNotBlank(vo.getNoticeDriver()) ? vo.getNoticeDriver() : DataDictionaryConstant.NOTICE_TO_N);
        messageConfigModel.setConditionName(getConditionName(vo));
        messageConfigModel.setAlarmStartOffset(vo.getAlarmStartOffset());
        messageConfigModel.setAlarmStartOffsetUnit(vo.getAlarmStartOffsetUnit());
        messageConfigModel.setAlarmEndOffset(vo.getAlarmEndOffset());
        messageConfigModel.setAlarmEndOffsetUnit(vo.getAlarmEndOffsetUnit());
        messageConfigModel.setAlarmInterval(vo.getAlarmInterval());
        messageConfigModel.setAlarmIntervalUnit(vo.getAlarmIntervalUnit());
        messageConfigModel.setAlarmVoice(vo.getAlarmVoice());
        tmsMessageConfigMapper.update(messageConfigModel);
        deleteByConfigId(Lists.newArrayList(vo.getId()));
        addByConfigId(vo.getId(), vo);
    }

    private void deleteByConfigId(List<Long> configIdList) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        Criteria criteria = Criteria.forClass(TmsMessageConfigCondition.class);
        Restriction restriction = new RestrictionBuilder()
                .in("messageConfigId",configIdList.toArray())
                .eq("enterpriseId",user.getEnterpriseId())
                .build();
        criteria.setRestriction(restriction);
        tmsMessageConfigConditionMapper.deleteByCriteria(criteria);

        criteria = Criteria.forClass(TmsMessageConfigNoticeTo.class);
        restriction = new RestrictionBuilder()
                .in("messageConfigId",configIdList.toArray())
                .eq("enterpriseId",user.getEnterpriseId())
                .build();
        criteria.setRestriction(restriction);
        tmsMessageConfigNoticeToMapper.deleteByCriteria(criteria);
    }

    private void addByConfigId(Long configId, SaveMessageConfigVO vo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        if (CollectionUtil.isNotEmpty(vo.getMessageConfigConditionVOList())) {
            vo.getMessageConfigConditionVOList().forEach(saveMessageConfigConditionVO -> {
                TmsMessageConfigCondition messageConfigConditionModel = BeanUtil.copyProperties(
                        saveMessageConfigConditionVO, TmsMessageConfigCondition.class);
                messageConfigConditionModel.setId(Long.valueOf(sysCodeengineService.getCodeNumberByCode(
                        SeriaNnumberConstant.TMS_MESSAGE_CONFIG_CONDITION_ID, "L")));
                messageConfigConditionModel.setMessageConfigId(configId);
                messageConfigConditionModel.setEnterpriseId(user.getEnterpriseId());
                messageConfigConditionModel.setEnterpriseName(user.getEnterpriseName());
                messageConfigConditionModel.setCreatetime(new Date());
                messageConfigConditionModel.setCreateperson(user.getNickname());
                messageConfigConditionModel.setUpdatetime(new Date());
                messageConfigConditionModel.setUpdateperson(user.getNickname());
                tmsMessageConfigConditionMapper.save(messageConfigConditionModel);
            });
        }

        if (CollectionUtil.isNotEmpty(vo.getMessageConfigNoticeToVOList())) {
            vo.getMessageConfigNoticeToVOList().forEach(saveMessageConfigNoticeToVO -> {
                TmsMessageConfigNoticeTo messageConfigNoticeToModel = BeanUtil.copyProperties(
                        saveMessageConfigNoticeToVO, TmsMessageConfigNoticeTo.class);
                messageConfigNoticeToModel.setId(Long.valueOf(sysCodeengineService.getCodeNumberByCode(
                        SeriaNnumberConstant.TMS_MESSAGE_CONFIG_NOTICE_TO_ID, "L")));
                messageConfigNoticeToModel.setMessageConfigId(configId);
                messageConfigNoticeToModel.setEnterpriseId(user.getEnterpriseId());
                messageConfigNoticeToModel.setEnterpriseName(user.getEnterpriseName());
                messageConfigNoticeToModel.setCreatetime(new Date());
                messageConfigNoticeToModel.setCreateperson(user.getNickname());
                messageConfigNoticeToModel.setUpdatetime(new Date());
                messageConfigNoticeToModel.setUpdateperson(user.getNickname());
                tmsMessageConfigNoticeToMapper.save(messageConfigNoticeToModel);
            });
        }
    }

    /**
     * 校验消息配置
     * @param messageConfigModel
     */
    private void checkConfigName(TmsMessageConfigModel messageConfigModel) {
        Criteria criteria = Criteria.forClass(TmsMessageConfigModel.class);
        Restriction restriction = new RestrictionBuilder()
                .eq("name",messageConfigModel.getName())
                .eq(TmsMessageConfigModel::getNoticeType,messageConfigModel.getNoticeType())
                .eq("enterpriseId",messageConfigModel.getEnterpriseId())
                .build();
        criteria.setRestriction(restriction);
        List<TmsMessageConfigModel> tmsMessageConfigModelList = tmsMessageConfigMapper.findByCriteria(criteria);
        if (CollectionUtil.isNotEmpty(tmsMessageConfigModelList) && tmsMessageConfigModelList.size() > 1) {
            throw new BizException("名称不能重复【"+messageConfigModel.getName()+"】");
        }

        restriction = new RestrictionBuilder()
                .eq("type",messageConfigModel.getType())
                .eq(TmsMessageConfigModel::getNoticeType,messageConfigModel.getNoticeType())
                .eq("enterpriseId",messageConfigModel.getEnterpriseId())
                .build();
        criteria.setRestriction(restriction);
        tmsMessageConfigModelList = tmsMessageConfigMapper.findByCriteria(criteria);
        if (CollectionUtil.isNotEmpty(tmsMessageConfigModelList) && tmsMessageConfigModelList.size() > 1) {
            throw new BizException("该类型的配置已存在");
        }
    }

    /**
     * 获取满足条件
     * @param vo
     * @return
     */
    private String getConditionName(SaveMessageConfigVO vo) {
        List<String> conditions = Lists.newArrayList();
        if (CollectionUtil.isNotEmpty(vo.getMessageConfigConditionVOList())) {
            // 策略条件类型
            List<Map<String, Object>> restMsgStyConditionType = sysRefdatadService.getDropDownById(DataDictionaryConstant.MESSAGE_CONDITION_TYPE, null, null, null);
            // 配送方式
            List<Map<String, Object>> restMsgDeliveryMethodType = sysRefdatadService.getDropDownById(DataDictionaryConstant.DELIVERY_METHOD_TYPE, null, null, null);
            // 订单类型
            List<Map<String, Object>> restMsgOrderType = sysRefdatadService.getDropDownById(DataDictionaryConstant.ORDER_TYPE, null, null, null);
            // 订单业务类型
            List<Map<String, Object>> restMsgOrderBusinessType = sysRefdatadService.getDropDownById(DataDictionaryConstant.ORDER_BUSINESS_TYPE, null, null, null);
            // 运输类型(运输模式)
            List<Map<String, Object>> restMsgTransportType = sysRefdatadService.getDropDownById(DataDictionaryConstant.TRANSPORT_TYPE, null, null, null);
            // 收货方类型
            List<Map<String, Object>> restMsgConsigneeType = sysRefdatadService.getDropDownById(DataDictionaryConstant.CONSIGNEE_TYPE, null, null, null);
            // 发货方类型
            List<Map<String, Object>> restMsgShipperType = sysRefdatadService.getDropDownById(DataDictionaryConstant.SHIPPER_TYPE, null, null, null);
            // 温度要求
            List<Map<String, Object>> restMsgTemperature = sysRefdatadService.getDropDownById(DataDictionaryConstant.TEMPERATURE_REQUIREMENT, null, null, null);
            vo.getMessageConfigConditionVOList().forEach(messageConfigCondition -> {
                conditions.add(PublicMethods.change(restMsgStyConditionType, messageConfigCondition.getConditionType()));
                switch (MessageConfigConditionEnum.getByCode(messageConfigCondition.getConditionType())) {
                    case DELIVERY_METHOD_TYPE :
                        conditions.add(PublicMethods.change(restMsgDeliveryMethodType, messageConfigCondition.getConditionValue()));
                        break;
                    case SHIPPER_TYPE :
                        conditions.add(PublicMethods.change(restMsgShipperType, messageConfigCondition.getConditionValue()));
                        conditions.add(messageConfigCondition.getUnitName());
                        break;
                    case CONSIGNEE_TYPE :
                        conditions.add(PublicMethods.change(restMsgConsigneeType, messageConfigCondition.getConditionValue()));
                        conditions.add(messageConfigCondition.getUnitName());
                        break;
                    case ORDER_TYPE :
                        conditions.add(PublicMethods.change(restMsgOrderType, messageConfigCondition.getConditionValue()));
                        break;
                    case ORDER_BUSINESS_TYPE :
                        conditions.add(PublicMethods.change(restMsgOrderBusinessType, messageConfigCondition.getConditionValue()));
                        break;
                    case TRANSPORT_TYPE :
                        conditions.add(PublicMethods.change(restMsgTransportType, messageConfigCondition.getConditionValue()));
                        break;
                    case TEMPERATURE_REQUIREMENT :
                        conditions.add(PublicMethods.change(restMsgTemperature, messageConfigCondition.getConditionValue()));
                        break;
                    case CARGO_OWNER :
                    case DEPARTMENT :
                        conditions.add(messageConfigCondition.getUnitName());
                        break;
                    default:
                        break;
                }
            });
        }
        return conditions.stream().collect(Collectors.joining(" "));
    }
}
