package com.chushang.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chushang.common.core.exception.ResultException;
import com.chushang.common.core.util.SpringUtils;
import com.chushang.common.core.util.StringUtils;
import com.chushang.datascope.annotation.DataScope;
import com.chushang.system.mapper.SysDeptMapper;
import com.chushang.system.service.ISysUserService;
import com.chushang.security.utils.SecurityUtils;
import com.chushang.system.entity.dto.ListDeptDTO;
import com.chushang.system.entity.po.SysDept;
import com.chushang.system.entity.po.SysRole;
import com.chushang.system.entity.vo.TreeSelect;
import com.chushang.system.service.ISysDeptService;
import com.chushang.system.service.ISysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门用于控制各平台的数据权限 服务实现类
 * </p>
 * @author author
 * @since 2022-08-18
 */
@Slf4j
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    @Autowired
    ISysRoleService roleService;
    @Autowired
    ISysUserService userService;

    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(ListDeptDTO listDept) {
        return baseMapper.selectDeptList(listDept);
    }

    @Override
    public void checkDeptDataScope(Long deptId) {
        if (!SecurityUtils.isAdmin()){
            ListDeptDTO dept = new ListDeptDTO();
            dept.setDeptId(deptId);
            List<SysDept> deptList = SpringUtils.getAopProxy(this).selectDeptList(dept);
            if (CollectionUtil.isEmpty(deptList))
            {
                throw new ResultException("没有权限访问部门数据！");
            }
        }
    }

    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> deptList) {
        List<SysDept> deptTrees = buildDeptTree(deptList);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<SysDept> buildDeptTree(List<SysDept> deptList)
    {
        if (CollectionUtil.isNotEmpty(deptList)){
            List<SysDept> returnList = new ArrayList<>();
            List<Long> tempList =
                    deptList.stream().map(SysDept::getDeptId).toList();
            for (SysDept dept : deptList)
            {
                // 如果是顶级节点, 遍历该父节点的所有子节点
                if (!tempList.contains(dept.getParentId()))
                {
                    recursionFn(deptList, dept);
                    returnList.add(dept);
                }
            }
            if (returnList.isEmpty())
            {
                returnList = deptList;
            }
            return returnList;
        }
        return deptList;
    }

    @Override
    public List<Long> selectDeptListByRoleId(Long roleId) {
        SysRole sysRole = roleService.selectRoleById(roleId);
        return baseMapper.selectDeptListByRoleId(roleId, sysRole.isDeptCheckStrictly());
    }

    @Override
    public boolean checkDeptExistUser(Long deptId) {
        return userService.checkDeptExistUser(deptId);
    }

    @Override
    public void updateDeptChildren(List<SysDept> children) {
        baseMapper.updateDeptChildren(children);
    }

    @Override
    public List<String> listScopeDeptIdByRoleId(Long roleId) {
        return baseMapper.listScopeDeptIdByRoleId(roleId);
    }

    @Override
    public List<String> listScopeDeptIdByDeptId(Long deptId) {
        return baseMapper.listScopeDeptIdByDeptId(deptId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> cList = new ArrayList<>();
        for (SysDept n : list) {
            if (StringUtils.isNotNull(n.getParentId()) && Objects.equals(n.getParentId(), t.getDeptId())) {
                cList.add(n);
            }
        }
        return cList;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0;
    }
}
