/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package easydo.technology.system.service.impl;

import easydo.technology.components.JdbcClient;
import easydo.technology.system.domain.Dept;
import easydo.technology.system.domain.SysDept;
import easydo.technology.system.domain.SysRolesDepts;
import easydo.technology.system.dto.*;
import easydo.technology.system.service.DataService;
import easydo.technology.system.service.DeptService;
import easydo.technology.system.service.RoleService;
import easydo.technology.utils.enums.DataScopeEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Zheng Jie
 * @website https://el-admin.vip
 * @description 数据权限服务实现
 * @date 2020-05-07
 **/
@Service
@RequiredArgsConstructor
//@CacheConfig(cacheNames = "data")
public class DataServiceImpl implements DataService {

    private final RoleService roleService;
    private final DeptService deptService;
    private final JdbcClient jdbcClient;
    private final DataSource dataSource;

    /**
     * 用户角色改变时需清理缓存
     * @param user /
     * @return /
     */
    @Override
    //@Cacheable(key = "'user:' + #p0.id")
    public List<Long> getDeptIds(UserDto user) {
        // 用于存储部门id
        Set<Long> deptIds = new HashSet<>();
        // 查询用户角色
        List<RoleSmallDto> roleSet = roleService.findByUsersId(user.getId());
        // 获取对应的部门ID
        for (RoleSmallDto role : roleSet) {
            DataScopeEnum dataScopeEnum = DataScopeEnum.find(role.getDataScope());
            switch (Objects.requireNonNull(dataScopeEnum)) {
                case THIS_LEVEL:
                    deptIds.add(user.getDept().getId());
                    break;
                case CUSTOMIZE:
                    deptIds.addAll(getCustomize(deptIds, role));
                    break;
                default:
                    return new ArrayList<>(deptIds);
            }
        }
        return new ArrayList<>(deptIds);
    }

    /**
     * 获取自定义的数据权限
     * @param deptIds 部门ID
     * @param role 角色
     * @return 数据权限ID
     */
    public Set<Long> getCustomize(Set<Long> deptIds, RoleSmallDto role){
        Set<DeptDto> depts = deptService.findByRoleId(role.getId());
        for (DeptDto dept : depts) {
            deptIds.add(dept.getId());
            List<Dept> deptChildren = deptService.findByPid(dept.getId());
            if (deptChildren != null && deptChildren.size() != 0) {
                deptIds.addAll(deptService.getDeptChildren(dept.getId(), deptChildren));
            }
        }
        return deptIds;
    }

    /**
     * 实测 可替代 getDeptIds方法
     * @param user
     * @return
     */
    @Override
    public List<Long> getUserDeptIds(UserDto user) {
        // 用于存储部门id
        Set<Long> deptIds = new HashSet<>();
        // 查询用户角色
        List<RoleSmallDto> roleSet = roleService.findByUsersId(user.getId());
        // 获取对应的部门ID
        for (RoleSmallDto role : roleSet) {
            DataScopeEnum dataScopeEnum = DataScopeEnum.find(role.getDataScope());
            switch (Objects.requireNonNull(dataScopeEnum)) {
                case THIS_LEVEL:
                    deptIds.add(user.getDept().getId());
                    break;
                //自定义的数据权限
                case CUSTOMIZE:
                    getRoleDeptIds(deptIds, role);
                    break;
                default:
                    return new ArrayList<>(deptIds);
            }
        }
        return new ArrayList<>(deptIds);
    }

    public void getRoleDeptIds(Set<Long> deptIds, RoleSmallDto role) {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            //查询当前角色关联的所有 部门信息
            HashMap<String, Object> map = new HashMap<String, Object>() {{
                put("roleId", role.getId());
            }};
            List<SysRolesDepts> rolesDepts = jdbcClient.getJdbcList(map, SysRolesDepts.class,connection);

            Set<Long> collect = rolesDepts.stream()
                    .map(SysRolesDepts::getDeptId)
                    .collect(Collectors.toSet());

            List<SysDept> depts = jdbcClient.getJdbcList(new SysDept(),connection);
            for (SysDept item : depts) {
                //如果现有的部门集合id中 存在 当前元素的 父id  将现有集合元素的主键放入deptIds
                if (collect.contains(item.getPid())){
                    collect.add(item.getDeptId());
                }
            }
            deptIds.addAll(collect);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
