package com.xjrsoft.module.organization.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.organization.dto.WeChatDepartPageDto;
import com.xjrsoft.module.organization.entity.Department;
import com.xjrsoft.module.organization.mapper.DepartmentMapper;
import com.xjrsoft.module.organization.service.IDepartmentService;
import com.xjrsoft.module.organization.vo.DepartmentTreeVo;
import com.xjrsoft.module.organization.vo.WeChatDepartPageVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 机构 服务实现类
 * </p>
 *
 * @author tzx
 * @since 2022-03-02
 */
@Service
@AllArgsConstructor
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    private final DepartmentMapper departmentMapper;
    @Override
    public Object Ipage(WeChatDepartPageDto dto) {
        LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(dto.getKeyword()),Department::getName,dto.getKeyword())
                .select(Department.class,x -> VoToColumnUtil.fieldsToColumns(WeChatDepartPageVO.class).contains(x.getProperty()));
        IPage<Department> page = departmentMapper.selectPage(ConventPage.getPage(dto), queryWrapper);
        List<Department> records = page.getRecords();
        for (Department record : records) {
            record.setRemark("部门更新成功");
            record.setSortCode(1);
        }
        PageOutput<WeChatDepartPageVO> pageOutput = ConventPage.getPageOutput(page, WeChatDepartPageVO.class);
        return pageOutput;
    }

    /**
     * 获取所有的子集id
     * @param deptIds
     * @param voList
     * @return
     */
    @Override
    public List<Long> getAllChildIds(List<Long> deptIds, List<DepartmentTreeVo> voList) {
        List<Long> ids = new ArrayList<>();
        for (Long deptId : deptIds) {
            if (voList.stream().anyMatch(x -> x.getParentId().equals(deptId))){
                List<DepartmentTreeVo> child = voList.stream().filter(x -> x.getParentId().equals(deptId)).collect(Collectors.toList());
                List<Long> allChildId = child.stream().map(DepartmentTreeVo::getId).collect(Collectors.toList());
                List<Long> allChildId1= getAllChildIds(allChildId, voList);
                ids.addAll(allChildId);
                ids.addAll(allChildId1);
            }
        }
        return ids;
    }
}
