package com.persagy.dmp.rwd.simple.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.persagy.dmp.common.constant.CommonConstant;
import com.persagy.dmp.digital.entity.ObjectRelation;
import com.persagy.dmp.rwd.digital.service.IObjectRelationService;
import com.persagy.dmp.rwd.simple.domain.CountRequestData;
import com.persagy.dmp.rwd.simple.service.RelationReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class RelationReportServiceImpl implements RelationReportService {

    private final IObjectRelationService objectRelationService;

    /***
     * Description: 根据对象id统计关系数量
     * @param requestData : 请求参数
     * @author : lijie
     * @date :2021/10/28 10:16
     * Update By lijie 2021/10/28 10:16
     */
    @Override
    public List<ObjectRelation> queryRelationCountByObjIds(CountRequestData requestData) {
        QueryWrapper<ObjectRelation> groupWrapper = new QueryWrapper<>();
        groupWrapper.eq(ObjectRelation.PROP_VALID,Boolean.TRUE);
        groupWrapper.in(CollUtil.isNotEmpty(requestData.getIds()),ObjectRelation.PROP_ID,requestData.getIds());
        groupWrapper.in(CollUtil.isNotEmpty(requestData.getGraphCodes()),
                StrUtil.toUnderlineCase(ObjectRelation.GRAPH_CODE_HUM),requestData.getGraphCodes());
        groupWrapper.in(CollUtil.isNotEmpty(requestData.getProjectIds()),
                StrUtil.toUnderlineCase(CommonConstant.QUERY_PROJECTID),requestData.getProjectIds());
        groupWrapper.in(CollUtil.isNotEmpty(requestData.getObjFromIds()),ObjectRelation.OBJ_FROM,requestData.getObjFromIds());
        groupWrapper.in(CollUtil.isNotEmpty(requestData.getObjToIds()),ObjectRelation.OBJ_TO,requestData.getObjToIds());
        groupWrapper.in(CollUtil.isNotEmpty(requestData.getRelCodes()),
                StrUtil.toUnderlineCase(ObjectRelation.REL_CODE_HUM),requestData.getRelCodes());
        groupWrapper.in(CollUtil.isNotEmpty(requestData.getRelValues()),
                StrUtil.toUnderlineCase(ObjectRelation.REL_VALUE_HUM),requestData.getRelValues());
        List<String> groups = requestData.getGroups();
        String[] selectFields = groups.stream().map(StrUtil::toUnderlineCase).collect(Collectors.toList()).toArray(new String[groups.size() + 1]);
        selectFields[groups.size()]="COUNT(id) AS count";
        groupWrapper.select(selectFields);
        groupWrapper.groupBy(groups.stream().map(StrUtil::toUnderlineCase).collect(Collectors.joining(StrUtil.COMMA)));
        return CollUtil.defaultIfEmpty(objectRelationService.list(groupWrapper),CollUtil.newArrayList());
    }
}
