package cn.com.oa.service.impl;

import cn.com.oa.mapper.GroupMapper;
import cn.com.oa.model.Company;
import cn.com.oa.model.Group;
import cn.com.oa.model.vo.GroupVo;
import cn.com.oa.service.ICompanyService;
import cn.com.oa.service.IGroupService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group> implements IGroupService {
    @Autowired
    private ICompanyService companyService;
    @Override
    public Group getDefaultGroup() {
        Company company = companyService.getCompany();
        LambdaQueryWrapper<Group> lambdaQueryWrapper=new LambdaQueryWrapper<Group>();
        lambdaQueryWrapper.eq(Group::getCompanyId, company.getUNIVERSALID())
                .eq(Group::getState,"1")
                .eq(Group::getGlevel,"2");
        return baseMapper.selectOne(lambdaQueryWrapper);
    }

    public Group buildOrgStructure(Long rootId) {
        LambdaQueryWrapper<Group> lambdaQueryWrapper=new LambdaQueryWrapper<Group>();
        lambdaQueryWrapper.eq(Group::getUNIVERSALID, rootId);
        Group rootGroup = baseMapper.selectOne(lambdaQueryWrapper);
        if (rootGroup != null) {
            List<Group> children = new ArrayList<>();
            List<Group> subGroups = findAllByPid(rootGroup.getUNIVERSALID().toString());
            for (Group subGroup : subGroups) {
                children.add(buildOrgStructure(subGroup.getUNIVERSALID())); // 递归调用
            }
            rootGroup.setChildren(children);
        }
        return rootGroup;
    }


    public List<Group> findAllByPid(String pid) {
        LambdaQueryWrapper<Group> lambdaQueryWrapper=new LambdaQueryWrapper<Group>();
        lambdaQueryWrapper.eq(Group::getPID, pid).eq(Group::getState,"1");
        return baseMapper.selectList(lambdaQueryWrapper);
    }
}
