package com.engine.organization.entity.department.bo;

import com.engine.organization.entity.department.dto.DepartmentListDTO;
import com.engine.organization.entity.department.param.DeptSearchParam;
import com.engine.organization.entity.department.po.DepartmentPO;
import com.engine.organization.entity.department.vo.SingleDeptTreeVO;
import com.engine.organization.entity.searchtree.SearchTree;
import com.engine.organization.mapper.comp.CompMapper;
import com.engine.organization.mapper.department.DepartmentMapper;
import com.engine.organization.mapper.employee.EmployeeMapper;
import com.engine.organization.util.db.MapperProxyFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import weaver.general.Util;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author weaver_cl
 * @description:
 * @Date 2022/5/20
 * @Version V1.0
 **/
public class DepartmentBO {

    public static List<DepartmentListDTO> buildDeptDTOList(Collection<DepartmentPO> list) {

        // 递归添加父级数据
        Map<Integer, DepartmentPO> poMaps = list.stream().collect(Collectors.toMap(DepartmentPO::getId, item -> item));
        List<DepartmentListDTO> dtoList = list.stream().map(e ->
                DepartmentListDTO
                        .builder()
                        .id(e.getId())
                        .departmentMark(e.getDepartmentMark())
                        .departmentName(e.getDepartmentName())
                        .departmentCode(e.getDepartmentCode())
                        .subCompanyId1(e.getSubCompanyId1())
                        .subCompanyName(0 == e.getSubCompanyId1() ? "" : MapperProxyFactory.getProxy(CompMapper.class).listById(e.getSubCompanyId1()).getSubCompanyName())
                        .supDepId(e.getSupDepId())
                        .supDepName(null == poMaps.get(e.getSupDepId()) ? "" : poMaps.get(e.getSupDepId()).getDepartmentName())
                        .bmfzr(getEmployeeNameById(e.getId()))
                        .showOrder(null == e.getShowOrder() ? 0 : e.getShowOrder())
                        .canceled(null == e.getCanceled() ? 0 : e.getCanceled())
                        .build()).collect(Collectors.toList());
        Map<Integer, List<DepartmentListDTO>> collects = dtoList.stream().filter(item -> null != item.getSupDepId() && 0 != item.getSupDepId()).collect(Collectors.groupingBy(DepartmentListDTO::getSupDepId));
        // 处理被引用数据
        List<String> usedIds = MapperProxyFactory.getProxy(DepartmentMapper.class).listUsedId();
        List<String> collect = Arrays.stream(String.join(",", usedIds).split(",")).collect(Collectors.toList());
        return dtoList.stream().peek(e -> {
            List<DepartmentListDTO> childList = collects.get(e.getId());
            if (CollectionUtils.isNotEmpty(childList)) {
                e.setChildren(childList);
                e.setIsUsed(1);
            } else {
                if (collect.contains(Util.null2String(e.getId()))) {
                    e.setIsUsed(1);
                } else {
                    e.setIsUsed(0);
                }
            }
        }).filter(item -> null == item.getSupDepId() || 0 == item.getSupDepId()).collect(Collectors.toList());
    }

    public static List<DepartmentListDTO> buildDeptDTOList(Collection<DepartmentPO> list, List<DepartmentPO> filterList) {
        // 搜索结果为空，直接返回空
        if (CollectionUtils.isEmpty(filterList)) {
            return Collections.emptyList();
        }
        // 递归添加父级数据
        Map<Integer, DepartmentPO> poMaps = list.stream().collect(Collectors.toMap(DepartmentPO::getId, item -> item));
        List<DepartmentPO> addedList = new ArrayList<>();
        for (DepartmentPO po : filterList) {
            dealParentData(addedList, po, poMaps);
        }
        return buildDeptDTOList(addedList);
    }

    public static DepartmentPO convertParamsToPO(DeptSearchParam param, Integer employeeId) {
        if (null == param) {
            return null;
        }
        return DepartmentPO
                .builder()
                .id(param.getId() == null ? 0 : param.getId())
                .departmentId(param.getDepartmentId())
                .departmentMark(param.getDepartmentMark())
                .departmentName(param.getDepartmentName())
                .subCompanyId1(param.getSubCompanyId1())
                .supDepId(param.getSupDepId())
                .allSupDepId(param.getAllSupDepId())
                .canceled(param.getCanceled() == null ? null : param.getCanceled() ? 0 : 1)
                .departmentCode(param.getDepartmentCode())
                .coadjutant(param.getCoadjutant())
                .uuid(param.getUuid())
                .showOrder(param.getShowOrder())
                .showOrderOfTree(param.getShowOrderOfTree())
                .created(new Date())
                .modified(new Date())
                .creater(employeeId)
                .modifier(employeeId)
                .build();
    }

    public static List<SingleDeptTreeVO> buildSingleDeptTreeVOS(List<DepartmentPO> departmentPOs, Integer parentComp) {

        if (CollectionUtils.isEmpty(departmentPOs)) {
            return Collections.emptyList();
        }

        List<SingleDeptTreeVO> singleDeptTreeVOS = departmentPOs.stream().map(e ->
                SingleDeptTreeVO
                        .builder()
                        .id(e.getId())
                        .departmentCode(e.getDepartmentCode())
                        .departmentMark(e.getDepartmentMark())
                        .subCompanyId1(e.getSubCompanyId1())
                        .supDepId(e.getSupDepId())
                        .supDepName(null == e.getSupDepId() || e.getSupDepId() == 0 ? "" : getDeptNameById(e.getSupDepId()))
                        //.deptPrincipalName(getEmployeeNameById(e.getDeptPrincipal()))
                        .build()).collect(Collectors.toList());
        //获取非一级部门
        Map<Integer, List<SingleDeptTreeVO>> collects = singleDeptTreeVOS.stream().filter(item -> !parentComp.equals(item.getSubCompanyId1()) && null != item.getSupDepId() && 0 != item.getSupDepId()).collect(Collectors.groupingBy(SingleDeptTreeVO::getSupDepId));

        return singleDeptTreeVOS.stream().peek(e -> e.setChildren(collects.get(e.getId()))).filter(item -> parentComp.equals(item.getSubCompanyId1())).collect(Collectors.toList());
    }

    public static List<SearchTree> buildSetToSearchTree(Set<DepartmentPO> departmentPOS) {
        return buildSetToSearchTree(departmentPOS, true);
    }


    public static List<SearchTree> buildSetToSearchTree(Set<DepartmentPO> departmentPOS, boolean isLeaf) {
        return departmentPOS.stream().map(item -> {
            SearchTree tree = new SearchTree();
            tree.setCanClick(true);
            tree.setCanceled(item.getCanceled() != null && item.getCanceled() != 0);
            tree.setIcon(isLeaf ? "icon-coms-Branch" : "icon-coms-LargeArea");
            tree.setId(item.getId().toString());
            tree.setIsParent(false);
            tree.setIsVirtual("0");
            tree.setName(item.getDepartmentName());
            tree.setPid(null == item.getSupDepId() ? "0" : item.getSupDepId().toString());
            tree.setSelected(false);
            tree.setType("2");
            tree.setParentComp(item.getSubCompanyId1().toString());
            tree.setOrderNum(null == item.getShowOrder() ? 0 : item.getShowOrder().intValue());
            return tree;
        }).collect(Collectors.toList());
    }


    public static String getDeptNameById(Integer id) {
        return MapperProxyFactory.getProxy(DepartmentMapper.class).getDeptNameById(id);
    }

    public static String getEmployeeNameById(Integer id) {
        if (null == id) {
            return "";
        }
        String departmentPrincipal = MapperProxyFactory.getProxy(DepartmentMapper.class).getDepartmentPrincipal(id);
        if (StringUtils.isBlank(departmentPrincipal)) {
            return "";
        }
        List<Long> collect = Arrays.stream(departmentPrincipal.split(",")).map(Long::parseLong).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            return "";
        }
        List<String> employeeNameById = MapperProxyFactory.getProxy(EmployeeMapper.class).getEmployeeNameById(collect);
        return StringUtils.join(employeeNameById, ",");
    }


    /**
     * 递归获取查询后数据的父级数据
     *
     * @param addedList
     * @param po
     * @param poMaps
     */
    private static void dealParentData(List<DepartmentPO> addedList, DepartmentPO po, Map<Integer, DepartmentPO> poMaps) {
        if (!addedList.contains(po)) {
            addedList.add(po);
        }
        DepartmentPO parentPO = poMaps.get(po.getSupDepId());
        if (null != parentPO) {
            dealParentData(addedList, parentPO, poMaps);
        }
    }


}
