package com.zcloud.basic.info.command.query;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.PageResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.zcloud.basic.info.command.convertor.DepartmentCoConvertor;
import com.zcloud.basic.info.domain.enums.CommonFlagEnum;
import com.zcloud.basic.info.domain.enums.CorpTypeEnum;
import com.zcloud.basic.info.dto.*;
import com.zcloud.basic.info.dto.clientobject.*;
import com.zcloud.basic.info.persistence.dataobject.DepartmentDO;
import com.zcloud.basic.info.persistence.repository.CorpInfoRepository;
import com.zcloud.basic.info.persistence.repository.DepartmentRepository;
import com.zcloud.basic.info.persistence.repository.DepartmentSuperviseRepository;
import com.zcloud.basic.info.persistence.repository.UserRepository;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import com.zcloud.gbscommon.utils.Tools;
import com.zcloud.gbscommon.zclouddepartment.face.ZcloudDepartmentFacade;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

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


/**
 * web-app
 *
 * @Author zhaokai
 * @Date 2025-10-29 16:03:20
 */
@Component
@AllArgsConstructor
public class DepartmentQueryExe {
    private final DepartmentRepository departmentRepository;
    private final DepartmentCoConvertor departmentCoConvertor;
    private final DepartmentSuperviseRepository departmentSuperviseRepository;
    private final UserRepository userRepository;
    private final CorpInfoRepository corpInfoRepository;
    @DubboReference
    private ZcloudDepartmentFacade zcloudDepartmentFacade;

    /**
     * 分页
     *
     * @param departmentPageQry
     * @return
     */
    public PageResponse<DepartmentCO> execute(DepartmentPageQry departmentPageQry) {
        if (departmentPageQry.getEqCorpinfoId() == null) {
            departmentPageQry.setEqCorpinfoId(AuthContext.getTenantId());
        }
        if(departmentPageQry.getEqParentId() == null){
            departmentPageQry.setEqParentId(AuthContext.getTenantId());
        }
        Map<String, Object> parmas = PageQueryHelper.toHashMap(departmentPageQry);
        PageResponse<DepartmentDO> pageResponse = departmentRepository.listPage(parmas);
        List<DepartmentCO> examCenterCOS = departmentCoConvertor.converDOsToCOs(pageResponse.getData());
        if (CollUtil.isEmpty(examCenterCOS)) {
            return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        //获取所有的部门id
        List<Long> departmentIds = examCenterCOS.stream().map(DepartmentCO::getId).collect(Collectors.toList());
        //获取所有部门的负责人
        Map<Long, String> departmentLeaderMap = userRepository.getDepartmentLeaderByDepartmentId(departmentIds);
        if (CollUtil.isNotEmpty(departmentLeaderMap)) {
            examCenterCOS.forEach(examCenterCO -> {
                examCenterCO.setDepartmentUserLeaderList(departmentLeaderMap.getOrDefault(examCenterCO.getId(), StringUtils.EMPTY));
            });
        }

        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<DepartmentTreeInfoCO> listTree(DepartmentTreeQry departmentQry) {
        if (Objects.isNull(departmentQry.getEqCorpinfoId())) {
            departmentQry.setEqCorpinfoId(AuthContext.getTenantId());
        }
        Map<String, Object> parmas = PageQueryHelper.toHashMap(departmentQry);
        List<DepartmentDO> pageResponse = departmentRepository.listTree(parmas);
        if (CollUtil.isEmpty(pageResponse)) {
            return Collections.emptyList();
        }
        List<DepartmentTreeInfoCO> examCenterCOS = departmentCoConvertor.converDOsToInfoCOs(pageResponse);
        //补充企业信息
        //补充企业名称
        Map<Long, String> corpinfoMap = corpInfoRepository.getCorpinfoNameByCorpinfoId(examCenterCOS.stream().map(DepartmentTreeInfoCO::getCorpinfoId).collect(Collectors.toList()));
        if (CollUtil.isNotEmpty(corpinfoMap)) {
            List<Long> departmentIds = examCenterCOS.stream().peek(examCenterCO -> {
                examCenterCO.setCorpinfoName(corpinfoMap.getOrDefault(examCenterCO.getCorpinfoId(), StringUtils.EMPTY));
            }).map(DepartmentTreeInfoCO :: getId).collect(Collectors.toList());
            Map<Long, String> deptMap = zcloudDepartmentFacade.listFullName(departmentIds);
            examCenterCOS.forEach(examCenterCO -> {
                examCenterCO.setFullName(deptMap.getOrDefault(examCenterCO.getId(), StringUtils.EMPTY));
            });
        }
        //GBS部门根节点父部门是tenantId
        if(departmentQry.getEqParentId()!=null){
            return Tools.buildEntityTree(examCenterCOS, "id", "parentId", "childrenList",departmentQry.getEqParentId());

        }else{
            return Tools.buildEntityTree(examCenterCOS, "id", "parentId", "childrenList",0L);

        }
    }


    public DepartmentInfoCO info(Long id) {
        DepartmentDO info = departmentRepository.getById(id);
        if (info == null) {
            return null;
        }

        DepartmentInfoCO departmentCO = new DepartmentInfoCO();
        BeanUtils.copyProperties(info, departmentCO);

        // 获取父部门名称
        if (departmentCO.getParentId() != null) {
            DepartmentDO departmentDO = departmentRepository.getById(departmentCO.getParentId());
            if (departmentDO != null) {
                departmentCO.setParentName(departmentDO.getName());
            }
        }
        if (CommonFlagEnum.YES.getCode().equals(departmentCO.getSuperviseFlag())) {
//            departmentSuperviseRepository
            DepartmentSupervisePageQry qry = new DepartmentSupervisePageQry();
            qry.setEqSuperviseDepartmentId(id);
            Map<String, Object> params = PageQueryHelper.toHashMap(qry);
            List<Long> postDepartmentDOS = departmentSuperviseRepository.listBySuperviseDepartmentId(params);
            if (CollUtil.isNotEmpty(postDepartmentDOS)) {
                departmentCO.setDepartmentIdsList(postDepartmentDOS);
            }
        }

        return departmentCO;
    }


    public List<DepartmentCO> listByDepartIds(Collection<Long> collection) {
        QueryWrapper<DepartmentDO> dOQueryWrapper = new QueryWrapper<>();
        dOQueryWrapper.in("id", collection);
        List<DepartmentDO> list = departmentRepository.list(dOQueryWrapper);
        return departmentCoConvertor.converDOsToCOs(list);
    }

    public List<DepartmentCO> getDeptList() {
        List<DepartmentDO> list = departmentRepository.list();
        return departmentCoConvertor.converDOsToCOs(list);
    }

    public List<DepartmentTreeInfoCO> listAllTree() {
        List<DepartmentDO> pageResponse = departmentRepository.listAllTree();
        if (CollUtil.isEmpty(pageResponse)) {
            return Collections.emptyList();
        }
        List<DepartmentTreeInfoCO> result2 = getDepartmentAllTree(pageResponse);
        return result2;
    }

    private List<DepartmentTreeInfoCO> getDepartmentAllTree(List<DepartmentDO> pageResponse) {
        List<DepartmentTreeInfoCO> examCenterCOS = departmentCoConvertor.converDOsToInfoCOs(pageResponse);
        Map<Long, String> corpinfoMap = corpInfoRepository.getCorpinfoNameByCorpinfoId(examCenterCOS.stream().map(DepartmentTreeInfoCO::getCorpinfoId).distinct().collect(Collectors.toList()));
        if (CollUtil.isNotEmpty(corpinfoMap)) {
            List<Long> departmentIds = examCenterCOS.stream().peek(examCenterCO -> {
                examCenterCO.setCorpinfoName(corpinfoMap.getOrDefault(examCenterCO.getCorpinfoId(), StringUtils.EMPTY));
            }).map(DepartmentTreeInfoCO :: getId).collect(Collectors.toList());
            Map<Long, String> deptMap = zcloudDepartmentFacade.listFullName(departmentIds);
            examCenterCOS.forEach(examCenterCO -> {
                examCenterCO.setFullName(deptMap.getOrDefault(examCenterCO.getId(), StringUtils.EMPTY));
            });
        }
        //GBS部门根节点父部门是tenantId
        //按照企业分组
        List<List<DepartmentTreeInfoCO>> result1= new ArrayList<>();
        List<DepartmentTreeInfoCO> result2= new ArrayList<>();
//        Map<Long, List<DepartmentTreeInfoCO>> corpMap = examCenterCOS.stream().collect(Collectors.groupingBy(DepartmentTreeInfoCO::getCorpinfoId));
//        corpMap.forEach((corpId, list) -> {
            List<DepartmentTreeInfoCO> departmentTreeInfoCOS = Tools.buildEntityTree(examCenterCOS, "id", "parentId", "childrenList", 0L);
            if(CollUtil.isNotEmpty(departmentTreeInfoCOS)){
                result2.addAll(departmentTreeInfoCOS);
            }
//        });
        return result2;
    }

    public Collection<DepartmentTreeInfoCO> listAllTreeByCorpType(DepartmentTreeQry qry) {
        Map<String, Object> parmas = PageQueryHelper.toHashMap(qry);
        List<Integer> enterpriseType =CorpTypeEnum.getCodesByEnterpriseType(qry.getEnterpriseType());
        if (CollUtil.isNotEmpty(enterpriseType)) {
            parmas.put("inType",enterpriseType);
        }
        List<DepartmentDO> pageResponse = departmentRepository.listAllTreeByCorpType(parmas);
        if (CollUtil.isEmpty(pageResponse)) {
            return Collections.emptyList();
        }
        List<DepartmentTreeInfoCO> result2 = getDepartmentAllTree(pageResponse);
        return result2;
    }


    public Collection<DepartmentTreeInfoCO> listTreeNopermission(DepartmentTreeQry departmentQry) {
         if (Objects.isNull(departmentQry.getEqCorpinfoId())) {
            throw new RuntimeException("请选择企业");
        }
        Map<String, Object> parmas = PageQueryHelper.toHashMap(departmentQry);
        List<DepartmentDO> pageResponse = departmentRepository.listTree(parmas);
        if (CollUtil.isEmpty(pageResponse)) {
            return Collections.emptyList();
        }
        List<DepartmentTreeInfoCO> examCenterCOS = departmentCoConvertor.converDOsToInfoCOs(pageResponse);
        //补充企业信息
        //补充企业名称
        Map<Long, String> corpinfoMap = corpInfoRepository.getCorpinfoNameByCorpinfoId(examCenterCOS.stream().map(DepartmentTreeInfoCO::getCorpinfoId).collect(Collectors.toList()));
        if (CollUtil.isNotEmpty(corpinfoMap)) {
            List<Long> departmentIds = examCenterCOS.stream().peek(examCenterCO -> {
                examCenterCO.setCorpinfoName(corpinfoMap.getOrDefault(examCenterCO.getCorpinfoId(), StringUtils.EMPTY));
            }).map(DepartmentTreeInfoCO :: getId).collect(Collectors.toList());
            Map<Long, String> deptMap = zcloudDepartmentFacade.listFullName(departmentIds);
            examCenterCOS.forEach(examCenterCO -> {
                examCenterCO.setFullName(deptMap.getOrDefault(examCenterCO.getId(), StringUtils.EMPTY));
            });
        }
        //GBS部门根节点父部门是tenantId
        if(departmentQry.getEqParentId()!=null){
            return Tools.buildEntityTree(examCenterCOS, "id", "parentId", "childrenList",departmentQry.getEqParentId());

        }else{
            return Tools.buildEntityTree(examCenterCOS, "id", "parentId", "childrenList",0L);

        }

    }
}

