package com.ruoyi.ibs.datavisual.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.ibs.datavisual.domain.vo.AdminRegionDataVO;
import com.ruoyi.ibs.datavisual.mapper.AdminRegionDataMapper;
import com.ruoyi.ibs.datavisual.service.AdminRegionDataService;
import com.ruoyi.ibs.grid.domain.entity.DeptRegionRelate;
import com.ruoyi.ibs.grid.mapper.DeptRegionRelateMapper;
import com.ruoyi.ibs.grid.service.RegionDataService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.SecurityUtils.userRoleHeadOrBranch;

/**
 * @Author 吴凯程
 * @Date 2025/3/28
 **/
@Service
public class AdminRegionDataServiceImpl implements AdminRegionDataService {

    @Resource
    private AdminRegionDataMapper adminRegionDataMapper;

    @Resource
    private DeptRegionRelateMapper deptRegionRelateMapper;

    @Resource
    private RegionDataService regionDataService;

    /**
     * @param opsDept
     * @return
     */
    @Override
    public List<AdminRegionDataVO> getTownDataList(String opsDept, String itemIdx,String branchName, String outletName, String nickName,String dt) {
        if(!SecurityUtils.userRole().equals("head")
                && !SecurityUtils.userRole().equals("public")
                && !SecurityUtils.userRole().equals("private")
                && !SecurityUtils.userRole().equals("headOps")
                && !SecurityUtils.userRole().equals("branch")
        ){
            throw new ServiceException("无权限查看本功能！");
        }

        LambdaQueryWrapper<DeptRegionRelate> queryWrapper = new LambdaQueryWrapper<>();
        List<DeptRegionRelate> deptRegionRelates = new ArrayList<>();
        List<String> codeList = new ArrayList<>();
        if("head".equalsIgnoreCase(SecurityUtils.userRoleHeadOrBranch())) {
            queryWrapper.eq(DeptRegionRelate::getDeptId, SecurityUtils.getDeptId());
            deptRegionRelates = deptRegionRelateMapper.selectList(queryWrapper);
            if (deptRegionRelates.size() < 1) {
                throw new ServiceException("机构未配置关联行政区划！");
            }
             codeList = deptRegionRelates.stream().map(DeptRegionRelate::getRegionCode).collect(Collectors.toList());
        }else{
            List<String> regionDataListByBranch = regionDataService.getRegionDataListByBranch();
            if (regionDataListByBranch.size() < 1) {
                throw new ServiceException("机构未配置关联行政区划！");
            }
            codeList = regionDataListByBranch.stream().map(e-> e.substring(0,9)).distinct().collect(Collectors.toList());
        }
        return adminRegionDataMapper.getTownDataList(codeList, opsDept, SecurityUtils.getDeptId(),  itemIdx,userRoleHeadOrBranch(),branchName, outletName, nickName,dt);
    }

    /**
     * @param code
     * @param opsDept
     * @return
     */
    @Override
    public List<AdminRegionDataVO> getVillageDataList(String code, String opsDept, String itemIdx,String branchName, String outletName, String nickName,String dt) {
//        if(!SecurityUtils.userRole().equals("head")
//                && !SecurityUtils.userRole().equals("public")
//                && !SecurityUtils.userRole().equals("private")
//                && !SecurityUtils.userRole().equals("branch")
//        ){
//            throw new ServiceException("无权限查看本功能！");
//        }
        String userName = new String();
        if(!StringUtils.isNotEmpty(code)){
           if("outlet".equalsIgnoreCase(userRoleHeadOrBranch())){
               ;
           }else if("manager".equalsIgnoreCase(userRoleHeadOrBranch())){
               userName = SecurityUtils.getUsername();
           }else{
               throw new ServiceException("无可查看范围！");
           }
        }


        return adminRegionDataMapper.getVillageDataList(code, opsDept, SecurityUtils.getDeptId(), itemIdx,userRoleHeadOrBranch(),branchName, outletName, nickName, userName,dt);
    }

    @Override
    public List<AdminRegionDataVO> getDetail(String code, String opsDept, String itemIdx,String dt) {

        List<AdminRegionDataVO> indexDetail = adminRegionDataMapper.getIndexDetail(code, opsDept, itemIdx,dt);
        if(indexDetail.size() > 0) {
            return buildTree(indexDetail, userRoleHeadOrBranch());
        }
        return indexDetail;
    }

    public List<AdminRegionDataVO> buildTree(List<AdminRegionDataVO> indexDetail,String userLevel) {
        // 创建一个映射来存储每个节点的父节点
        Map<String, AdminRegionDataVO> nodeMap = new HashMap<>();

        // 创建根节点列表，用于存储所有顶级节点（branch）
        List<AdminRegionDataVO> rootNodes = new ArrayList<>();

        List<AdminRegionDataVO> head = indexDetail.stream().filter(e -> "head".equalsIgnoreCase(e.getIndexType())).collect(Collectors.toList());
        List<AdminRegionDataVO> branch = indexDetail.stream().filter(e -> "branch".equalsIgnoreCase(e.getIndexType())).collect(Collectors.toList());
        List<AdminRegionDataVO> outlet = indexDetail.stream().filter(e -> "outlet".equalsIgnoreCase(e.getIndexType())).collect(Collectors.toList());
        List<AdminRegionDataVO> manager = indexDetail.stream().filter(e -> "manager".equalsIgnoreCase(e.getIndexType())).collect(Collectors.toList());






        if(head.size() > 0){
            head.forEach(node->{
                nodeMap.put(node.getHeadName(), node);
                node.setName(node.getHeadName());
                rootNodes.add(node);
                // 将节点存储到映射中
                nodeMap.put(node.getHeadName(), node);
            });
        }

        if(branch.size() > 0){
            branch.forEach(node->{
                nodeMap.put(node.getBranchName(), node);
                node.setName(node.getBranchName());
                if(rootNodes != null  && rootNodes.size() > 0){
                    AdminRegionDataVO parent = nodeMap.get(node.getHeadName());
                    parent.getChildren().add(node);
                    // 将节点存储到映射中
                }else{
                    rootNodes.add(node);
                }
            });
        }

        if(outlet.size() > 0){
            outlet.forEach(node->{
                node.setName(node.getOutletName());
                // 将outlet节点存储到映射中
                nodeMap.put(node.getOutletName(), node);
                node.setName(node.getOutletName());
                // 查找其父节点（branch）
                String parentName = node.getBranchName();
                if (parentName != null && nodeMap.containsKey(parentName)) {
                    AdminRegionDataVO parent = nodeMap.get(parentName);
                    parent.getChildren().add(node);
                }
            });
        }


        if(manager.size() > 0){
            manager.forEach(node->{
                // 将outlet节点存储到映射中
                node.setName(node.getUserName());
                // 查找其父节点（branch）
                String parentName = StringUtils.isNotEmpty(node.getOutletName())? node.getOutletName()
                        :  StringUtils.isNotEmpty(node.getBranchName())? node.getBranchName() :   node.getHeadName() ;
                if (parentName != null && nodeMap.containsKey(parentName)) {
                    AdminRegionDataVO parent = nodeMap.get(parentName);
                    parent.getManagerList().add(node);
                }
            });
        }


        // 将根节点列表赋值给indexDetail
        indexDetail.clear();
        indexDetail.addAll(rootNodes);


        if("head".equalsIgnoreCase(userLevel)){
            return indexDetail;
        }
        if("branch".equalsIgnoreCase(userLevel)){
            List<AdminRegionDataVO> children = indexDetail.get(0).getChildren();
            if(children != null && children.size() > 0){
                indexDetail.get(0).setChildren(children.stream().filter(e->e.getBranchId().compareTo(SecurityUtils.getDeptId()) == 0).collect(Collectors.toList()) );
            }
        }
        if("manager".equalsIgnoreCase(userLevel)){
            List<AdminRegionDataVO> managerVo = manager.stream().filter(e -> e.getUserName().equalsIgnoreCase(SecurityUtils.getUsername())).collect(Collectors.toList());
            if(managerVo != null && managerVo.size() > 0){
                indexDetail.clear();
                AdminRegionDataVO adminRegionDataOutVO = nodeMap.get(managerVo.get(0).getOutletName());
                AdminRegionDataVO adminRegionDatabranchVO = nodeMap.get(managerVo.get(0).getBranchName());
                AdminRegionDataVO adminRegionDataHeadVO = nodeMap.get(managerVo.get(0).getHeadName());

                if(StringUtils.isNotNull(adminRegionDataOutVO)) {
                    adminRegionDataHeadVO.setChildren(Arrays.asList(adminRegionDatabranchVO));
                    adminRegionDatabranchVO.setChildren(Arrays.asList(adminRegionDataOutVO));
                    adminRegionDataOutVO.setManagerList(managerVo);
                }else
                if(StringUtils.isNotNull(adminRegionDatabranchVO)) {
                    adminRegionDataHeadVO.setChildren(Arrays.asList(adminRegionDatabranchVO));
                    adminRegionDatabranchVO.setManagerList(managerVo);
                }else{
                    adminRegionDataHeadVO.setManagerList(managerVo);
                }
                indexDetail.add( adminRegionDataHeadVO  );

            }
            return indexDetail;
        }


        if ("outlet".equalsIgnoreCase(userLevel)){
            List<AdminRegionDataVO> children = indexDetail.get(0).getChildren();
            if(children != null && children.size() > 0){
                for ( AdminRegionDataVO branchVo :children) {
                    List<AdminRegionDataVO> outletVo = branchVo.getChildren().stream().filter(e -> e.getOutletId().compareTo(SecurityUtils.getDeptId()) == 0 ).collect(Collectors.toList());
                    if(outletVo != null && outletVo.size() > 0){
                        branchVo.setChildren(outletVo);
                        ArrayList<AdminRegionDataVO> arrayList = new ArrayList<>();
                        arrayList.add(branchVo);
                        indexDetail.get(0).setChildren(  arrayList );
                    }
                }
            }
            return indexDetail;
        }

        return indexDetail;
    }

}
