package com.persagy.dmp.rwd.digital.service.calstrategy;

import cn.hutool.core.util.EscapeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.persagy.dmp.basic.dto.RelationCalDTO;
import com.persagy.dmp.basic.dto.RelationCalRuleDTO;
import com.persagy.dmp.common.exception.BusinessException;
import com.persagy.dmp.digital.entity.ObjectRelation;
import com.persagy.dmp.rwd.basic.constant.BusinessErrorRwdCode;
import com.persagy.dmp.rwd.digital.dao.ObjectRelationMapper;
import com.persagy.dmp.rwd.digital.domain.CalculatingDTO;
import com.persagy.dmp.rwd.digital.service.CalculateService;
import com.persagy.dmp.rwd.digital.service.IObjectRelationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/***
 * Description: 根据关系链计算关系的策略类
 * @author : lijie
 * @date :2021/9/8 17:03
 * Update By lijie 2021/9/8 17:03
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RelChainCalculateServiceImpl implements CalculateService {

    private final IObjectRelationService objectRelationService;
    private final ObjectRelationMapper objectRelationMapper;


    /***
     * Description: 根据关系链计算关系
     * @param calRule : 计算规则
     * @param calculatingDTO : 参数
     * @return : void
     * @author : lijie
     * @date :2021/9/8 17:10
     * Update By lijie 2021/9/8 17:10
     */
    @Override
    @Transactional
    public void calculateRelation(RelationCalRuleDTO calRule, CalculatingDTO calculatingDTO) {
        List<RelationCalDTO> chain = calRule.getDependentRelChain();
        if (chain.size()<=1){
            throw new BusinessException(BusinessErrorRwdCode.A7310.getCode(),BusinessErrorRwdCode.A7310.getDesc());
        }
        // 1.删除该类关系
        LambdaQueryWrapper<ObjectRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ObjectRelation::getGraphCode,calculatingDTO.getGraphCode());
        queryWrapper.eq(ObjectRelation::getRelCode,calculatingDTO.getRelCode());
        if (StrUtil.isNotBlank(calculatingDTO.getRelValue())){
            queryWrapper.eq(ObjectRelation::getRelValue,calculatingDTO.getRelValue());
        }
        if (StrUtil.isNotBlank(calculatingDTO.getGroupCode())){
            queryWrapper.eq(ObjectRelation::getGroupCode,calculatingDTO.getGroupCode());
        }
        if (StrUtil.isNotBlank(calculatingDTO.getProjectId())){
            queryWrapper.eq(ObjectRelation::getProjectId,calculatingDTO.getProjectId());
        }
        objectRelationService.remove(queryWrapper);
        // 2.根据链的关系计算,链的首尾
        calculatingDTO.setChain(calRule.getDependentRelChain());
        objectRelationMapper.insertObjectRelationByRelChain(calculatingDTO);
    }
}
