package com.ssyf.module.auth.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssyf.module.auth.domain.entity.DataRelation;
import com.ssyf.module.auth.domain.query.DataRelationQuery;
import com.ssyf.module.auth.mapper.DataRelationMapper;
import com.ssyf.module.auth.service.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author auth
 * @since 2022-12-12
 */
@Service
public class DataRelationServiceImpl extends ServiceImpl<DataRelationMapper, DataRelation> implements DataRelationService {

    @Override
    public List<DataRelation> getList(DataRelationQuery query) {
        return this.list(createBaseWrapper(query));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reset(String type, String hostId, List<String> relationIds) {
        DataRelationQuery query = new DataRelationQuery();
        query.setType(type).setHostId(hostId);
        this.removeBy(query);

        if(CollectionUtil.isEmpty(relationIds)){
            return;
        }
        //重建关联
        List<DataRelation> relationList = new ArrayList<>();
        relationIds.forEach(relationId->{
            DataRelation relation = new DataRelation();
            relation.setType(type).setHostId(hostId).setRelationId(relationId);
            relationList.add(relation);
        });
        //优化
        this.saveBatch(relationList);
    }

    @Override
    public void removeBy(DataRelationQuery query) {
        this.remove(createBaseWrapper(query));
    }

    @Override
    public void removeByRelationIds(List<String> relationIds) {
        LambdaQueryWrapper<DataRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(DataRelation::getRelationId ,relationIds);
        this.remove(queryWrapper);
    }

    private LambdaQueryWrapper<DataRelation> createBaseWrapper(DataRelationQuery query){
        LambdaQueryWrapper<DataRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(query.getType()) ,DataRelation::getType ,query.getType());
        queryWrapper.like(StrUtil.isNotBlank(query.getHostId()) ,DataRelation::getHostId ,query.getHostId());
        queryWrapper.like(StrUtil.isNotBlank(query.getRelationId()) ,DataRelation::getRelationId ,query.getRelationId());
        return queryWrapper;
    }
}
