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

import com.engine.organization.entity.job.dto.JobListDTO;
import com.engine.organization.entity.job.param.JobSearchParam;
import com.engine.organization.entity.job.po.JobPO;
import com.engine.organization.entity.job.vo.SingleJobTreeVO;
import com.engine.organization.entity.searchtree.SearchTree;
import com.engine.organization.mapper.job.JobMapper;
import com.engine.organization.transmethod.JobTransMethod;
import com.engine.organization.util.db.MapperProxyFactory;
import org.apache.commons.collections.CollectionUtils;
import weaver.general.Util;
import weaver.hrm.job.JobTitlesComInfo;

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

/**
 * @description:
 * @author:dxfeng
 * @createTime: 2022/05/30
 * @version: 1.0
 */
public class JobBO {

    public static JobPO convertParamsToPO(JobSearchParam param, long employeeId) {
        if (null == param) {
            return null;
        }
        return JobPO
                .builder()
                .id(param.getId() == null ? 0 : param.getId())
                .jobNo(param.getJobNo())
                .jobTitleName(param.getJobTitleName())
                .ecJobTitle(param.getEcJobTitle())
                .ecCompany(param.getSubcompanyid1())
                .ecDepartment(param.getDepartmentid())
                .sequenceId(param.getSequenceId())
                .schemeId(param.getSchemeId())
                .parentJob(param.getParentJob())
                .isKey(param.getIsKey())
                .workplace(param.getWorkplace())
                .description(param.getDescription())
                .workDuty(param.getWorkDuty())
                .workAuthority(param.getWorkAuthority())
                .showOrder(param.getShowOrder())
                .forbiddenTag(param.getForbiddenTag() == null ? null : param.getForbiddenTag() ? 0 : 1)
                .deleteType(0)
                .createTime(new Date())
                .updateTime(new Date())
                .creator(employeeId)
                .build();
    }


    public static List<SingleJobTreeVO> buildSingleJobTreeVOS(List<JobPO> jobPOS, Integer parentDept) {
        if (CollectionUtils.isEmpty(jobPOS)) {
            return Collections.emptyList();
        }
        Map<Long, JobPO> poMaps = jobPOS.stream().collect(Collectors.toMap(JobPO::getId, item -> item));

        List<SingleJobTreeVO> singleJobTreeVOS = jobPOS.stream().map(e ->
                SingleJobTreeVO
                        .builder()
                        .id(e.getId())
                        .jobNo(e.getJobNo())
                        .jobName(e.getJobTitleName())
                        //.parentJobName(null == poMaps.get(e.getParentJob()) ? "" : poMaps.get(e.getParentJob()).getJobTitleName())
                        .parentJob(e.getParentJob())
                        .parentDept(e.getEcDepartment())
                        .build()).collect(Collectors.toList());
        //获取非一级部门
        Map<Long, List<SingleJobTreeVO>> collects = singleJobTreeVOS.stream().filter(item -> null != item.getParentJob()).collect(Collectors.groupingBy(SingleJobTreeVO::getParentJob));

        return singleJobTreeVOS.stream().peek(e -> e.setChildren(collects.get(e.getId()))).filter(item -> parentDept.equals(item.getParentDept()) && null == item.getParentJob()).collect(Collectors.toList());
    }


    public static List<JobListDTO> buildDTOList(Collection<JobListDTO> list) {
        // 递归添加父级数据
        List<JobListDTO> dtoList = list.stream().map(e ->
                JobListDTO.builder()
                        .id(e.getId())
                        .jobNo(e.getJobNo())
                        .jobTitleName(e.getJobTitleName())
                        .subCompanyName(e.getSubCompanyName())
                        .departmentName(e.getDepartmentName())
                        //.sequenceName(e.getSequenceName())
                        //.schemeName(e.getSchemeName())
                        //.parentJob(e.getParentJob())
                        //.parentJobName(null == poMaps.get(e.getParentJob()) ? "" : poMaps.get(e.getParentJob()).getJobName())
                        .isKey(JobTransMethod.getIsKeySpan(e.getIsKey()))
                        .showOrder(e.getShowOrder())
                        //.forbiddenTag(e.getForbiddenTag())
                        .isUsed(0)
                        .build()).collect(Collectors.toList());
        List<String> usedIds = MapperProxyFactory.getProxy(JobMapper.class).listUsedId();
        Map<Long, List<JobListDTO>> collects = dtoList.stream().filter(item -> null != item.getParentJob() && 0 != item.getParentJob()).collect(Collectors.groupingBy(JobListDTO::getParentJob));
        return dtoList.stream().peek(e -> {
            List<JobListDTO> childList = collects.get(e.getId());
            if (CollectionUtils.isNotEmpty(childList)) {
                e.setChildren(childList);
                e.setIsUsed(1);
            }else{
                if (usedIds.contains(Util.null2String(e.getId()))) {
                    e.setIsUsed(1);
                } else {
                    e.setIsUsed(0);
                }
            }
        }).filter(item -> null == item.getParentJob() || 0 == item.getParentJob()).collect(Collectors.toList());
    }


    public static List<JobListDTO> buildJobDTOList(List<JobListDTO> allList, List<JobListDTO> filterJobPOs) {
        // 搜索结果为空，直接返回空
        if (CollectionUtils.isEmpty(filterJobPOs)) {
            return Collections.emptyList();
        }
        // 递归添加父级数据
        Map<Long, JobListDTO> poMaps = allList.stream().collect(Collectors.toMap(JobListDTO::getId, item -> item));
        List<JobListDTO> addedList = new ArrayList<>();
        for (JobListDTO dto : filterJobPOs) {
            dealParentData(addedList, dto, poMaps);
        }
        // 递归添加父级数据
        return buildDTOList(addedList);

    }

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

    public static List<SearchTree> buildSetToSearchTree(Set<JobPO> builderJobs) {
        return builderJobs.stream().map(item -> {
            SearchTree tree = new SearchTree();
            tree.setCanClick(true);
            tree.setCanceled(item.getForbiddenTag() != 0);
            tree.setIcon("icon-coms-content-o");
            tree.setId(item.getId().toString());
            tree.setIsParent(false);
            tree.setIsVirtual("0");
            tree.setName(item.getJobTitleName());
            tree.setPid(null == item.getParentJob() ? "0" : item.getParentJob().toString());
            tree.setSelected(false);
            tree.setType("3");
            tree.setParentComp(null == item.getEcDepartment() ? "0" : item.getEcDepartment().toString());
            tree.setOrderNum(null == item.getShowOrder() ? 0 : item.getShowOrder());
            return tree;
        }).collect(Collectors.toList());

    }

    public static String getJobTitleNameByEcJobTitle(String ecJobTitle) {
        return new JobTitlesComInfo().getJobTitlesname(ecJobTitle);
    }

    public static JobPO getEcJobTitleByJobId(Long jobId) {
        if (null == jobId) {
            return null;
        }
        return MapperProxyFactory.getProxy(JobMapper.class).getJobById(jobId);
    }
}
