package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.service.AreaService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.TreeBuildUtils;
import org.dromara.common.mybatis.helper.DataBaseHelper;
import org.dromara.common.redis.utils.CacheUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysArea;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.bo.SysAreaBo;
import org.dromara.system.domain.vo.SysAreaVo;
import org.dromara.system.mapper.SysAreaMapper;
import org.dromara.system.mapper.SysRoleMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysAreaService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 区域管理 服务实现
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysAreaServiceImpl implements ISysAreaService, AreaService {

    private final SysAreaMapper baseMapper;
    private final SysRoleMapper roleMapper;
    private final SysUserMapper userMapper;

    /**
     * 查询区域管理数据
     *
     * @param area 区域信息
     * @return 区域信息集合
     */
    @Override
    public List<SysAreaVo> selectAreaList(SysAreaBo area) {
        LambdaQueryWrapper<SysArea> lqw = buildQueryWrapper(area);
        return baseMapper.selectAreaList(lqw);
    }

    /**
     * 查询区域树结构信息
     *
     * @param bo 区域信息
     * @return 区域树信息集合
     */
    @Override
    public List<Tree<Long>> selectAreaTreeList(SysAreaBo bo) {
        // 只查询未禁用区域
        bo.setStatus(UserConstants.DEPT_NORMAL);
        LambdaQueryWrapper<SysArea> lqw = buildQueryWrapper(bo);
        List<SysAreaVo> areas = baseMapper.selectAreaList(lqw);
        return buildAreaTreeSelect(areas);
    }

    private LambdaQueryWrapper<SysArea> buildQueryWrapper(SysAreaBo bo) {
        LambdaQueryWrapper<SysArea> lqw = Wrappers.lambdaQuery();
        lqw.eq(SysArea::getDelFlag, "0");
        lqw.eq(ObjectUtil.isNotNull(bo.getAreaId()), SysArea::getAreaId, bo.getAreaId());
        lqw.eq(ObjectUtil.isNotNull(bo.getParentId()), SysArea::getParentId, bo.getParentId());
        lqw.like(StringUtils.isNotBlank(bo.getAreaName()), SysArea::getAreaName, bo.getAreaName());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysArea::getStatus, bo.getStatus());
        lqw.orderByAsc(SysArea::getAncestors);
        lqw.orderByAsc(SysArea::getParentId);
        lqw.orderByAsc(SysArea::getOrderNum);
        lqw.orderByAsc(SysArea::getAreaId);
        if(bo.getParams()!=null&&bo.getParams().get("areas")!=null){
            lqw.in(SysArea::getAreaId, (List) bo.getParams().get("areas"));
        }
        return lqw;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param areas 区域列表
     * @return 下拉树结构列表
     */
    @Override
    public List<Tree<Long>> buildAreaTreeSelect(List<SysAreaVo> areas) {
        if (CollUtil.isEmpty(areas)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(areas, (area, tree) ->
            tree.setId(area.getAreaId())
                .setParentId(area.getParentId())
                .setName(area.getAreaName())
                .setWeight(area.getOrderNum()));
    }

    /**
     * 根据角色ID查询区域树信息
     *
     * @param roleId 角色ID
     * @return 选中区域列表
     */
//    @Override
//    public List<Long> selectAreaListByRoleId(Long roleId) {
//        SysRole role = roleMapper.selectById(roleId);
//        return baseMapper.selectAreaListByRoleId(roleId, role.getDeptCheckStrictly());
//    }

    /**
     * 根据区域ID查询信息
     *
     * @param areaId 区域ID
     * @return 区域信息
     */
    @Cacheable(cacheNames = CacheNames.SYS_AREA, key = "#areaId")
    @Override
    public SysAreaVo selectAreaById(Long areaId) {
        SysAreaVo area = baseMapper.selectVoById(areaId);
        if (ObjectUtil.isNull(area)) {
            return null;
        }
        SysAreaVo parentArea = baseMapper.selectVoOne(new LambdaQueryWrapper<SysArea>()
            .select(SysArea::getAreaName).eq(SysArea::getAreaId, area.getParentId()));
        area.setParentName(ObjectUtil.isNotNull(parentArea) ? parentArea.getAreaName() : null);
        return area;
    }

    @Override
    public List<SysAreaVo> selectAreaByIds(List<Long> areaIds) {
        return baseMapper.selectAreaList(new LambdaQueryWrapper<SysArea>()
            .select(SysArea::getAreaId, SysArea::getAreaName, SysArea::getLeader)
            .eq(SysArea::getStatus, UserConstants.DEPT_NORMAL)
            .in(CollUtil.isNotEmpty(areaIds), SysArea::getAreaId, areaIds));
    }

    /**
     * 通过区域ID查询区域名称
     *
     * @param areaIds 区域ID串逗号分隔
     * @return 区域名称串逗号分隔
     */
    @Override
    public String selectAreaNameByIds(String areaIds) {
        List<String> list = new ArrayList<>();
        for (Long id : StringUtils.splitTo(areaIds, Convert::toLong)) {
            SysAreaVo vo = SpringUtils.getAopProxy(this).selectAreaById(id);
            if (ObjectUtil.isNotNull(vo)) {
                list.add(vo.getAreaName());
            }
        }
        return String.join(StringUtils.SEPARATOR, list);
    }

    /**
     * 根据ID查询所有子区域数（正常状态）
     *
     * @param areaId 区域ID
     * @return 子区域数
     */
    @Override
    public long selectNormalChildrenAreaById(Long areaId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<SysArea>()
            .eq(SysArea::getStatus, UserConstants.DEPT_NORMAL)
            .apply(DataBaseHelper.findInSet(areaId, "ancestors")));
    }

    /**
     * 是否存在子节点
     *
     * @param areaId 区域ID
     * @return 结果
     */
    @Override
    public boolean hasChildByAreaId(Long areaId) {
        return baseMapper.exists(new LambdaQueryWrapper<SysArea>()
            .eq(SysArea::getParentId, areaId));
    }

    /**
     * 查询区域是否存在用户
     *
     * @param areaId 区域ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkAreaExistUser(Long areaId) {
        return userMapper.exists(new LambdaQueryWrapper<SysUser>()
            .eq(SysUser::getAreaId, areaId));
    }

    /**
     * 校验区域名称是否唯一
     *
     * @param area 区域信息
     * @return 结果
     */
    @Override
    public boolean checkAreaNameUnique(SysAreaBo area) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysArea>()
            .eq(SysArea::getAreaName, area.getAreaName())
            .eq(SysArea::getParentId, area.getParentId())
            .ne(ObjectUtil.isNotNull(area.getAreaId()), SysArea::getAreaId, area.getAreaId()));
        return !exist;
    }

    /**
     * 校验区域是否有数据权限
     *
     * @param areaId 区域id
     */
    @Override
    public void checkAreaDataScope(Long areaId) {
        if (ObjectUtil.isNull(areaId)) {
            return;
        }
        if (LoginHelper.isSuperAdmin()) {
            return;
        }
        if (baseMapper.countAreaById(areaId) == 0) {
            throw new ServiceException("没有权限访问区域数据！");
        }
    }

    /**
     * 新增保存区域信息
     *
     * @param bo 区域信息
     * @return 结果
     */
    @Override
    public int insertArea(SysAreaBo bo) {
        SysArea info = baseMapper.selectById(bo.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("区域停用，不允许新增");
        }
        SysArea area = MapstructUtils.convert(bo, SysArea.class);
        area.setAncestors(info.getAncestors() + StringUtils.SEPARATOR + area.getParentId());
        return baseMapper.insert(area);
    }

    /**
     * 修改保存区域信息
     *
     * @param bo 区域信息
     * @return 结果
     */
    @CacheEvict(cacheNames = CacheNames.SYS_AREA, key = "#bo.areaId")
    @Override
    public int updateArea(SysAreaBo bo) {
        SysArea area = MapstructUtils.convert(bo, SysArea.class);
        SysArea oldArea = baseMapper.selectById(area.getAreaId());
        if (!oldArea.getParentId().equals(area.getParentId())) {
            // 如果是新父区域 则校验是否具有新父区域权限 避免越权
            this.checkAreaDataScope(area.getParentId());
            SysArea newParentArea = baseMapper.selectById(area.getParentId());
            if (ObjectUtil.isNotNull(newParentArea) && ObjectUtil.isNotNull(oldArea)) {
                String newAncestors = newParentArea.getAncestors() + StringUtils.SEPARATOR + newParentArea.getAreaId();
                String oldAncestors = oldArea.getAncestors();
                area.setAncestors(newAncestors);
                updateAreaChildren(area.getAreaId(), newAncestors, oldAncestors);
            }
        }
        int result = baseMapper.updateById(area);
        if (UserConstants.DEPT_NORMAL.equals(area.getStatus()) && StringUtils.isNotEmpty(area.getAncestors())
            && !StringUtils.equals(UserConstants.DEPT_NORMAL, area.getAncestors())) {
            // 如果该区域是启用状态，则启用该区域的所有上级区域
            updateParentAreaStatusNormal(area);
        }
        return result;
    }

    /**
     * 修改该区域的父级区域状态
     *
     * @param area 当前区域
     */
    private void updateParentAreaStatusNormal(SysArea area) {
        String ancestors = area.getAncestors();
        Long[] areaIds = Convert.toLongArray(ancestors);
        baseMapper.update(null, new LambdaUpdateWrapper<SysArea>()
            .set(SysArea::getStatus, UserConstants.DEPT_NORMAL)
            .in(SysArea::getAreaId, Arrays.asList(areaIds)));
    }

    /**
     * 修改子元素关系
     *
     * @param areaId       被修改的区域ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    private void updateAreaChildren(Long areaId, String newAncestors, String oldAncestors) {
        List<SysArea> children = baseMapper.selectList(new LambdaQueryWrapper<SysArea>()
            .apply(DataBaseHelper.findInSet(areaId, "ancestors")));
        List<SysArea> list = new ArrayList<>();
        for (SysArea child : children) {
            SysArea area = new SysArea();
            area.setAreaId(child.getAreaId());
            area.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
            list.add(area);
        }
        if (CollUtil.isNotEmpty(list)) {
            if (baseMapper.updateBatchById(list)) {
                list.forEach(area -> CacheUtils.evict(CacheNames.SYS_AREA, area.getAreaId()));
            }
        }
    }

    /**
     * 删除区域管理信息
     *
     * @param deptId 区域ID
     * @return 结果
     */
    @CacheEvict(cacheNames = CacheNames.SYS_AREA, key = "#areaId")
    @Override
    public int deleteAreaById(Long areaId) {
        return baseMapper.deleteById(areaId);
    }

}
