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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.ibs.grid.domain.dto.*;
import com.ruoyi.ibs.grid.domain.entity.*;
import com.ruoyi.ibs.grid.domain.excel.RegionSecGridExcelDTO;
import com.ruoyi.ibs.grid.domain.excel.RegionTopGridExcelDTO;
import com.ruoyi.ibs.grid.domain.vo.AddressTreeVO;
import com.ruoyi.ibs.grid.domain.vo.RegionGridVO;
import com.ruoyi.ibs.grid.mapper.*;
import com.ruoyi.ibs.grid.service.*;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @Author 吴凯程
 * @Date 2024/9/18
 **/

@Service
@Slf4j
public class RegionGridServiceImpl implements RegionGridService {

    @Resource
    private RegionGridMapper regionGridMapper;

    @Resource
    private RegionUserRelateMapper regionUserRelateMapper;

    @Resource
    private RegionAdminDivisionRelateMapper regionAdminDivisionRelateMapper;

    @Resource
    private RegionAddressTreeMapper regionAddressTreeMapper;

    @Resource
    private AdminDivisionMapper adminDivisionMapper;

    @Resource
    private SysAddressService sysAddressService;

    @Resource
    private RegionGridUtilsService regionGridUtilsService;

    @Resource
    private SysDeptMapper sysDeptMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private GridInfoRedisService gridInfoRedisService;

    @Resource
    private GridAreaFenceService gridAreaFenceService;

    @Resource
    private RegionGridUpdateService regionGridUpdateService;

    private final Map<Integer, Integer> codeSizeToLevel = new HashMap<Integer, Integer>() {{
        put(2, 1);
        put(4, 2);
        put(6, 3);
        put(9, 4);
        put(12,5);
    }};

    private final Map<Integer, Integer> levelToParentCode = new HashMap<Integer, Integer>() {{
        put(2, 2);
        put(3, 4);
        put(4, 6);
        put(5, 9);
    }};

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createTopRegionGrid(TopRegionGridDTO topRegionGridDTO) {
        if (regionGridUtilsService.checkGridNameExist(topRegionGridDTO.getGridName(), topRegionGridDTO.getGridLevel())) {
            throw new ServiceException("网格创建失败，网格名称已存在");
        }
        RegionGrid regionGrid = new RegionGrid();
        BeanUtils.copyProperties(topRegionGridDTO, regionGrid);
        regionGridMapper.insert(regionGrid);

        Long gridId = regionGrid.getGridId();

        if (topRegionGridDTO.getGridDutyType().equals("1") && topRegionGridDTO.getGridUserRelateDTOList().size() != 1) {
            throw new ServiceException("分配类型为责任网格时只可以选择单个机构");
        }
        if (topRegionGridDTO.getGridDutyType().equals("2") && topRegionGridDTO.getGridUserRelateDTOList().size() < 2) {
            throw new ServiceException("分配类型为竞争网格时需要选择多个机构");
        }
        topRegionGridDTO.getGridUserRelateDTOList().forEach(gridRelateDTO -> {
            if(gridRelateDTO.getRelateType().equals("1")){
                throw new ServiceException("一级网格不可以绑定客户经理！");
            }
            RegionUserRelate regionUserRelate = new RegionUserRelate();
            BeanUtils.copyProperties(gridRelateDTO, regionUserRelate);
            regionUserRelate.setGridId(gridId);
            regionUserRelateMapper.insert(regionUserRelate);
        });

        topRegionGridDTO.getAdminDivisionDTOList().forEach(gridAdminDivisionDTO -> {
            Integer level = codeSizeToLevel.get(gridAdminDivisionDTO.getCode().length());
            if(level == 5){
                RegionAdminDivisionRelate regionAdminDivisionRelate = new RegionAdminDivisionRelate();
                regionAdminDivisionRelate.setCode(gridAdminDivisionDTO.getCode());
                regionAdminDivisionRelate.setGridId(gridId);
                regionAdminDivisionRelate.setOpsDept(topRegionGridDTO.getOpsDept());
                regionAdminDivisionRelateMapper.insert(regionAdminDivisionRelate);
            }
            String parentCode =  gridAdminDivisionDTO.getCode().subSequence(0, levelToParentCode.get(level)).toString();
            RegionAddressTree regionAddressTree = new RegionAddressTree();
            regionAddressTree.setGridId(gridId);
            regionAddressTree.setCode(gridAdminDivisionDTO.getCode());
            regionAddressTree.setLabel(gridAdminDivisionDTO.getLabel());
            regionAddressTree.setLevel(level);
            regionAddressTree.setParentCode(parentCode);
            regionAddressTreeMapper.insert(regionAddressTree);
        });

        List<String> codeLevel5 = topRegionGridDTO.getAdminDivisionDTOList().stream()
                .map(RegionAdminDivisionDTO::getCode)
                .filter(code -> codeSizeToLevel.get(code.length()) == 5)
                .collect(Collectors.toList());
        if (!gridAreaFenceService.updateGridFence("1", gridId, codeLevel5)) {
            throw new ServiceException("网格围栏保存失败！");
        }
        gridInfoRedisService.cleanGridInfo("1");
        regionGridUpdateService.updateTopGrid(regionGrid.getGridId());
        return "一级网格创建成功！";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createSecRegionGrid(SecRegionGridDTO secRegionGridDTO) {
        if (regionGridUtilsService.checkGridNameExist(secRegionGridDTO.getGridName(), secRegionGridDTO.getGridLevel())) {
            throw new ServiceException("网格创建失败，网格名称已存在");
        }
        RegionGrid parentGrid = regionGridMapper.selectById(secRegionGridDTO.getParentGridId());

        RegionGrid regionGrid = new RegionGrid();
        regionGrid.setOpsDept(parentGrid.getOpsDept());
        BeanUtils.copyProperties(secRegionGridDTO, regionGrid);
        regionGridMapper.insert(regionGrid);


        Long gridId = regionGrid.getGridId();
        if (secRegionGridDTO.getGridDutyType().equals("1") && secRegionGridDTO.getGridUserRelateDTOList().size() != 1) {
            throw new ServiceException("分配类型为责任网格时只可以选择单个机构");
        }
        if (secRegionGridDTO.getGridDutyType().equals("2") && secRegionGridDTO.getGridUserRelateDTOList().size() < 2) {
            throw new ServiceException("分配类型为竞争网格时需要选择多个机构");
        }
        secRegionGridDTO.getGridUserRelateDTOList().forEach(gridRelateDTO -> {
            if(gridRelateDTO.getRelateType().equals("2")){
                throw new ServiceException("二级网格不可以绑定机构！");
            }
            RegionUserRelate regionUserRelate = new RegionUserRelate();
            BeanUtils.copyProperties(gridRelateDTO, regionUserRelate);
            regionUserRelate.setGridId(gridId);
            regionUserRelate.setParentGridId(regionGrid.getParentGridId());
            regionUserRelateMapper.insert(regionUserRelate);
        });

        List<String> codeLevel5 = secRegionGridDTO.getAdminDivisionCodeList().stream()
                .filter(code -> codeSizeToLevel.get(code.length()) == 5)
                .collect(Collectors.toList());
        codeLevel5.forEach(code -> {
            RegionAdminDivisionRelate regionAdminDivisionRelate = new RegionAdminDivisionRelate();
            regionAdminDivisionRelate.setCode(code);
            regionAdminDivisionRelate.setGridId(gridId);
            regionAdminDivisionRelate.setOpsDept(parentGrid.getOpsDept());
            regionAdminDivisionRelate.setParentGridId(regionGrid.getParentGridId());
            regionAdminDivisionRelateMapper.insert(regionAdminDivisionRelate);
        });
        if (!gridAreaFenceService.updateGridFence("1", gridId, codeLevel5)) {
            throw new ServiceException("网格围栏保存失败！");
        }
        gridInfoRedisService.cleanGridInfo("2");
        regionGridUpdateService.updateSecGrid(regionGrid.getGridId());
        return "二级网格创建成功！";
    }





    /**
     * @param topGridUpdateDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateTopRegionGrid(TopGridUpdateDTO topGridUpdateDTO) {

        Long gridId = topGridUpdateDTO.getGridId();
        RegionGrid regionGrid = regionGridMapper.selectById(gridId);
        if (Objects.isNull(regionGrid)) {
            throw new ServiceException("网格不存在！");
        }
        if (!regionGrid.getGridName().equals(topGridUpdateDTO.getGridName())
                && regionGridUtilsService.checkGridNameExist(topGridUpdateDTO.getGridName(), regionGrid.getGridLevel())) {
            throw new ServiceException("网格修改失败，网格名称已存在");
        }
        Long deptId = SecurityUtils.getDeptId();
        if (!regionGrid.getDeptId().equals(deptId) && deptId != 999000) {
            throw new ServiceException("当前用户无权限进行操作");
        }
        BeanUtils.copyProperties(topGridUpdateDTO, regionGrid);
        regionGridMapper.updateById(regionGrid);

        if(!topGridUpdateDTO.getAdminDivisionDTOList().isEmpty()){
            LambdaQueryWrapper<RegionAdminDivisionRelate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RegionAdminDivisionRelate::getGridId, gridId);
            regionAdminDivisionRelateMapper.delete(queryWrapper);

            LambdaQueryWrapper<RegionAddressTree> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(RegionAddressTree::getGridId, gridId);
            regionAddressTreeMapper.delete(queryWrapper1);

            topGridUpdateDTO.getAdminDivisionDTOList().forEach(gridAdminDivisionDTO -> {
                Integer level = codeSizeToLevel.get(gridAdminDivisionDTO.getCode().length());
                if(level == 5){
                    RegionAdminDivisionRelate regionAdminDivisionRelate = new RegionAdminDivisionRelate();
                    regionAdminDivisionRelate.setCode(gridAdminDivisionDTO.getCode());
                    regionAdminDivisionRelate.setGridId(gridId);
                    regionAdminDivisionRelate.setOpsDept(regionGrid.getOpsDept());
                    regionAdminDivisionRelateMapper.insert(regionAdminDivisionRelate);
                }
                String parentCode =  gridAdminDivisionDTO.getCode().subSequence(0, levelToParentCode.get(level)).toString();
                RegionAddressTree regionAddressTree = new RegionAddressTree();
                regionAddressTree.setGridId(gridId);
                regionAddressTree.setCode(gridAdminDivisionDTO.getCode());
                regionAddressTree.setLabel(gridAdminDivisionDTO.getLabel());
                regionAddressTree.setLevel(level);
                regionAddressTree.setParentCode(parentCode);
                regionAddressTreeMapper.insert(regionAddressTree);
            });

            List<String> codeLevel5 = topGridUpdateDTO.getAdminDivisionDTOList().stream()
                    .map(RegionAdminDivisionDTO::getCode)
                    .filter(code -> codeSizeToLevel.get(code.length()) == 5)
                    .collect(Collectors.toList());
            if (!gridAreaFenceService.updateGridFence("1", gridId, codeLevel5)) {
                throw new ServiceException("网格围栏保存失败！");
            }
        }
        if (Objects.nonNull(topGridUpdateDTO.getDeleteAdminDivisionList()) &&
                !topGridUpdateDTO.getDeleteAdminDivisionList().isEmpty()) {
            LambdaQueryWrapper<RegionAdminDivisionRelate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RegionAdminDivisionRelate::getParentGridId, gridId)
                    .in(RegionAdminDivisionRelate::getCode, topGridUpdateDTO.getDeleteAdminDivisionList());
            List<RegionAdminDivisionRelate> deleteLists = regionAdminDivisionRelateMapper.selectList(queryWrapper);
            List<Long> secGridIds = deleteLists.stream().map(RegionAdminDivisionRelate::getGridId).distinct().collect(Collectors.toList());
            regionAdminDivisionRelateMapper.delete(queryWrapper);
            updateGridFenceToSecGrid(secGridIds);
        }

        if(!topGridUpdateDTO.getGridUserRelateDTOList().isEmpty()){
            for(GridUserRelateDTO gridUserRelateDTO : topGridUpdateDTO.getGridUserRelateDTOList()){
                switch (gridUserRelateDTO.getOptFlag()){
                    case "0":
                        if(!checkGridUserRelateExist(gridId, gridUserRelateDTO)){
                            RegionUserRelate regionUserRelate = new RegionUserRelate();
                            BeanUtils.copyProperties(gridUserRelateDTO, regionUserRelate);
                            regionUserRelate.setGridId(gridId);
                            regionUserRelateMapper.insert(regionUserRelate);
                        }
                        break;
                    case "1":
                        LambdaQueryWrapper<RegionUserRelate> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(RegionUserRelate::getGridId, gridId)
                                .eq(RegionUserRelate::getRelateType, gridUserRelateDTO.getRelateType())
                                .eq(RegionUserRelate::getRelateDeptId, gridUserRelateDTO.getRelateDeptId());
                        regionUserRelateMapper.delete(queryWrapper);

                        LambdaQueryWrapper<RegionGrid> queryWrapper1 = new LambdaQueryWrapper<>();
                        queryWrapper1.eq(RegionGrid::getParentGridId, gridId)
                                .eq(RegionGrid::getGridLevel, "2")
                                .eq(RegionGrid::getDeptId, gridUserRelateDTO.getRelateDeptId());
                        List<Long> nextGridIds = regionGridMapper.selectList(queryWrapper1).stream().map(RegionGrid::getGridId).collect(Collectors.toList());
                        if (!nextGridIds.isEmpty()) {
                            deleteByGridId(nextGridIds);
                        }
                        break;
                    default:
                        log.error("操作标志optLabel不存在！");
                        break;
                }
            }
        }
        regionGridUpdateService.updateTopGrid(regionGrid.getGridId());
        return "一级网格信息更新成功！";
    }

    private void updateGridFenceToSecGrid(List<Long> gridIds) {
        gridIds.forEach(gridId -> {
            LambdaQueryWrapper<RegionAdminDivisionRelate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RegionAdminDivisionRelate::getGridId, gridId);
            List<RegionAdminDivisionRelate> regionAdminDivisionRelates = regionAdminDivisionRelateMapper.selectList(queryWrapper);
            if (Objects.isNull(regionAdminDivisionRelates) || regionAdminDivisionRelates.isEmpty()) {
                RegionGrid regionGrid = regionGridMapper.selectById(gridId);
                LambdaQueryWrapper<RegionUserRelate> userWrapper = new LambdaQueryWrapper<>();
                userWrapper.eq(RegionUserRelate::getGridId, gridId);
                regionUserRelateMapper.delete(userWrapper);
                gridAreaFenceService.deleteGridFence("1", gridId);
                regionGridMapper.deleteById(regionGrid);
            } else {
                List<String> codeLevel5 = regionAdminDivisionRelates.stream().map(RegionAdminDivisionRelate::getCode)
                        .filter(code -> codeSizeToLevel.get(code.length()) == 5)
                        .collect(Collectors.toList());
                if (!gridAreaFenceService.updateGridFence("1", gridId, codeLevel5)) {
                    throw new ServiceException("网格围栏保存失败！");
                }
            }
        });
    }

    /**
     * @param secGridUpdateDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateSecRegionGrid(SecGridUpdateDTO secGridUpdateDTO) {

        Long gridId = secGridUpdateDTO.getGridId();
        RegionGrid regionGrid = regionGridMapper.selectById(gridId);
        if (Objects.isNull(regionGrid)) {
            throw new ServiceException("网格不存在！");
        }
        if (!regionGrid.getGridName().equals(secGridUpdateDTO.getGridName())
                && regionGridUtilsService.checkGridNameExist(secGridUpdateDTO.getGridName(), regionGrid.getGridLevel())) {
            throw new ServiceException("网格修改失败，网格名称已存在");
        }
        Long deptId = SecurityUtils.getDeptId();
        if (!regionGrid.getDeptId().equals(deptId) && deptId != 999000) {
            throw new ServiceException("当前用户无权限进行操作");
        }

        BeanUtils.copyProperties(secGridUpdateDTO, regionGrid);
        regionGridMapper.updateById(regionGrid);

        if(!secGridUpdateDTO.getAdminDivisionCodeList().isEmpty()){
            LambdaQueryWrapper<RegionAdminDivisionRelate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RegionAdminDivisionRelate::getGridId, gridId);
            regionAdminDivisionRelateMapper.delete(queryWrapper);

//            secGridUpdateDTO.getAdminDivisionCodeList().forEach(code -> {
//                Integer level = codeSizeToLevel.get(code.length());
//                if(level == 5){
//                    RegionAdminDivisionRelate regionAdminDivisionRelate = new RegionAdminDivisionRelate();
//                    regionAdminDivisionRelate.setCode(code);
//                    regionAdminDivisionRelate.setGridId(gridId);
//                    regionAdminDivisionRelateMapper.insert(regionAdminDivisionRelate);
//                }
//            });

            List<String> codeLevel5 = secGridUpdateDTO.getAdminDivisionCodeList().stream()
                    .filter(code -> codeSizeToLevel.get(code.length()) == 5)
                    .collect(Collectors.toList());
            codeLevel5.forEach(code -> {
                RegionAdminDivisionRelate regionAdminDivisionRelate = new RegionAdminDivisionRelate();
                regionAdminDivisionRelate.setCode(code);
                regionAdminDivisionRelate.setGridId(gridId);
                regionAdminDivisionRelate.setOpsDept(regionGrid.getOpsDept());
                regionAdminDivisionRelate.setParentGridId(regionGrid.getParentGridId());
                regionAdminDivisionRelateMapper.insert(regionAdminDivisionRelate);
            });
            if (!gridAreaFenceService.updateGridFence("1", gridId, codeLevel5)) {
                throw new ServiceException("网格围栏保存失败！");
            }
        }

        if(!secGridUpdateDTO.getGridUserRelateDTOList().isEmpty()){
            for(GridUserRelateDTO gridUserRelateDTO : secGridUpdateDTO.getGridUserRelateDTOList()){
                switch (gridUserRelateDTO.getOptFlag()){
                    case "0":
                        if(!checkGridUserRelateExist(gridId, gridUserRelateDTO)){
                            RegionUserRelate regionUserRelate = new RegionUserRelate();
                            BeanUtils.copyProperties(gridUserRelateDTO, regionUserRelate);
                            regionUserRelate.setGridId(gridId);
                            regionUserRelate.setParentGridId(regionGrid.getParentGridId());
                            regionUserRelateMapper.insert(regionUserRelate);
                        }
                        break;
                    case "1":
                        LambdaQueryWrapper<RegionUserRelate> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(RegionUserRelate::getGridId, gridId)
                                .eq(RegionUserRelate::getUserName, gridUserRelateDTO.getUserName());
                        if (regionUserRelateMapper.delete(queryWrapper) < 1) {
                            throw new ServiceException("关联客户经理删除失败！");
                        }
                        break;
                    default:
                        log.error("操作标志optLabel不存在！");
                        break;
                }
            }
        }
        regionGridUpdateService.updateSecGrid(regionGrid.getGridId());
        return "二级网格修改成功！" ;
    }

    private boolean checkGridUserRelateExist(Long gridId, GridUserRelateDTO gridUserRelateDTO){
        LambdaQueryWrapper<RegionUserRelate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RegionUserRelate::getGridId, gridId)
                .eq(RegionUserRelate::getRelateType, gridUserRelateDTO.getRelateType())
                .eq(RegionUserRelate::getRelateDeptId, gridUserRelateDTO.getRelateDeptId());
        if(gridUserRelateDTO.getRelateType().equals("1")){
            queryWrapper.eq(RegionUserRelate::getUserName, gridUserRelateDTO.getUserName());
        }
        return regionUserRelateMapper.selectCount(queryWrapper) > 0;
    }


    @Override
    public RegionGridVO getRegionGridDetail(Long gridId) {
        RegionGridVO regionGridVO = new RegionGridVO();
        RegionGrid regionGrid = regionGridMapper.selectById(gridId);
        if (Objects.isNull(regionGrid)) {
            throw new ServiceException("网格不存在！");
        }

        BeanUtils.copyProperties(regionGrid, regionGridVO);
        LambdaQueryWrapper<RegionUserRelate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RegionUserRelate::getGridId, gridId);
        List<RegionUserRelate> regionUserRelates = regionUserRelateMapper.selectList(queryWrapper);
        regionGridVO.setUserRelateList(regionUserRelates);

        LambdaQueryWrapper<RegionAdminDivisionRelate> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(RegionAdminDivisionRelate::getGridId, gridId);
        List<RegionAdminDivisionRelate> regionAdminDivisionRelates = regionAdminDivisionRelateMapper.selectList(queryWrapper2);
        List<String> collect = regionAdminDivisionRelates.stream().map(RegionAdminDivisionRelate::getCode).collect(Collectors.toList());
        if (collect.isEmpty()) {
            throw new ServiceException("网格未绑定行政区划！");
        }
        regionGridVO.setDivisionRelateList(collect);
        regionGridVO.setCustCount(regionGridUtilsService.getGridCustCount(gridId).stream().reduce(0l, Long::sum));
        Long deptId = SecurityUtils.getDeptId();
        // TODO

        if(regionGrid.getGridLevel().equals("1")){
            List<String> selectedRegionCodes = regionGridMapper.getSelectedRegionCodes(deptId, regionGrid.getOpsDept(), "1", gridId);
            List<AddressTreeVO> fullAddressTreeByCache = sysAddressService.getFullAddressTreeByCache("33", selectedRegionCodes);
            regionGridVO.setAddressTree(fullAddressTreeByCache);
        }else if(regionGrid.getGridLevel().equals("2")){
            List<String> selectedRegionCodes = regionGridMapper.getSelectedRegionCodes(deptId, regionGrid.getOpsDept(), "2", gridId);
            List<AddressTreeVO> topGridAddressTree = regionGridUtilsService.getTopGridAddressTree(regionGrid.getParentGridId(), selectedRegionCodes);
            regionGridVO.setAddressTree(topGridAddressTree);
        }
        return regionGridVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteRegionGrid(DeleteDTO deleteDTO) {
        deleteByGridId(deleteDTO.getIdList());
        return "网格删除完成！";
    }

    private boolean isValidAdminCode(String code) {
        if (!code.matches("\\d+")) {
            return false;
        }
        if (!code.startsWith("33")) {
            return false;
        }
        if (code.length() < 7) {
            return false;
        }
        return true;
    }

    /**
     * @param regionTopGridExcelDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createTopRegionGridByTemplate(RegionTopGridExcelDTO regionTopGridExcelDTO) {
        if (!SecurityUtils.isHead()) {
            throw new ServiceException("用户无权限操作！");
        }
        String opsDept = SecurityUtils.getOpsDept();
        TopRegionGridDTO topRegionGridDTO = new TopRegionGridDTO();
        BeanUtils.copyProperties(regionTopGridExcelDTO, topRegionGridDTO);
        topRegionGridDTO.setOpsDept(opsDept);

        String[] adminDivisionList = regionTopGridExcelDTO.getAdminDivisionList().split(",");
        if (adminDivisionList.length < 1) {
            throw new ServiceException("行政区划不能为空！");
        }
        List<String> adminList = new ArrayList<>();
        for (String ad : adminDivisionList) {
            String[] split = ad.split("-");
            if(split.length != 3){
                throw new ServiceException("行政区划：" + ad + "结构不正确！");
            }
            LambdaQueryWrapper<AdminDivision> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AdminDivision::getCounty, split[0])
                    .eq(AdminDivision::getTown,  split[1])
                    .eq(AdminDivision::getVillage, split[2]);
            AdminDivision adminDivision = adminDivisionMapper.selectOne(queryWrapper);
            if(Objects.isNull(adminDivision)){
                throw new ServiceException("行政区划：" + ad + "不存在！");
            }
            adminList.add(adminDivision.getCode());
        }
        Map<String, AdminDivision> adminDivisionMap = new HashMap<>();
        for (String code : adminList.stream().distinct().collect(Collectors.toList())) {
            LambdaQueryWrapper<RegionAdminDivisionRelate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RegionAdminDivisionRelate::getCode, code)
                    .eq(RegionAdminDivisionRelate::getOpsDept, opsDept);
            if (regionAdminDivisionRelateMapper.selectCount(queryWrapper) > 0) {
                throw new ServiceException("行政区划：" + code + "已被绑定！");
            }
            Boolean insertFlag = adminDivisionMap.containsKey(code);
            String tempCode = code;
            while (!insertFlag) {
                if (tempCode.length() == 2) {
                    break;
                }
                AdminDivision adminDivisionByCode = sysAddressService.getAdminDivisionByCode(tempCode);
                adminDivisionMap.put(tempCode, adminDivisionByCode);
                tempCode = adminDivisionByCode.getCode().subSequence(0, levelToParentCode.get(adminDivisionByCode.getLevel())).toString();
                insertFlag = adminDivisionMap.containsKey(tempCode);
            }
        }
        List<RegionAdminDivisionDTO> adminDivisionDTOList = new ArrayList<>();
        adminDivisionMap.forEach((key, ad) -> {
            RegionAdminDivisionDTO regionAdminDivisionDTO = new RegionAdminDivisionDTO();
            regionAdminDivisionDTO.setCode(ad.getCode());
            regionAdminDivisionDTO.setLabel(ad.getLabel());
            adminDivisionDTOList.add(regionAdminDivisionDTO);
        });
        topRegionGridDTO.setAdminDivisionDTOList(adminDivisionDTOList);

        List<GridUserRelateDTO> gridUserRelateDTOList = new ArrayList<>();
        List<Long> deptIds = Arrays.stream(regionTopGridExcelDTO.getDeptList().split(",")).distinct().map(Long::valueOf).collect(Collectors.toList());
        if (deptIds.size() < 1) {
            throw new ServiceException("机构不能为空！");
        }
        for (Long deptId : deptIds) {
            SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
            if (Objects.isNull(sysDept)) {
                throw new ServiceException("机构：" + deptId + " 不存在！");
            }
            if (!sysDept.getDeptType().equals("branch")){
                throw new ServiceException("不支持绑定非支行机构：" + deptId);
            }
            GridUserRelateDTO gridUserRelateDTO = new GridUserRelateDTO();
            gridUserRelateDTO.setRelateType("2");
            gridUserRelateDTO.setRelateDeptId(sysDept.getDeptId());
            gridUserRelateDTO.setRelateDeptName(sysDept.getDeptName());
            gridUserRelateDTO.setRelateDeptType(sysDept.getDeptType());
            gridUserRelateDTOList.add(gridUserRelateDTO);
        }
        topRegionGridDTO.setGridUserRelateDTOList(gridUserRelateDTOList);
        return createTopRegionGrid(topRegionGridDTO);
    }

    /**
     * @param regionSecGridExcelDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createSecRegionGridByTemplate(RegionSecGridExcelDTO regionSecGridExcelDTO) {

        RegionGrid topRegionGrid = regionGridMapper.selectTopGridByName(regionSecGridExcelDTO.getTopGridName(), SecurityUtils.getDeptId());
        if (Objects.isNull(topRegionGrid)){
            throw new ServiceException("一级网格不存在！");
        }
        String[] adminDivisionList = regionSecGridExcelDTO.getAdminDivisionList().split(",");
        if (adminDivisionList.length < 1) {
            throw new ServiceException("行政区划不能为空！");
        }
        List<String> adminList = new ArrayList<>();
        for (String ad : adminDivisionList) {
            String[] split = ad.split("-");
            if(split.length != 3){
                throw new ServiceException("行政区划：" + ad + "结构不正确！");
            }

            Optional<AdminDivision> optionalItem = SysAddressServiceImpl.adminDivisionMap.values().stream()
                    .filter(item -> item.getCounty().equals(split[0]) && item.getTown().equals(split[1]) && item.getVillage().equals(split[2]))
                    .findFirst();
            if (optionalItem.isPresent()) {
                String code = optionalItem.get().getCode();
                if(!regionGridUtilsService.checkadminRegionValid(code, topRegionGrid.getOpsDept())){
                    throw new ServiceException("行政区划：" + ad + "无法绑定该一级网格！");
                }
                if(!regionGridUtilsService.checkadminRegionAvailable(code, topRegionGrid.getOpsDept())){
                    throw new ServiceException("行政区划：" + ad + "已被绑定！");
                }
                adminList.add(code);
            } else {
                throw new ServiceException("行政区划：" + ad + "不存在！");
            }
        }
        String[] userArray = regionSecGridExcelDTO.getUserList().split(",");
        if (userArray.length < 1) {
            throw new ServiceException("柜员不能为空！");
        }
        LambdaQueryWrapper<RegionUserRelate> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(RegionUserRelate::getGridId, topRegionGrid.getGridId());
        List<Long> deptIds = regionUserRelateMapper.selectList(queryWrapper1).stream().map(RegionUserRelate::getRelateDeptId).collect(Collectors.toList());
        List<GridUserRelateDTO> gridUserRelateDTOList = new ArrayList<>();
        for (String userName : userArray) {
            SysUser sysUser = sysUserMapper.selectUserByUserName(userName);
            if (Objects.isNull(sysUser)){
                throw new ServiceException("柜员：" + userName + "不存在！");
            }
            if(!deptIds.contains(sysUser.getDept().getParentId()) && !deptIds.contains(sysUser.getDeptId())){
                throw new ServiceException("柜员：" + userName + "不在该一级网格机构归属下！");
            }
            GridUserRelateDTO gridUserRelateDTO = new GridUserRelateDTO();
            gridUserRelateDTO.setRelateType("1");
            gridUserRelateDTO.setNickName(sysUser.getNickName());
            gridUserRelateDTO.setUserName(sysUser.getUserName());
            gridUserRelateDTO.setRelateDeptId(sysUser.getDeptId());
            gridUserRelateDTO.setRelateDeptName(sysUser.getDept().getDeptName());
            gridUserRelateDTO.setRelateDeptType(sysUser.getDept().getDeptType());
            gridUserRelateDTO.setOptFlag("0");
            gridUserRelateDTOList.add(gridUserRelateDTO);
        }

        SecRegionGridDTO secRegionGridDTO = new SecRegionGridDTO();
        secRegionGridDTO.setParentGridId(topRegionGrid.getGridId());
        secRegionGridDTO.setOpsDept(topRegionGrid.getOpsDept());
        secRegionGridDTO.setGridName(regionSecGridExcelDTO.getGridName());
        secRegionGridDTO.setGridDutyType(regionSecGridExcelDTO.getGridDutyType());
        secRegionGridDTO.setAdminDivisionCodeList(adminList);
        secRegionGridDTO.setGridUserRelateDTOList(gridUserRelateDTOList);

        return createSecRegionGrid(secRegionGridDTO);
    }




    private void deleteByGridId(List<Long> idList){
        Long deptId = SecurityUtils.getDeptId();
        String deptCode = deptId.toString().substring(0, 3);
        idList.forEach(gridId -> {
            RegionGrid regionGrid = regionGridMapper.selectById(gridId);
            if (Objects.isNull(regionGrid)) {
                throw new ServiceException("网格已删除或不存在！");
            }
            String ancestors = sysDeptMapper.selectDeptById(regionGrid.getDeptId()).getAncestors();
            if (!regionGrid.getDeptId().equals(deptId) && !ancestors.contains(String.valueOf(deptId))) {
                throw new ServiceException("当前用户无权限进行操作");
            }

            LambdaQueryWrapper<RegionUserRelate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RegionUserRelate::getGridId, gridId);
            regionUserRelateMapper.delete(queryWrapper);

            LambdaQueryWrapper<RegionAdminDivisionRelate> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(RegionAdminDivisionRelate::getGridId, gridId);
            regionAdminDivisionRelateMapper.delete(queryWrapper2);

            gridAreaFenceService.deleteGridFence("1", gridId);

            if(Objects.equals(regionGrid.getGridLevel(), "1")){
                LambdaQueryWrapper<RegionAddressTree> queryWrapper3 = new LambdaQueryWrapper<>();
                queryWrapper3.eq(RegionAddressTree::getGridId, gridId);
                regionAddressTreeMapper.delete(queryWrapper3);

                LambdaQueryWrapper<RegionGrid> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(RegionGrid::getParentGridId, gridId);
                List<RegionGrid> regionGrids = regionGridMapper.selectList(queryWrapper1);
                if(!regionGrids.isEmpty()){
                    List<Long> nextIds = regionGrids.stream().map(RegionGrid::getGridId).collect(Collectors.toList());
                    deleteByGridId(nextIds);
                }
                regionGridUpdateService.deleteTopGrid(deptCode, regionGrid.getGridId());
            }else if (Objects.equals(regionGrid.getGridLevel(), "2")){
                regionGridUpdateService.deleteSecGrid(deptCode, regionGrid.getGridId());
            }
            regionGridMapper.deleteById(regionGrid);

        });
    }




}
