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.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.ibs.draw.domain.dto.grid.CustCountDTO;
import com.ruoyi.ibs.grid.domain.dto.GridCustListDTO;
import com.ruoyi.ibs.grid.domain.dto.RegionGridListDTO;
import com.ruoyi.ibs.grid.domain.dto.UnbindDTO;
import com.ruoyi.ibs.grid.domain.entity.*;
import com.ruoyi.ibs.grid.domain.vo.RegionCustUserVO;
import com.ruoyi.ibs.grid.domain.vo.RegionGridCustVO;
import com.ruoyi.ibs.grid.domain.vo.RegionGridListVO;
import com.ruoyi.ibs.grid.domain.vo.RegionUnbindVo;
import com.ruoyi.ibs.grid.mapper.*;
import com.ruoyi.ibs.grid.service.RegionGridListService;
import com.ruoyi.ibs.grid.service.RegionGridUtilsService;
import com.ruoyi.ibs.grid.service.SysAddressService;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author 吴凯程
 * @Date 2025/1/7
 **/
@Service
public class RegionGridListServiceImpl implements RegionGridListService {

    @Resource
    private RegionGridMapper regionGridMapper;

    @Resource
    private SysDeptMapper sysDeptMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private RegionCustUserUnbindMapper regionCustUserUnbindMapper;

    @Resource
    private RegionGridUtilsService regionGridUtilsService;

    @Resource
    private RegionUserRelateMapper regionUserRelateMapper;

    @Resource
    private SysAddressService sysAddressService;

    @Resource
    private AnchorMapper anchorMapper;

    @Resource
    private RegionCustUserMapper regionCustUserMapper;

    /**
     * 根据网格类型查询客户信息
     *
     * @param gridCustListDTO 包含客户类型和其他查询条件的DTO对象
     * @param regionGrid 区域网格对象，用于获取创建者和其他网格信息
     * @return 返回一个客户信息列表，根据客户类型的不同而查询不同的数据
     */
    @Override
    public List<RegionCustUserVO> selectCustFromGrid(GridCustListDTO gridCustListDTO, RegionGrid regionGrid) {
        LambdaQueryWrapper<RegionCustUser> queryWrapper = new LambdaQueryWrapper<>();
        if (regionGrid.getGridLevel().equals("1")) {
            queryWrapper.eq(RegionCustUser::getTopGridId, regionGrid.getGridId());
        } else if (regionGrid.getGridLevel().equals("2")) {
            queryWrapper.eq(RegionCustUser::getSecGridId, regionGrid.getGridId());
        }
        queryWrapper.eq(RegionCustUser::getCustType, gridCustListDTO.getCustType());
        if (Objects.nonNull(gridCustListDTO.getCustId()) && !gridCustListDTO.getCustId().isEmpty()) {
            queryWrapper.like(RegionCustUser::getCustId, gridCustListDTO.getCustId());
        }
        if (Objects.nonNull(gridCustListDTO.getCustType()) && !gridCustListDTO.getCustType().isEmpty()) {
            queryWrapper.eq(RegionCustUser::getCustType, gridCustListDTO.getCustType());
        }
        if (Objects.nonNull(gridCustListDTO.getCustName()) && !gridCustListDTO.getCustName().isEmpty()) {
            queryWrapper.like(RegionCustUser::getCustName, gridCustListDTO.getCustName());
        }
        List<RegionCustUser> custUserList = regionCustUserMapper.selectList(queryWrapper);

        return custUserList.stream().map(regionCustUser -> {
            RegionCustUserVO regionCustUserVO = new RegionCustUserVO();
            BeanUtils.copyProperties(regionCustUser, regionCustUserVO);
            regionCustUserVO.setAddress(anchorMapper.selectAddressByCustIdc(regionCustUser.getCustId().substring(3)));
            return regionCustUserVO;
        }).collect(Collectors.toList());
    }

    /**
     * @param gridCustListDTO
     * @param regionGrid
     * @return
     */
    @Override
    public List<RegionGridCustVO> selectCustFromGridByManager(GridCustListDTO gridCustListDTO, RegionGrid regionGrid) {
        List<RegionGridCustVO> custList = new ArrayList<>();
        if (regionGrid.getGridLevel().equals("1") && gridCustListDTO.getCustType().equals("0")) {
            custList = regionGridMapper.getRetailCustFromTopByManager(gridCustListDTO);
        } else if (regionGrid.getGridLevel().equals("1") && gridCustListDTO.getCustType().equals("1")) {
            custList = regionGridMapper.getMerchantCustFromTopByManager(gridCustListDTO);
        } else if (regionGrid.getGridLevel().equals("1") && gridCustListDTO.getCustType().equals("2")) {
            custList = regionGridMapper.getBusinessCustFromTopByManager(gridCustListDTO);
        } else if (regionGrid.getGridLevel().equals("2") && gridCustListDTO.getCustType().equals("0")) {
            custList = regionGridMapper.getRetailCustFromSecByManager(gridCustListDTO);
        } else if (regionGrid.getGridLevel().equals("2") && gridCustListDTO.getCustType().equals("1")) {
            custList = regionGridMapper.getMerchantCustFromSecByManager(gridCustListDTO);
        } else if (regionGrid.getGridLevel().equals("2") && gridCustListDTO.getCustType().equals("2")) {
            custList = regionGridMapper.getBusinessCustFromSecByManager(gridCustListDTO);
        }
        if (custList.isEmpty()) {
            return custList;
        }
        String creator = sysUserMapper.selectUserByUserName(regionGrid.getCreateBy()).getNickName() + '-' + regionGrid.getCreateBy();
        for (RegionGridCustVO regionGridCustVO : custList) {
            regionGridCustVO.setAddress(anchorMapper.selectAddressByCustIdc(regionGridCustVO.getCustIdn()));
            AdminDivision adminDivisionByCode = sysAddressService.getAdminDivisionByCode(regionGridCustVO.getRegionCode());
            regionGridCustVO.setRegionName(adminDivisionByCode.getTown() + '-' + adminDivisionByCode.getVillage());
            regionGridCustVO.setCreator(creator);
            if (regionGrid.getGridLevel().equals("1")) {
                regionGridCustVO.setTopGridId(regionGrid.getGridId());
                regionGridCustVO.setTopGridName(regionGrid.getGridName());
                regionGridCustVO.setTopGridDutyType(regionGrid.getGridDutyType());
                RegionGrid secGrid = regionGridMapper.getSecGridIdByCode(regionGrid.getGridId(), regionGridCustVO.getRegionCode());
                if (Objects.nonNull(secGrid)) {
                    regionGridCustVO.setSecGridId(secGrid.getGridId());
                    regionGridCustVO.setSecGridName(secGrid.getGridName());
                    regionGridCustVO.setSecGridDutyType(secGrid.getGridDutyType());
                }
            } else {
                RegionGrid topGrid = regionGridMapper.selectById(regionGrid.getParentGridId());
                regionGridCustVO.setTopGridId(topGrid.getGridId());
                regionGridCustVO.setTopGridName(topGrid.getGridName());
                regionGridCustVO.setTopGridDutyType(topGrid.getGridDutyType());
                regionGridCustVO.setSecGridId(regionGrid.getGridId());
                regionGridCustVO.setSecGridName(regionGrid.getGridName());
                regionGridCustVO.setSecGridDutyType(regionGrid.getGridDutyType());
            }
            List<Long> deptListByRegionCode = regionGridMapper.getDeptListByRegionCode(regionGridCustVO.getRegionCode(), regionGrid.getOpsDept());
            if (!deptListByRegionCode.isEmpty()) {
                List<String> branch = new ArrayList<>();
                List<String> outlet = new ArrayList<>();
                for (Long deptId : deptListByRegionCode) {
                    SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
                    if (sysDept.getDeptType().equals("branch") || sysDept.getDeptType().equals("head")) {
                        branch.add(sysDept.getDeptName());
                    } else if (sysDept.getDeptType().equals("outlet")) {
                        branch.add(sysDept.getParentName());
                        outlet.add(sysDept.getDeptName());
                    }
                }
                if (!branch.isEmpty()) {
                    String collect = branch.stream().distinct().collect(Collectors.joining(","));
                    regionGridCustVO.setBranchNames(collect);
                }
                if (!outlet.isEmpty()) {
                    String collect = outlet.stream().distinct().collect(Collectors.joining(","));
                    regionGridCustVO.setOutletNames(collect);
                }
            }
            List<String> userListByRegionCode = regionGridMapper.getUserListByRegionCode(regionGridCustVO.getRegionCode(), regionGrid.getOpsDept());
            if (!userListByRegionCode.isEmpty()) {
                String collect = userListByRegionCode.stream().collect(Collectors.joining(","));
                regionGridCustVO.setUserNames(collect);
            }
            regionGridCustVO.setIsOptUnbind(Boolean.FALSE);
        }
        return custList;
    }


    /**
     * @param unbindDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String unbindCustUser(UnbindDTO unbindDTO) {
        LambdaQueryWrapper<RegionCustUserUnbind> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RegionCustUserUnbind::getGridId, unbindDTO.getGridId())
                .eq(RegionCustUserUnbind::getCustId, unbindDTO.getCustId())
                .eq(RegionCustUserUnbind::getUserName, unbindDTO.getUserName());
        RegionCustUserUnbind regionCustUserUnbind = regionCustUserUnbindMapper.selectOne(queryWrapper);
        if (Objects.isNull(regionCustUserUnbind)) {
            regionCustUserUnbind = new RegionCustUserUnbind();
            BeanUtils.copyProperties(unbindDTO, regionCustUserUnbind);
            regionCustUserUnbindMapper.insert(regionCustUserUnbind);
            return "解绑成功";
        } else {
            regionCustUserUnbindMapper.deleteById(regionCustUserUnbind);
            return "重新绑定成功";
        }
    }

    /**
     * @param gridId
     * @param custId
     * @return
     */
    @Override
    public List<RegionUnbindVo> getUserUnbindList(Long gridId, String custId) {
        List<RegionUnbindVo> userUnbindList = regionGridMapper.getUserUnbindList(gridId, custId);
        userUnbindList.forEach(regionUnbindVo -> regionUnbindVo.setCustId(custId));
        return userUnbindList;
    }

    /**
     * @param gridId
     * @return
     */
    @Override
    public CustCountDTO getUnbindCustCount(Long gridId) {
        CustCountDTO custCountDTO = new CustCountDTO();
        LambdaQueryWrapper<RegionCustUserUnbind> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RegionCustUserUnbind::getGridId, gridId)
                .eq(RegionCustUserUnbind::getUserName, SecurityUtils.getUsername())
                .eq(RegionCustUserUnbind::getCustType, "0");
        custCountDTO.setRetailCount(regionCustUserUnbindMapper.selectCount(queryWrapper));
        LambdaQueryWrapper<RegionCustUserUnbind> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(RegionCustUserUnbind::getGridId, gridId)
                .eq(RegionCustUserUnbind::getUserName, SecurityUtils.getUsername())
                .eq(RegionCustUserUnbind::getCustType, "1");
        custCountDTO.setMerchantCount(regionCustUserUnbindMapper.selectCount(queryWrapper1));
        LambdaQueryWrapper<RegionCustUserUnbind> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(RegionCustUserUnbind::getGridId, gridId)
                .eq(RegionCustUserUnbind::getUserName, SecurityUtils.getUsername())
                .eq(RegionCustUserUnbind::getCustType, "2");
        custCountDTO.setBusinessCount(regionCustUserUnbindMapper.selectCount(queryWrapper2));
        return custCountDTO;
    }

    /**
     * @param regionGridListDTO
     * @return
     */
    @Override
    public List<RegionGridListVO> getTopGridList(RegionGridListDTO regionGridListDTO) {
        if (SecurityUtils.isHead()) {
            regionGridListDTO.setOpsDept(SecurityUtils.getOpsDept());
        }
        List<RegionGridListVO> topGridList = regionGridMapper.getTopGridList(regionGridListDTO);
        for (RegionGridListVO regionGridListVO : topGridList) {
            List<Long> gridCustCount = regionGridUtilsService.getGridCustCount(regionGridListVO.getGridId());
            regionGridListVO.setRetailCount(gridCustCount.get(0));//获取个人客户数
            regionGridListVO.setMerchantCount(gridCustCount.get(1));//获取商户客户数
            regionGridListVO.setBusinessCount(gridCustCount.get(2));//获取企业客户数

            if (regionGridListVO.getOpsDept().equals("0")) {
                regionGridListVO.setBusinessCount(null);//获取企业客户数
            } else if (regionGridListVO.getOpsDept().equals("1")) {
                regionGridListVO.setRetailCount(null);//获取个人客户数
                regionGridListVO.setMerchantCount(null);
            }

            LambdaQueryWrapper<RegionUserRelate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RegionUserRelate::getGridId, regionGridListVO.getGridId());
            List<RegionUserRelate> regionUserRelates = regionUserRelateMapper.selectList(queryWrapper);
            List<Long> relateDepts = regionUserRelates.stream().map(RegionUserRelate::getRelateDeptId).collect(Collectors.toList());
            List<String> deptNames = regionUserRelates.stream().map(RegionUserRelate::getRelateDeptName).collect(Collectors.toList());
            regionGridListVO.setRelateBranchNames(deptNames.stream().collect(Collectors.joining(",")));

            LambdaQueryWrapper<RegionGrid> gridWrapper = new LambdaQueryWrapper<>();
            gridWrapper.eq(RegionGrid::getParentGridId, regionGridListVO.getGridId());
            List<RegionGrid> regionGrids = regionGridMapper.selectList(gridWrapper);
            if (!regionGrids.isEmpty()) {
                List<String> collect = regionGrids.stream().map(RegionGrid::getGridName).collect(Collectors.toList());
                regionGridListVO.setSecGrids(collect.stream().collect(Collectors.joining(",")));
            }
            regionGridListVO.setIsEdit(regionGridListVO.getDeptId().equals(SecurityUtils.getDeptId())
                    && regionGridListVO.getOpsDept().equals(SecurityUtils.getOpsDept()));
            regionGridListVO.setIsCreate(relateDepts.contains(SecurityUtils.getDeptId()));
            regionGridListVO.setRegionNames(regionGridMapper.getRegionNamesByGridId(regionGridListVO.getGridId()).stream().collect(Collectors.joining(",")));
        }

        return topGridList;
    }

    /**
     * @param regionGridListDTO
     * @return
     */
    @Override
    public List<RegionGridListVO> getSecGridList(RegionGridListDTO regionGridListDTO) {
        if (SecurityUtils.userRole().equals("manager")) {
            return getSecGridListByManager(regionGridListDTO);
        }
        if (SecurityUtils.isHead()) {
            regionGridListDTO.setOpsDept(SecurityUtils.getOpsDept());
        }
        List<RegionGridListVO> secGridList = regionGridMapper.getSecGridList(regionGridListDTO);
        for (RegionGridListVO regionGridListVO : secGridList) {
            List<Long> gridCustCount = regionGridUtilsService.getGridCustCount(regionGridListVO.getGridId());
            regionGridListVO.setRetailCount(gridCustCount.get(0));//获取个人客户数
            regionGridListVO.setMerchantCount(gridCustCount.get(1));//获取商户客户数
            regionGridListVO.setBusinessCount(gridCustCount.get(2));//获取企业客户数

            if (regionGridListVO.getOpsDept().equals("0")) {
                regionGridListVO.setBusinessCount(null);//获取企业客户数
            } else if (regionGridListVO.getOpsDept().equals("1")) {
                regionGridListVO.setRetailCount(null);//获取个人客户数
                regionGridListVO.setMerchantCount(null);
            }

            LambdaQueryWrapper<RegionUserRelate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RegionUserRelate::getGridId, regionGridListVO.getGridId());
            List<RegionUserRelate> regionUserRelates = regionUserRelateMapper.selectList(queryWrapper);
            List<String> branches = new ArrayList<>();
            List<String> outlets = new ArrayList<>();
            List<String> userNames = new ArrayList<>();
            for (RegionUserRelate regionUserRelate : regionUserRelates) {
                if (regionUserRelate.getRelateDeptType().equals("outlet")) {
                    outlets.add(regionUserRelate.getRelateDeptName());
                    SysDept sysDept = sysDeptMapper.selectDeptById(regionUserRelate.getRelateDeptId());
                    branches.add(sysDept.getParentName());
                } else {
                    branches.add(regionUserRelate.getRelateDeptName());
                }
                userNames.add(regionUserRelate.getNickName());
            }
            if (!branches.isEmpty()) {
                regionGridListVO.setRelateBranchNames(branches.stream().distinct().collect(Collectors.joining(",")));
            }
            if (!outlets.isEmpty()) {
                regionGridListVO.setRelateOutletNames(outlets.stream().distinct().collect(Collectors.joining(",")));
            }
            regionGridListVO.setRelateUserNames(userNames.stream().distinct().collect(Collectors.joining(",")));
            regionGridListVO.setIsEdit(regionGridListVO.getDeptId().equals(SecurityUtils.getDeptId()) && SecurityUtils.hasRole("branchAdmin"));
            regionGridListVO.setRegionNames(regionGridMapper.getRegionNamesByGridId(regionGridListVO.getGridId()).stream().collect(Collectors.joining(",")));
        }
        return secGridList;
    }

    /**
     * @param regionGridListDTO
     * @return
     */
    @Override
    public List<RegionGridListVO> getSecGridListByManager(RegionGridListDTO regionGridListDTO) {
        List<RegionGridListVO> secGridListByManager = regionGridMapper.getSecGridListByManager(regionGridListDTO);
        for (RegionGridListVO regionGridListVO : secGridListByManager) {
            List<Long> gridCustCount = regionGridUtilsService.getGridCustCount(regionGridListVO.getGridId());
            regionGridListVO.setRetailCount(gridCustCount.get(0));//获取个人客户数
            regionGridListVO.setMerchantCount(gridCustCount.get(1));//获取商户客户数
            regionGridListVO.setBusinessCount(gridCustCount.get(2));//获取企业客户数

            if (regionGridListVO.getOpsDept().equals("0")) {
                regionGridListVO.setBusinessCount(null);//获取企业客户数
            } else if (regionGridListVO.getOpsDept().equals("1")) {
                regionGridListVO.setRetailCount(null);//获取个人客户数
                regionGridListVO.setMerchantCount(null);
            }

            LambdaQueryWrapper<RegionUserRelate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RegionUserRelate::getGridId, regionGridListVO.getGridId());
            List<RegionUserRelate> regionUserRelates = regionUserRelateMapper.selectList(queryWrapper);
            List<String> branches = new ArrayList<>();
            List<String> outlets = new ArrayList<>();
            List<String> userNames = new ArrayList<>();
            for (RegionUserRelate regionUserRelate : regionUserRelates) {
                if (regionUserRelate.getRelateDeptType().equals("outlet")) {
                    outlets.add(regionUserRelate.getRelateDeptName());
                    SysDept sysDept = sysDeptMapper.selectDeptById(regionUserRelate.getRelateDeptId());
                    branches.add(sysDept.getParentName());
                } else {
                    branches.add(regionUserRelate.getRelateDeptName());
                }
                userNames.add(regionUserRelate.getNickName());
            }
            if (!branches.isEmpty()) {
                regionGridListVO.setRelateBranchNames(branches.stream().distinct().collect(Collectors.joining(",")));
            }
            if (!outlets.isEmpty()) {
                regionGridListVO.setRelateOutletNames(outlets.stream().distinct().collect(Collectors.joining(",")));
            }
            regionGridListVO.setRelateUserNames(userNames.stream().distinct().collect(Collectors.joining(",")));
            regionGridListVO.setRegionNames(regionGridMapper.getRegionNamesByGridId(regionGridListVO.getGridId()).stream().collect(Collectors.joining(",")));
        }

        return secGridListByManager;
    }
}
