package com.xinelu.manage.service.specialdiseasetriggercondition.impl;

import com.alibaba.fastjson2.JSONArray;
import com.xinelu.common.constant.CacheConstants;
import com.xinelu.common.constant.Constants;
import com.xinelu.common.core.domain.entity.SysDictData;
import com.xinelu.common.core.redis.RedisCache;
import com.xinelu.common.enums.ReleaseStatusEnum;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.DictUtils;
import com.xinelu.common.utils.SecurityUtils;
import com.xinelu.common.utils.StringUtils;
import com.xinelu.common.utils.bean.BeanUtils;
import com.xinelu.common.utils.codes.GenerateSystemCodeUtil;
import com.xinelu.common.utils.spring.SpringUtils;
import com.xinelu.manage.domain.specialdiseaseroute.SpecialDiseaseRoute;
import com.xinelu.manage.domain.specialdiseasetriggercondition.SpecialDiseaseTriggerCondition;
import com.xinelu.manage.dto.specialdiseasetriggercondition.TriggerConditionDto;
import com.xinelu.manage.dto.specialdiseasetriggercondition.TriggerConditionSaveDTO;
import com.xinelu.manage.dto.specialdiseasetriggercondition.TriggerConditionUpdateDto;
import com.xinelu.manage.mapper.specialdiseaseroute.SpecialDiseaseRouteMapper;
import com.xinelu.manage.mapper.specialdiseasetriggercondition.SpecialDiseaseTriggerConditionMapper;
import com.xinelu.manage.service.specialdiseasetriggercondition.ISpecialDiseaseTriggerConditionService;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 触发条件关系Service业务层处理
 *
 * @author xinelu
 * @date 2024-03-18
 */
@Service
public class SpecialDiseaseTriggerConditionServiceImpl implements ISpecialDiseaseTriggerConditionService {
    @Resource
    private SpecialDiseaseTriggerConditionMapper specialDiseaseTriggerConditionMapper;
	@Resource
	private SpecialDiseaseRouteMapper specialDiseaseRouteMapper;
	@Resource
	private GenerateSystemCodeUtil generateSystemCodeUtil;

    /**
     * 查询触发条件关系
     *
     * @param id 触发条件关系主键
     * @return 触发条件关系
     */
    @Override
    public SpecialDiseaseTriggerCondition selectSpecialDiseaseTriggerConditionById(Long id) {
        return specialDiseaseTriggerConditionMapper.selectSpecialDiseaseTriggerConditionById(id);
    }

    /**
     * 查询触发条件关系列表
     *
     * @param specialDiseaseTriggerCondition 触发条件关系
     * @return 触发条件关系
     */
    @Override
    public List<SpecialDiseaseTriggerCondition> selectSpecialDiseaseTriggerConditionList(SpecialDiseaseTriggerCondition specialDiseaseTriggerCondition) {
        return specialDiseaseTriggerConditionMapper.selectSpecialDiseaseTriggerConditionList(specialDiseaseTriggerCondition);
    }

    /**
     * 新增触发条件关系
     *
     * @param triggerConditionSaveDTO 触发条件关系
     * @return 结果
     */
    @Override
    public int insertSpecialDiseaseTriggerCondition(TriggerConditionSaveDTO triggerConditionSaveDTO) {
	    // 判断主路径的发布状态
	    SpecialDiseaseRoute specialDiseaseRoute = specialDiseaseRouteMapper.selectSpecialDiseaseRouteById(triggerConditionSaveDTO.getParentRouteId());
	    if (Objects.nonNull(specialDiseaseRoute) && StringUtils.isNotBlank(specialDiseaseRoute.getReleaseStatus()) && !StringUtils.equals(ReleaseStatusEnum.UNPUBLISHED.getInfo(), specialDiseaseRoute.getReleaseStatus())) {
		    throw new ServiceException("已发布过的专病路径不能修改！");
	    }

	    if (triggerConditionSaveDTO.getParentRouteId() == null) {
			throw new ServiceException("请选择主路径");
	    }
	    if (CollectionUtils.isEmpty(triggerConditionSaveDTO.getTriggerConditionList())) {
		    throw new ServiceException("请选择触发条件");
	    }
	    if (StringUtils.isBlank(triggerConditionSaveDTO.getSuitRange())) {
		    throw new ServiceException("请选择适用范围");
	    }
	    triggerConditionSaveDTO.getTriggerConditionList().forEach(item -> {
			if (StringUtils.isBlank(item.getTriggerConditionCode()) || StringUtils.isBlank(item.getTriggerConditionOperator()) || StringUtils.isBlank(item.getTriggerConditionValue())) {
				throw new ServiceException("请选择完整的触发条件");
			}
		    item.setTriggerConditionOperator(item.getTriggerConditionOperator().replace("&gt;", ">").replace("&lt;", "<"));
	    });
	    // 保存子路径
	    specialDiseaseRoute.setCreateTime(LocalDateTime.now());
	    specialDiseaseRoute.setCreateBy(SecurityUtils.getUsername());
	    specialDiseaseRoute.setRouteCode(Constants.ROUTE_CODE + generateSystemCodeUtil.generateSystemCode(Constants.ROUTE_CODE));
	    specialDiseaseRoute.setId(null);
		// 根据触发条件拼接子路径路径名称
	    specialDiseaseRoute.setRouteName(getRouteName(triggerConditionSaveDTO.getTriggerConditionList()));
	    specialDiseaseRoute.setSuitRange(triggerConditionSaveDTO.getSuitRange());
	    specialDiseaseRoute.setParentRouteId(triggerConditionSaveDTO.getParentRouteId());
	    int flag = specialDiseaseRouteMapper.insertSpecialDiseaseRoute(specialDiseaseRoute);
		if (flag > 0) {
			// 保存触发条件
			List<SpecialDiseaseTriggerCondition> triggerConditions = new ArrayList<>();
			triggerConditionSaveDTO.getTriggerConditionList().forEach(item -> {
				SpecialDiseaseTriggerCondition triggerCondition = new SpecialDiseaseTriggerCondition();
				BeanUtils.copyBeanProp(triggerCondition, item);

				triggerCondition.setCreateTime(LocalDateTime.now());
				triggerCondition.setCreateBy(SecurityUtils.getUsername());
				triggerCondition.setRouteId(specialDiseaseRoute.getId());
				triggerCondition.setRouteName(specialDiseaseRoute.getRouteName());
				triggerCondition.setId(null);
				triggerConditions.add(triggerCondition);
			});

			specialDiseaseTriggerConditionMapper.insertTriggerConditionList(triggerConditions);
		}

        return flag;
    }

    /**
     * 修改触发条件关系
     *
     * @param triggerConditionUpdateDto 触发条件关系
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateSpecialDiseaseTriggerCondition(TriggerConditionUpdateDto triggerConditionUpdateDto) {
	    // 判断主路径的发布状态
	    SpecialDiseaseRoute route = specialDiseaseRouteMapper.selectSpecialDiseaseRouteById(triggerConditionUpdateDto.getRouteId());
		if (Objects.nonNull(route)) {
			SpecialDiseaseRoute parentRoute = specialDiseaseRouteMapper.selectSpecialDiseaseRouteById(route.getParentRouteId());
			if (Objects.nonNull(parentRoute) && org.apache.commons.lang3.StringUtils.isNotBlank(parentRoute.getReleaseStatus()) && !StringUtils.equals(ReleaseStatusEnum.UNPUBLISHED.getInfo(), parentRoute.getReleaseStatus())) {
				throw new ServiceException("已发布过的专病路径不能修改！");
			}
		}

	    if (triggerConditionUpdateDto.getRouteId() == null) {
		    throw new ServiceException("请选择路径");
	    }
	    if (CollectionUtils.isEmpty(triggerConditionUpdateDto.getTriggerConditionList())) {
		    throw new ServiceException("请选择触发条件");
	    }
	    if (StringUtils.isBlank(triggerConditionUpdateDto.getSuitRange())) {
		    throw new ServiceException("请选择适用范围");
	    }
	    triggerConditionUpdateDto.getTriggerConditionList().forEach(item -> {
		    if (StringUtils.isBlank(item.getTriggerConditionCode()) || StringUtils.isBlank(item.getTriggerConditionOperator()) || StringUtils.isBlank(item.getTriggerConditionValue())) {
			    throw new ServiceException("请选择完整的触发条件");
		    }
		    item.setTriggerConditionOperator(item.getTriggerConditionOperator().replace("&gt;", ">").replace("&lt;", "<"));
	    });
		// 修改子路径路径名称
	    SpecialDiseaseRoute specialDiseaseRoute = new SpecialDiseaseRoute();
		specialDiseaseRoute.setId(triggerConditionUpdateDto.getRouteId());
	    specialDiseaseRoute.setRouteName(getRouteName(triggerConditionUpdateDto.getTriggerConditionList()));
	    specialDiseaseRoute.setSuitRange(triggerConditionUpdateDto.getSuitRange());
	    specialDiseaseRouteMapper.updateSpecialDiseaseRoute(specialDiseaseRoute);

	    // 修改触发条件
	    SpecialDiseaseTriggerCondition specialDiseaseTriggerCondition = new SpecialDiseaseTriggerCondition();
	    specialDiseaseTriggerCondition.setRouteId(triggerConditionUpdateDto.getRouteId());
	    List<SpecialDiseaseTriggerCondition> triggerConditionList = specialDiseaseTriggerConditionMapper.selectSpecialDiseaseTriggerConditionList(specialDiseaseTriggerCondition);
	    Long[] ids = triggerConditionList.stream().map(SpecialDiseaseTriggerCondition::getId).toArray(Long[]::new);
	    specialDiseaseTriggerConditionMapper.deleteSpecialDiseaseTriggerConditionByIds(ids);

	    List<SpecialDiseaseTriggerCondition> triggerConditions = new ArrayList<>();
	    triggerConditionUpdateDto.getTriggerConditionList().forEach(item -> {
		    SpecialDiseaseTriggerCondition triggerCondition = new SpecialDiseaseTriggerCondition();
		    BeanUtils.copyBeanProp(triggerCondition, item);
		    specialDiseaseTriggerCondition.setCreateTime(LocalDateTime.now());
		    specialDiseaseTriggerCondition.setCreateBy(SecurityUtils.getUsername());
		    specialDiseaseTriggerCondition.setUpdateTime(LocalDateTime.now());
		    specialDiseaseTriggerCondition.setUpdateBy(SecurityUtils.getUsername());
		    triggerCondition.setId(null);
			triggerCondition.setRouteId(triggerConditionUpdateDto.getRouteId());
		    triggerCondition.setRouteName(specialDiseaseRoute.getRouteName());
		    triggerConditions.add(triggerCondition);
	    });
	    int flag = specialDiseaseTriggerConditionMapper.insertTriggerConditionList(triggerConditions);
		if (flag <= 0) {
			throw new ServiceException("修改失败");
		}
        return specialDiseaseRoute.getRouteName();
    }

    /**
     * 批量删除触发条件关系
     *
     * @param ids 需要删除的触发条件关系主键
     * @return 结果
     */
    @Override
    public int deleteSpecialDiseaseTriggerConditionByIds(Long[] ids) {
        return specialDiseaseTriggerConditionMapper.deleteSpecialDiseaseTriggerConditionByIds(ids);
    }

    /**
     * 删除触发条件关系信息
     *
     * @param id 触发条件关系主键
     * @return 结果
     */
    @Override
    public int deleteSpecialDiseaseTriggerConditionById(Long id) {
        return specialDiseaseTriggerConditionMapper.deleteSpecialDiseaseTriggerConditionById(id);
    }

	private String getRouteName(List<TriggerConditionDto> triggerConditionList) {
		StringBuilder routeName = new StringBuilder();
		for (int i = 0; i < triggerConditionList.size(); i++) {
			TriggerConditionDto item = triggerConditionList.get(i);
			JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(CacheConstants.SYS_DICT_KEY + "trigger_condition_name");
			List<SysDictData> dictData = new ArrayList<>();
			if (StringUtils.isNotNull(arrayCache)) {
				dictData = arrayCache.toList(SysDictData.class);
			}
			SysDictData triggerCondition = new SysDictData();
			if (StringUtils.isNotEmpty(dictData)) {
				for (SysDictData dict : dictData) {
					if (item.getTriggerConditionCode().equals(dict.getDictValue())) {
						BeanUtils.copyBeanProp(triggerCondition, dict);
					}
				}
			}
			String triggerConditionValue = item.getTriggerConditionValue();
			if (StringUtils.equals("SELECT", triggerCondition.getDictDataType())) {
				triggerConditionValue =  DictUtils.getDictLabel(triggerCondition.getDictValue(), item.getTriggerConditionValue());
			}
			if (i == 0) {
				routeName.append(triggerCondition.getDictLabel() + DictUtils.getDictLabel("trigger_condition_operator", item.getTriggerConditionOperator()))
					.append(triggerConditionValue);
			}
			if (i == 1) {
				routeName.append("|"+ triggerCondition.getDictLabel() + DictUtils.getDictLabel("trigger_condition_operator", item.getTriggerConditionOperator()) + triggerConditionValue);
			}
			if (i == 2) {
				routeName.append("(" + DictUtils.getDictLabel("trigger_logic", item.getTriggerLogic()) + ")" + DictUtils.getDictLabel("trigger_condition_name", item.getTriggerConditionCode()) + DictUtils.getDictLabel("trigger_condition_operator", item.getTriggerConditionOperator()) + triggerConditionValue);
			}
		}
		return routeName.toString();
	}
}
