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

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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ibs.draw.domain.entity.DrawShape;
import com.ruoyi.ibs.grid.domain.dto.GridShapeHeatMapDTO;
import com.ruoyi.ibs.grid.domain.entity.GridShapeCountLingshou;
import com.ruoyi.ibs.grid.domain.entity.GridShapeCustGongsi;
import com.ruoyi.ibs.grid.domain.entity.GridShapeCustLingshou;
import com.ruoyi.ibs.grid.domain.vo.GridShapeHeatMapVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ibs.grid.mapper.GridShapeCountMapper;
import com.ruoyi.ibs.grid.domain.entity.GridShapeCountGongsi;
import com.ruoyi.ibs.grid.service.IGridShapeCountService;

import javax.annotation.Resource;

/**
 * 自定义地图网格汇总统计_公司Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-08
 */
@Service
public class GridShapeCountServiceImpl implements IGridShapeCountService
{
    @Autowired
    private GridShapeCountMapper gridShapeCountGongsiMapper;


    @Resource
    RedisCache redisCache;

    /**
     * 查询自定义地图网格汇总统计_公司
     * 
     * @param dt 自定义地图网格汇总统计_公司主键
     * @return 自定义地图网格汇总统计_公司
     */
    @Override
    public GridShapeCountGongsi selectGridShapeCountGongsiByDt(String dt)
    {
        return gridShapeCountGongsiMapper.selectGridShapeCountGongsiByDt(dt);
    }

    /**
     * 查询自定义地图网格汇总统计_公司列表
     * @return 自定义地图网格汇总统计_公司
     */
    @Override
    public List<GridShapeCountGongsi> selectGridShapeCountGongsiList(String shapeType ,String shapeName, String gridName,String dt)
    {
        HashMap<String, Object> paramMap = new HashMap<>();
        if(SecurityUtils.userRole().equals("head") || SecurityUtils.userRole().equals("public") || SecurityUtils.userRole().equals("private") ||SecurityUtils.userRole().equals("ops")){
            paramMap.put("isHead",true);
        }
        if(SecurityUtils.userRole().equals("branch")){
            paramMap.put("isBranch",true);
        }
        if(SecurityUtils.userRole().equals("outlet")){
            paramMap.put("isOutlet",true);
        }
        if(SecurityUtils.userRole().equals("manager")){
            paramMap.put("isManager",true);
        }
        paramMap.put("deptId",SecurityUtils.getDeptId());
        paramMap.put("userName",SecurityUtils.getUsername());
        paramMap.put("gridName",gridName);
        paramMap.put("shapeType",shapeType);
        paramMap.put("shapeName",shapeName);
        paramMap.put("dt",dt);

//        return GridVirtualCountMapper.selectGridVirtualCountLingshouList(paramMap);
        return gridShapeCountGongsiMapper.selectGridShapeCountGongsiList(paramMap);
    }


    @Override
    public List<GridShapeCountLingshou> selectGridShapeCountLingshouList(String shapeType , String shapeName, String gridName,String dt)
    {
        HashMap<String, Object> paramMap = new HashMap<>();
        if(SecurityUtils.userRole().equals("head") || SecurityUtils.userRole().equals("public") || SecurityUtils.userRole().equals("private") ||SecurityUtils.userRole().equals("ops")){
            paramMap.put("isHead",true);
        }
        if(SecurityUtils.userRole().equals("branch")){
            paramMap.put("isBranch",true);
        }
        if(SecurityUtils.userRole().equals("outlet")){
            paramMap.put("isOutlet",true);
        }
        if(SecurityUtils.userRole().equals("manager")){
            paramMap.put("isManager",true);
        }
        paramMap.put("deptId",SecurityUtils.getDeptId());
        paramMap.put("userName",SecurityUtils.getUsername());
        paramMap.put("gridName",gridName);
        paramMap.put("shapeType",shapeType);
        paramMap.put("shapeName",shapeName);
        paramMap.put("dt",dt);

//        return GridVirtualCountMapper.selectGridVirtualCountLingshouList(paramMap);
        return gridShapeCountGongsiMapper.selectGridShapeCountLingshouList(paramMap);
    }

    public List<GridShapeCustGongsi> selectGridShapeCountgsCustList(String shapeId , String custName, String socialCreditCode,String dt){
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("deptId",SecurityUtils.getDeptId());
        paramMap.put("userName",SecurityUtils.getUsername());
        paramMap.put("shapeId",shapeId);
        paramMap.put("custName",custName);
        paramMap.put("socialCreditCode",socialCreditCode);
        paramMap.put("dt",dt);

        return gridShapeCountGongsiMapper.selectGridShapeCountgsCustList(paramMap);
    }

    public List<GridShapeCustLingshou> selectGridShapeCountlsCustList(String shapeId , String custName, String custIdc,String dt){
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("deptId",SecurityUtils.getDeptId());
        paramMap.put("userName",SecurityUtils.getUsername());
        paramMap.put("shapeId",shapeId);
        paramMap.put("custName",custName);
        paramMap.put("custIdc",custIdc);
        paramMap.put("dt",dt);

        return gridShapeCountGongsiMapper.selectGridShapeCountlsCustList(paramMap);
    }

    /**
     * 新增自定义地图网格汇总统计_公司
     * 
     * @param gridShapeCountGongsi 自定义地图网格汇总统计_公司
     * @return 结果
     */
    @Override
    public int insertGridShapeCountGongsi(GridShapeCountGongsi gridShapeCountGongsi)
    {
        return gridShapeCountGongsiMapper.insertGridShapeCountGongsi(gridShapeCountGongsi);
    }

    /**
     * 修改自定义地图网格汇总统计_公司
     * 
     * @param gridShapeCountGongsi 自定义地图网格汇总统计_公司
     * @return 结果
     */
    @Override
    public int updateGridShapeCountGongsi(GridShapeCountGongsi gridShapeCountGongsi)
    {
        return gridShapeCountGongsiMapper.updateGridShapeCountGongsi(gridShapeCountGongsi);
    }

    /**
     * 批量删除自定义地图网格汇总统计_公司
     * 
     * @param dts 需要删除的自定义地图网格汇总统计_公司主键
     * @return 结果
     */
    @Override
    public int deleteGridShapeCountGongsiByDts(String[] dts)
    {
        return gridShapeCountGongsiMapper.deleteGridShapeCountGongsiByDts(dts);
    }

    /**
     * 删除自定义地图网格汇总统计_公司信息
     * 
     * @param dt 自定义地图网格汇总统计_公司主键
     * @return 结果
     */
    @Override
    public int deleteGridShapeCountGongsiByDt(String dt)
    {
        return gridShapeCountGongsiMapper.deleteGridShapeCountGongsiByDt(dt);
    }


    @Override
    public List<GridShapeHeatMapVO> heatMapList(GridShapeHeatMapDTO gridVirtualHeatMapDTO) {
        Map<String, String> indexMaps = this.indexList("grid_shape_count_lingshou_detail".equalsIgnoreCase(gridVirtualHeatMapDTO.getTabName()) ? "ls" : "gs");
        if( !indexMaps.containsKey(gridVirtualHeatMapDTO.getIndexId())){
            throw new ServiceException("指标不存在！");
        }
        gridVirtualHeatMapDTO.setUserLevel(SecurityUtils.userRoleHeadOrBranch());
        gridVirtualHeatMapDTO.setUserCode("manager".equalsIgnoreCase(gridVirtualHeatMapDTO.getUserLevel()) ?  SecurityUtils.getUserNameCode() : SecurityUtils.getDeptId().toString());
        List<GridShapeCountGongsi> gridShapeCountGongsis = gridShapeCountGongsiMapper.heatMapList(gridVirtualHeatMapDTO);
        List<GridShapeHeatMapVO> ans =new ArrayList<>();
        if(gridShapeCountGongsis != null && gridShapeCountGongsis.size() > 0){
            // 使用shapeId作为key进行分组
            Map<String, List<GridShapeCountGongsi>> groupedData = gridShapeCountGongsis.stream()
                    .collect(Collectors.groupingBy(GridShapeCountGongsi::getShapeId));
            // 转换为目标对象列表
            return groupedData.values().stream()
                    .map(group -> {
                        GridShapeCountGongsi firstItem = group.get(0); // 使用第一个元素的公共属性

                        // 收集deptId、outletsId、userName到对应的列表
                        List<String> branchIds = group.stream()
                                .map(GridShapeCountGongsi::getDeptId)
                                .filter(Objects::nonNull)
                                .distinct()
                                .collect(Collectors.toList());

                        List<String> outletIds = group.stream()
                                .map(GridShapeCountGongsi::getOutletsId)
                                .filter(Objects::nonNull)
                                .distinct()
                                .collect(Collectors.toList());

                        List<String> managerIds = group.stream()
                                .map(GridShapeCountGongsi::getUserName)
                                .filter(Objects::nonNull)
                                .distinct()
                                .collect(Collectors.toList());

                        // 使用Builder模式构建目标对象
                        return GridShapeHeatMapVO.builder()
                                .dt(firstItem.getDt())
                                .branchs(branchIds)
                                .ourlets(outletIds)
                                .managers(managerIds)
                                .shapeId(Long.valueOf(firstItem.getShapeId()))
                                .shapeName(firstItem.getShapeName())
                                .indexValue(firstItem.getIndexValue())
                                .gridName(firstItem.getGridName())
                                .shapeWkt(firstItem.getShapeWkt())
                                .build();
                    }).collect(Collectors.toList());
        }
        return ans;
    }


    @Override
    public Map<String,String> shapeNameList(String  shapeType,String tabName){

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("tabName", tabName);
        paramMap.put("shapeType", shapeType);
        paramMap.put("userLevel", SecurityUtils.userRoleHeadOrBranch());
        paramMap.put("deptId", SecurityUtils.getDeptId());
        paramMap.put("userNameCode", SecurityUtils.getUserNameCode());

        List<GridShapeCountGongsi> gridShapeCountGongsis = gridShapeCountGongsiMapper.selectShapeNameList(paramMap);
        if (gridShapeCountGongsis != null && gridShapeCountGongsis.size() > 0){
            return gridShapeCountGongsis.stream().collect(Collectors.toMap(GridShapeCountGongsi::getShapeId, GridShapeCountGongsi::getShapeName));
        }
        return new HashMap<>();
    }


    @Override
    public Map<String,String>  indexList(String type ){

        String dicName = "gs".equalsIgnoreCase(type) ? "sys_dict:gridshapecountindex_gs" : "ls".equalsIgnoreCase(type) ? "sys_dict:gridshapecountindex_ls" : "";
        if(StringUtils.isEmpty(dicName)){
            return new HashMap<>();
        }
        Map<String,String> params = new HashMap<>();
        ArrayList<SysDictData> sysDictTypeArrayList = new ArrayList<SysDictData>(redisCache.getCacheObject(dicName));
        sysDictTypeArrayList.forEach(sdt -> {
            params.put(sdt.getDictValue(), sdt.getDictLabel());
        });
        return params;

    }
}
