package cn.cslg.pas.service;

import cn.cslg.pas.domain.SystemDictAssociate;
import cn.cslg.pas.mapper.SystemDictAssociateMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

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

/**
 * @author 沈永艺
 * @date 2022.6.22
 * @description 获取字典项 （应用场景 与 调查类型） 的业务逻辑处理层
 */

@Service
public class SystemDictAssociateService extends ServiceImpl<SystemDictAssociateMapper, SystemDictAssociate> {
    /**
     * @param value 父项（应用场景） 参数 Value 值
     * @param type  字典项（应用场景） Key 值
     * @param flag  查询标记 1为in操作查询 0为 notIn操作查询
     * @return 返回一个 SystemDictAssociate 类型的 List
     * @author 沈永艺
     * @date 2022.6.21
     * @description 通过传入Value值参数 以及Type（Key） 值 对 应用场景和调查类型之间的关联关系做业务查询
     */
    public List<SystemDictAssociate> getDictTreeByParentDictValue(List<String> value, String type, Integer flag) {
        LambdaQueryWrapper<SystemDictAssociate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(SystemDictAssociate::getDictChildLabel, SystemDictAssociate::getDictChildType, SystemDictAssociate::getDictChildValue);
        List<SystemDictAssociate> systemDictAssociateList;

        if (flag == 1) {
            if (value == null || value.isEmpty()) {
                return new ArrayList<>();
            }
            queryWrapper.in(SystemDictAssociate::getDictParentValue, value).eq(SystemDictAssociate::getDictParentType, type);
        } else if (flag == 0) {
            LambdaQueryWrapper<SystemDictAssociate> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.select(SystemDictAssociate::getDictChildLabel, SystemDictAssociate::getDictChildType, SystemDictAssociate::getDictChildValue);
            queryWrapper1.in(SystemDictAssociate::getDictParentValue, value).eq(SystemDictAssociate::getDictParentType, type);
            List<SystemDictAssociate> systemDictAssociateList1 = this.list(queryWrapper1).stream().distinct().collect(Collectors.toList());

            queryWrapper.notIn(SystemDictAssociate::getDictParentValue, value).eq(SystemDictAssociate::getDictParentType, type);
            List<SystemDictAssociate> systemDictAssociateList2 = this.list(queryWrapper).stream().distinct().collect(Collectors.toList());

            for (int i = 0; i < systemDictAssociateList1.size(); i++) {
                for (int j = 0; j < systemDictAssociateList2.size(); j++) {
                    int finalI = i;
                    systemDictAssociateList2.removeIf(a -> a.getDictChildLabel().equals(systemDictAssociateList1.get(finalI).getDictChildLabel()));
                }
            }

            return systemDictAssociateList2;
        }
        systemDictAssociateList = this.list(queryWrapper).stream().distinct().collect(Collectors.toList());
        return systemDictAssociateList;
    }

}