/**
 * Copyright &copy; 2021-2026 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.sys.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.core.service.TreeService;
import com.jeeplus.sys.constant.CommonConstants;
import com.jeeplus.sys.constant.enums.OfficeTypeEnum;
import com.jeeplus.sys.domain.Office;
import com.jeeplus.sys.mapper.OfficeMapper;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.mapstruct.OfficeWrapper;
import com.jeeplus.sys.utils.UserUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 机构Service
 * @author jeeplus
 * @version 2021-05-16
 */
@Service
@Transactional
public class OfficeService extends TreeService<OfficeMapper, Office> {

    @Autowired
    private OfficeWrapper officeWrapper;

    @Autowired
    private OfficeMapper officeMapper;

    public List <OfficeDTO> getRootTree(List<OfficeDTO> list, String extId, String type, String showAll, String showMyOffice) {
        List<OfficeDTO> offices = Lists.newArrayList ();
        // 获取到所有parent_id为‘0’的部门数据
        List<OfficeDTO> rootTrees = officeWrapper.toDTO (super.getChildren (new Office (OfficeDTO.getRootId ())));
        for (OfficeDTO root : rootTrees) {
            if (this.isUseAble ( extId, type,root, showAll )){
                // 不是被排除节点的子节点
                List<OfficeDTO> officeList = formatListToTree (root, list, extId, type, showAll);
                offices.addAll (officeList);
            }
        }
        if (com.jeeplus.sys.utils.StringUtils.isNotBlank(showMyOffice)) {
            OfficeDTO officeDTO = UserUtils.getCurrentUserDTO().getOfficeDTO();
            // 排除管理员
            if (!UserUtils.getCurrentUserDTO().isAdmin()){
                if (StringUtils.isNotBlank(officeDTO.getParentIds())) {
                    String[] split = officeDTO.getParentIds().split(",");
                    if (split.length > 2) {
                        Office office = officeMapper.selectById(split[2]);
                        if ("0".equals(office.getIsPublic())) {
                            // isPublic为“0”，当前用户的公司为私有，查询的部门包含自己所属公司全部部门和其他的公有部门
                            if(null != officeDTO && StringUtils.isNotBlank(officeDTO.getParentIds())){
                                offices = this.getCompanyFromTree(offices);
                            }
                        }
                    } else {
                        if ("0".equals(officeDTO.getIsPublic())) {
                            // isPublic为“0”，当前用户的公司为私有，查询的部门包含自己所属公司全部部门和其他的公有部门
                            if(null != officeDTO && StringUtils.isNotBlank(officeDTO.getParentIds())){
                                offices = this.getCompanyFromTree(offices);
                            }
                        }
                    }
                }
            }
        }
        return offices;
    }

    /**
     * 在tree数据中找到当前登录人的“集团”以及“公司”
     */
    public List<OfficeDTO> getCompanyFromTree(List<OfficeDTO> rootTrees){
        // 当前登录人的集团id
        String corporationId = UserUtils.getCurrentUserDTO().getCompanyDTO().getId();
        // 公司id
        String parentIds = officeMapper.selectById(UserUtils.getCurrentUserDTO().getOfficeDTO().getId()).getParentIds();
        String companyId = null;
        String[] split = parentIds.split(",");
        if(split.length>2){
            companyId = split[2];
        }else{
            companyId = UserUtils.getCurrentUserDTO().getOfficeDTO().getId();
        }
        List<OfficeDTO> os = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(rootTrees)) {
            String finalCompanyId = companyId;
            rootTrees.stream().forEach(item->{
                if ("1".equals(item.getIsPublic())) { // 找到公有的集团
                    OfficeDTO officeDTO = item;
                    if (CollectionUtil.isNotEmpty(item.getChildren())){
                        officeDTO.setChildren(item.getChildren());
                    }
                    os.add(officeDTO);
                }else{
                    if(item.getId().equals(corporationId)){  // 找到登录人的集团
                        OfficeDTO officeDTO = item;
                        if (CollectionUtil.isNotEmpty(item.getChildren())&&!"".equals(finalCompanyId)){
                            List<OfficeDTO> companys = new ArrayList<>();
                            item.getChildren().stream().forEach(child->{
                                if(child.getId().equals(finalCompanyId) || "1".equals(child.getIsPublic())){ // 登录人的公司 或者 公有公司
                                    companys.add(child);
                                }
                            });
                            officeDTO.setChildren(companys);
                        }
                        os.add(officeDTO);
                    }
                }
            });
        }
        return os;
    }


    public List<OfficeDTO> formatListToTree(OfficeDTO root, List<OfficeDTO> allList, String extId, String type, String showAll) {
        String rootId = root.getId ();

        // type为2时，是选择部门，因此禁用type为1的公司节点
        if(OfficeTypeEnum.OFFICE.getValue ().equals(type) && root.getType().equals(OfficeTypeEnum.COMPANY.getValue ())){
            root.setDisabled(true);
        }else {
            root.setDisabled(false);
        }
        // 最终的树形态
        List<OfficeDTO> trees = Lists.newArrayList ();

        // 把需要构造树的所有列表, 根据以父id作为key, 整理为列表
        Map <String, List<OfficeDTO>> treeMap = Maps.newHashMap ();
        for (OfficeDTO entity : allList) {
            List<OfficeDTO> offices = treeMap.get (entity.getParent ().getId ());
            if (offices == null) {
                offices = Lists.newLinkedList ();
            }

            if (this.isUseAble ( extId, type,root, showAll )){
                // type为2时，是选择部门，因此禁用type为1的公司节点
                if(OfficeTypeEnum.OFFICE.getValue ().equals(type) && entity.getType().equals(OfficeTypeEnum.COMPANY.getValue ())){
                    entity.setDisabled(true);
                }else {
                    entity.setDisabled(false);
                }
                offices.add (entity);
                treeMap.put (entity.getParent ().getId (), offices);
            }
        }

        // 开始递归格式化
        List<OfficeDTO> children = treeMap.get (rootId);
        if (children != null) {
            for (OfficeDTO parent : children) {
                formatFillChildren (parent, treeMap);
                trees.add (parent);
            }
        }

        root.setChildren (trees);
        return Lists.newArrayList (root);
    }

    /**
     * 从treeMap中取出子节点填入parent, 并递归此操作
     **/
    private void formatFillChildren(OfficeDTO parent, Map<String, List<OfficeDTO>> treeMap) {

        List<OfficeDTO> children = treeMap.get (parent.getId ());
        parent.setChildren (children);
        if (children != null && !children.isEmpty ()) {
            for (OfficeDTO child : children) {
                formatFillChildren (child, treeMap);
            }
        }
    }

    private  boolean isUseAble(String extId, String type, OfficeDTO dto, String showAll){
        return  (StringUtils.isBlank (extId) || (extId != null && !extId.equals (dto.getId ()) && dto.getParentIds ().indexOf ("," + extId + ",") == -1))
                && (type == null || (type != null && (type.equals ( OfficeTypeEnum.COMPANY.getValue ()) ? type.equals (dto.getType ()) : true)))
                &&(CommonConstants.YES.equals ( showAll ) || CommonConstants.YES.equals (dto.getUseable ()));
    }

    /**
     * 根据部门名称查询部门信息
     * @param officeName
     * @return
     */
    public OfficeDTO getOfficeByName(String officeName,String parentName){
        if(StringUtils.isBlank(parentName)){
            parentName = "";
        }
        String parentIdArray[] =parentName.split(",");
        StringBuilder parentSql = new StringBuilder();
        for (int i = 0 ; i < parentIdArray.length; i++){
            if(StringUtils.isNotBlank(parentIdArray[i])){
                parentSql.append(" AND parent_id = (select id from sys_office where name = '").append(parentIdArray[i]).append("' AND del_flag = 0");
            }
        }
        for (int i = 0 ; i < parentIdArray.length; i++){
            if(StringUtils.isNotBlank(parentIdArray[i])){
                parentSql.append(")");
            }
        }
        OfficeDTO office = officeMapper.getOfficeByName(officeName,parentSql.toString());
        return office;
    }


    /**
     * 根据部门名称查询部门信息
     * @param officeName
     * @return
     */
    public List<OfficeDTO> getOfficeAllByOfficeName(String officeName){
        List<OfficeDTO> officeList = officeMapper.getOfficeAllByOfficeName(officeName);

        return officeList;
    }


    public List <OfficeDTO> getofficeUserTree(String officeName, List<OfficeDTO> list, String extId, String type, String showAll) {
        List<OfficeDTO> offices = Lists.newArrayList ();
        //查询总部门信息
        OfficeDTO root = officeMapper.getOfficeByName(officeName,"");
        if(null != root){
            if (this.isUseAble ( extId, type,root, showAll )){
                // 不是被排除节点的子节点
                List<OfficeDTO> officeList = formatListToTree (root, list, extId, type, showAll);
                offices.addAll (officeList);
            }
        }
        return offices;
    }

    public List <OfficeDTO> getRootTree2(List<OfficeDTO> list, String extId, String type, String showAll) {
        List<OfficeDTO> offices = Lists.newArrayList ();
        List<OfficeDTO> rootTrees = officeWrapper.toDTO (super.getChildren (new Office (OfficeDTO.getRootId ())));
        for (OfficeDTO root : rootTrees) {
            if (this.isUseAble ( extId, type,root, showAll )){
                // 不是被排除节点的子节点
                List<OfficeDTO> officeList = formatListToTree2 (root, list, extId, type, showAll);
                offices.addAll (officeList);
            }
        }
        return offices;
    }

    public List<OfficeDTO> formatListToTree2(OfficeDTO root, List<OfficeDTO> allList, String extId, String type, String showAll) {
        String rootId = root.getId ();

        // type为1时，是选择公司，因此禁用type为2的部门节点
        if(OfficeTypeEnum.COMPANY.getValue ().equals(type) && root.getType().equals(OfficeTypeEnum.COMPANY.getValue ())){
            root.setDisabled(false);
        }else {
            root.setDisabled(true);
        }
        // 最终的树形态
        List<OfficeDTO> trees = Lists.newArrayList ();

        // 把需要构造树的所有列表, 根据以父id作为key, 整理为列表
        Map <String, List<OfficeDTO>> treeMap = Maps.newHashMap ();
        for (OfficeDTO entity : allList) {
            List<OfficeDTO> offices = treeMap.get (entity.getParent ().getId ());
            if (offices == null) {
                offices = Lists.newLinkedList ();
            }

            if (this.isUseAble ( extId, type,root, showAll )){
                // type为2时，是选择部门，因此禁用type为1的公司节点
                if(OfficeTypeEnum.COMPANY.getValue ().equals(type) && entity.getType().equals(OfficeTypeEnum.COMPANY.getValue ())){
                    entity.setDisabled(false);
                }else {
                    entity.setDisabled(true);
                }
                offices.add (entity);
                treeMap.put (entity.getParent ().getId (), offices);
            }
        }

        // 开始递归格式化
        List<OfficeDTO> children = treeMap.get (rootId);
        if (children != null) {
            for (OfficeDTO parent : children) {
                formatFillChildren (parent, treeMap);
                trees.add (parent);
            }
        }

        root.setChildren (trees);
        return Lists.newArrayList (root);
    }

    public OfficeDTO getOfficeById(String id){
        return officeMapper.getOfficeById(id);
    }

    public IPage<OfficeDTO> findListTree(Page<OfficeDTO> page, OfficeDTO officeDTO) throws Exception{
        QueryWrapper<OfficeDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("so.del_flag","0");
        queryWrapper.orderByAsc("so.create_date");
        if (ObjectUtil.isNotEmpty(officeDTO)) {
            if (StringUtils.isNotBlank(officeDTO.getName())) {
                List<String> ids = new ArrayList<>();
                List<Office> list = this.list(new QueryWrapper<Office>().lambda()
                        .like(StringUtils.isNotBlank(officeDTO.getName()),Office::getName, officeDTO.getName())
               );
                list.stream().forEach(item->{
                    ids.add(item.getId());
                    if (StringUtils.isNotBlank(item.getParentId())) {
                        String parentId = item.getParentId();
                        while (true) {
                            Office byId = this.getOne(new QueryWrapper<Office>().lambda().eq(Office::getId, parentId));
                            if (ObjectUtil.isNotEmpty(byId)) {
                                ids.add(byId.getId());
                                if (StringUtils.isBlank(byId.getParentId())) {
                                    break;
                                } else {
                                    parentId = byId.getParentId();
                                }
                            } else {
                                break;
                            }
                        }
                    }
                    List<String> childIdList = this.list(new QueryWrapper<Office>().lambda().eq(Office::getParentId, item.getId())).stream().map(Office::getId).collect(Collectors.toList());
                    while (true) {
                        if (CollectionUtil.isNotEmpty(childIdList)) {
                            childIdList.stream().forEach(childId->{
                                ids.add(childId);
                            });
                            List<String> childIdS = this.list(new QueryWrapper<Office>().lambda().in(Office::getParentId, childIdList)).stream().map(Office::getId).collect(Collectors.toList());
                            if (CollectionUtil.isNotEmpty(childIdS)) {
                                childIdList = childIdS;
                            } else {
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                });
                List<String> lastIdList = ids.stream().distinct().collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(lastIdList)){
                    queryWrapper.in("so.id",lastIdList);
                } else {
                    return new Page<>();
                }
            }
        }
        return officeMapper.findList(page, queryWrapper);
    }

    public List<String> getOfficeNameByIds(List<String> idList){
       return officeMapper.getOfficeNameByIds(idList);
    }

    public List<String> getOfficeIdByNames(List<String> nameList){
       return officeMapper.getOfficeIdByNames(nameList);
    }

    /**
     * 获取二级节点数据信息
     * @return
     */
    public List<OfficeDTO> getSecondLevelData(){
        return officeMapper.getSecondLevelData();
    }

    public List<OfficeDTO> getAllCompany() {
        Page<OfficeDTO> page = new Page<>();
        page.setSize(-1);
        page.setCurrent(1);
        QueryWrapper<OfficeDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("so.del_flag","0");
        queryWrapper.eq("so.parent_id","0");  // parent_id 为 “0”
        queryWrapper.orderByDesc("so.name");
        return officeMapper.findList(page, queryWrapper).getRecords();
    }

    /**
     * 查询当前登录人所属部门是评估还是兴光会计
     *  1 评估
     *  2 兴光会计
     *  3 其他
     *  4 管理员
     */
    public String checkLoginIsPgOrKj() {
        AtomicReference<String> returnCode = new AtomicReference<>("3");
        // 如果当前登录人是管理员，直接返回 4
        if (UserUtils.getCurrentUserDTO().isAdmin()) {
            return "4";
        }
        // 获取当前登录人所属部门
        String officeId = UserUtils.getCurrentUserDTO().getOfficeDTO().getId();
        // 获取当前登录人所属部门的所有上级机构的id
        List<String> supOfficeIds = new ArrayList<>();
        Office office = officeMapper.selectById(officeId);
        if (ObjectUtil.isNotEmpty(office)) {
            if (StringUtils.isNotBlank(office.getParentIds())) {
                String[] splitIds = office.getParentIds().split(",");
                if (ObjectUtil.isNotEmpty(splitIds)) {
                    for (String splitId : splitIds) {
                        supOfficeIds.add(splitId);
                    }
                }
            }
        }
        supOfficeIds.add(officeId);
        List<Office> officeList = officeMapper.selectList(new LambdaQueryWrapper<Office>().in(Office::getId, supOfficeIds));
        officeList.stream().forEach(item -> {
            if ("xgzcpg".equals(item.getCode())) { // 当前人所属评估部门
                returnCode.set("1");
            }
            if ("xgkjssws".equals(item.getCode())) { // 当前人所属兴光会计部门
                returnCode.set("2");
            }
        });
        return returnCode.get();
    }
}
