package cn.com.taiji.beidou.ship.warning.model.service.impl;

import cn.com.taiji.beidou.common.core.domain.R;
import cn.com.taiji.beidou.common.exception.GlobalException;
import cn.com.taiji.beidou.common.utils.SecurityUtils;
import cn.com.taiji.beidou.common.utils.StringUtils;
import cn.com.taiji.beidou.common.utils.uuid.SnowFlakeIdWorker;
import cn.com.taiji.beidou.ship.config.StringProducer;
import cn.com.taiji.beidou.ship.warning.model.domain.*;
import cn.com.taiji.beidou.ship.warning.model.mapper.ShipWarningModelMapper;
import cn.com.taiji.beidou.ship.warning.model.service.ShipWarningService;
import cn.com.taiji.beidou.ship.warning.rule.domain.RuleModelAreaData;
import cn.com.taiji.beidou.ship.warning.rule.domain.RuleModelParamData;
import cn.com.taiji.beidou.ship.warning.rule.domain.UpdateEnabledReq;
import cn.com.taiji.beidou.ship.warning.rule.domain.WarningRuleData;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author CHEN
 * @Date 2022/11/20 9:51
 */
@Service
public class ShipWarningServiceImpl implements ShipWarningService {

    @Resource
    private ShipWarningModelMapper shipWarningModelMapper;

    @Resource
    private StringProducer stringProducer;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addOrUpdateWarningRule(WarningRuleReq warningRuleReq) {
        SnowFlakeIdWorker worker = new SnowFlakeIdWorker(1, 0);
        String ruleId =String.valueOf(worker.nextId());
        String paramRuleId = warningRuleReq.getRuleId();

        String userId = String.valueOf(SecurityUtils.getUserId());
        WarningRuleData warningRuleData = new WarningRuleData();
        String name = warningRuleReq.getName();

        warningRuleData.setCreateBy(userId)
                .setName(warningRuleReq.getName())
                .setStartTime(warningRuleReq.getStartTime())
                .setEndTime(warningRuleReq.getEndTime())
                .setEnabled(warningRuleReq.getEnabled());
        //如果规则ID不为空，则是修改规则
        if(StringUtils.isNotBlank(paramRuleId)){
            if(shipWarningModelMapper.selectRuleByIdCount(paramRuleId)>0){
                throw new GlobalException("规则已启用，请停用后再修改");
            }
            //判断编辑后的名称是否唯一
            if(shipWarningModelMapper.selectWarningRuleByName(name,paramRuleId)>0){
                throw new GlobalException("已有规则名称"+name);
            }
            //删除规则和模型关联
            shipWarningModelMapper.delRuleAndModelByRule(paramRuleId);
            warningRuleData.setId(paramRuleId);
            shipWarningModelMapper.updateRule(warningRuleData);
            shipWarningModelMapper.delRuleAndParamByRule(paramRuleId);
            //根据规则ID删除 规则模型区域关系
            shipWarningModelMapper.delRuleModelAreaByRId(paramRuleId);
            //删除规则下的规则模型参数关系
            //shipWarningModelMapper.delRuleModelParamByRId(paramRuleId);
            ruleId = paramRuleId;
        }else {
            if(shipWarningModelMapper.selectWarningRuleByName(name,null)>0){
                throw new GlobalException("已有规则名称"+name);
            }
            warningRuleData.setId(ruleId);
            shipWarningModelMapper.insertRule(warningRuleData);
        }
        String modelId = warningRuleReq.getModelId();
        String id =String.valueOf(worker.nextId());
        shipWarningModelMapper.insertRuleAndModel(id,ruleId,modelId,userId);

        String finalRuleId = ruleId;
        warningRuleReq.getParamList().stream().forEach(list->{
            RuleModelParamData ruleModelParamByRMP = shipWarningModelMapper.getRuleModelParamByRMP(finalRuleId, modelId, list.getParamId());
            if(ruleModelParamByRMP!=null){
                ruleModelParamByRMP.setParamValue(list.getParamValue());
                shipWarningModelMapper.insertRuleModelParam(ruleModelParamByRMP);
            }else {
                RuleModelParamData ruleModelParamData = new RuleModelParamData();
                ruleModelParamData.setId(worker.nextId());
                ruleModelParamData.setRuleId(finalRuleId);
                ruleModelParamData.setModelId(modelId);
                ruleModelParamData.setParamId(list.getParamId());
                ruleModelParamData.setParamValue(list.getParamValue());
                ruleModelParamData.setCreateBy(userId);
                shipWarningModelMapper.insertRuleModelParam(ruleModelParamData);
            }

        });

        String[] splits = warningRuleReq.getAreaList().split(",");
        for(String split:splits){
            String id1 =String.valueOf(worker.nextId());
            RuleModelAreaData data = new RuleModelAreaData();
            data.setId(id1);
            data.setRuleId(finalRuleId);
            data.setModelId(modelId);
            data.setAreaId(split);
            data.setCreateBy(userId);
            shipWarningModelMapper.insertRuleModelArea(data);
        }

        return 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addOrUpdateWarningModel(WarningModelReq warningModelReq) {
        SnowFlakeIdWorker worker = new SnowFlakeIdWorker(1, 0);
        String paramModelId = warningModelReq.getModelId();
        String modelId =String.valueOf(worker.nextId());
        String modelName = warningModelReq.getModelName();
        String userId = String.valueOf(SecurityUtils.getUserId());
        WarningModelData warningModelData = new WarningModelData();
        warningModelData.setCode(warningModelReq.getCode())
                .setName(warningModelReq.getModelName())
                .setDescription(warningModelReq.getDescription())
                .setCreateBy(userId);
        //如果模型ID不为空，则是修改模型
        if(StringUtils.isNotBlank(paramModelId)){
            if(shipWarningModelMapper.isEnableByModel(paramModelId)>0){
                throw new GlobalException("该模型配置规则正在启用，请先停用规则！");
            }
            if (shipWarningModelMapper.selectWarningModelByName(modelName,paramModelId)>0){
                throw new GlobalException("已有模型名称"+modelName);
            }
            shipWarningModelMapper.delModelAndParam(paramModelId);
            //获取原来的规则模型参数关系
            List<RuleModelParamData> ruleAndParamByMId = shipWarningModelMapper.getRuleAndParamByMId(paramModelId);
            //删除原来的规则模型参数关系
            shipWarningModelMapper.delRuleModelParamByMId(paramModelId);
            //新增规则模型参数关系
            warningModelReq.getParamList().stream().forEach(param->{
                String paramId =String.valueOf(worker.nextId());
                WarningParamData warningParamData = new WarningParamData();
                String paramDictId = param.getParamDictId();
                if (StringUtils.isNotBlank(paramDictId)){
                    warningParamData.setId(paramId)
                            .setDictId(paramDictId)
                            .setRecommend(param.getRecommend())
                            .setIsMust(param.getIsMust())
                            .setCreateBy(userId);
                    shipWarningModelMapper.insertParam(warningParamData);
                    ruleAndParamByMId.stream().forEach(rmid->{
                        RuleModelParamData ruleModelParamData = new RuleModelParamData();
                        ruleModelParamData.setId(worker.nextId());
                        ruleModelParamData.setRuleId(rmid.getRuleId());
                        ruleModelParamData.setModelId(rmid.getModelId());
                        ruleModelParamData.setParamId(paramId);
                        shipWarningModelMapper.insertRuleModelParam(ruleModelParamData);
                    });
                    shipWarningModelMapper.insertModelAndParam(String.valueOf(worker.nextId()),
                            paramModelId,paramId,userId);
                }
            });

            //删除模型区域关联关系
            shipWarningModelMapper.delModelAndArea(paramModelId);
            warningModelData.setId(paramModelId);
            shipWarningModelMapper.updateModel(warningModelData);
            modelId = paramModelId;
        }else {
            //判断预警模型名称是否唯一
            if (shipWarningModelMapper.selectWarningModelByName(modelName,null)>0){
                throw new GlobalException("已有模型名称"+modelName);
            }

            warningModelData.setId(modelId);
            shipWarningModelMapper.insertModel(warningModelData);
            //处理模型参数
            String finalModelId = modelId;
            warningModelReq.getParamList().stream().forEach(param->{
                String paramId =String.valueOf(worker.nextId());
                WarningParamData warningParamData = new WarningParamData();
                String paramDictId = param.getParamDictId();
                if (StringUtils.isNotBlank(paramDictId)){
                    warningParamData.setId(paramId)
                            .setDictId(paramDictId)
                            .setRecommend(param.getRecommend())
                            .setIsMust(param.getIsMust())
                            .setCreateBy(userId);
                    shipWarningModelMapper.insertParam(warningParamData);
                    shipWarningModelMapper.insertModelAndParam(String.valueOf(worker.nextId()), finalModelId,paramId,userId);
                }
            });
        }

        //处理区域
        String[] splits = warningModelReq.getAreaList().split(",");
        for(String split:splits){
            String id =String.valueOf(worker.nextId());
            shipWarningModelMapper.insertModelAndArea(id,modelId,split,userId);
        }

        return 0;
    }

    @Override
    public int addWarningParam(WarningParamData warningParamData) {
        warningParamData.setId(String.valueOf(new SnowFlakeIdWorker(1,0).nextId()));
        warningParamData.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        return shipWarningModelMapper.insertParam(warningParamData);
    }

    @Override
    public int addWarningArea(WarningAreaData warningAreaData) {
        warningAreaData.setId(String.valueOf(new SnowFlakeIdWorker(1,0).nextId()));
        warningAreaData.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        return shipWarningModelMapper.insertArea(warningAreaData);
    }

    @Override
    public int updateEnabledById(UpdateEnabledReq updateEnabledReq) {
        JSONObject object = new JSONObject();
        object.put("type","1");
        if(updateEnabledReq.getEnabled()){
            object.put("operation","4");
        }else {
            object.put("operation","5");
        }
        object.put("id",updateEnabledReq.getId());
        int i = shipWarningModelMapper.updateEnabledById(updateEnabledReq);
        if(i>0){
            stringProducer.sendMessage("taiji_ax_warn_sync_message",object.toJSONString());
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delRule(String id) {
        if(shipWarningModelMapper.selectRuleByIdCount(id)>0){
            throw new GlobalException("规则已启用，请停用后再删除");
        }

        //删除规则模型关联表
        shipWarningModelMapper.delRuleAndModelByRule(id);
        //删除预警规则
        return shipWarningModelMapper.delRule(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delModel(String id) {
        if(shipWarningModelMapper.selectRuleModelByModelIdCount(id)>0){
            throw new GlobalException("该模型已配置规则，请先解除配置！");
        }

        shipWarningModelMapper.delModelAndArea(id);
        shipWarningModelMapper.delModelAndParam(id);
        return shipWarningModelMapper.delModel(id);
    }

    @Override
    public List<WarningAreaVo> findInId(String ids) {
        String[] array = ids.split(",");

        return shipWarningModelMapper.findInId(array);
    }
}
