package com.emergency.avenue.admin.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.emergency.avenue.admin.api.entity.SysDeptRelation;
import com.emergency.avenue.admin.api.entity.SysRole;
import com.emergency.avenue.admin.api.feign.RemoteDataScopeService;
import com.emergency.avenue.admin.service.SysRoleService;
import com.emergency.avenue.common.core.common.DataPermissions;
import com.emergency.avenue.common.core.constant.SecurityConstants;
import com.emergency.avenue.common.core.constant.enums.UserTypeEnum;
import com.emergency.avenue.common.core.util.R;
import com.emergency.avenue.common.core.util.RetOps;
import com.emergency.avenue.common.data.datascope.DataScope;
import com.emergency.avenue.common.data.datascope.DataScopeTypeEnum;
import com.emergency.avenue.common.security.service.AvenueUser;
import com.emergency.avenue.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

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

/**
 * @author avenue
 * @date 2020/11/29
 */
@Slf4j
@Service("dataPermissionsDeptIdHandle")
public class DataPermissionsDeptIdHandle {

	@Resource
	private RemoteDataScopeService dataScopeService;

	@Resource
	private SysRoleService sysRoleService;

	public DataPermissions handleDataScope() {
		AvenueUser user = SecurityUtils.getUser();
		DataPermissions dataPermissions = new DataPermissions();
		// toc 客户端不进行数据权限
		if (UserTypeEnum.TOC.getStatus().equals(user.getUserType())) {
			dataPermissions.setIsOnly(false);
		}

		List<String> roleIdList = user.getAuthorities().stream().map(GrantedAuthority::getAuthority)
				.filter(authority -> authority.startsWith(SecurityConstants.ROLE))
				.map(authority -> authority.split(StrUtil.UNDERLINE)[1]).collect(Collectors.toList());

		List<String> deptList = dataPermissions.getDeptPermissionsList();

		// 当前用户的角色为空 , 返回false
		if (CollUtil.isEmpty(roleIdList)) {
			dataPermissions.setIsOnly(false);
		}
		// @formatter:off
		SysRole role = RetOps.of(R.ok(sysRoleService.findRolesByRoleIds(roleIdList, CollUtil.join(roleIdList, StrUtil.UNDERLINE))))
				.getData()
				.orElseGet(Collections::emptyList)
				.stream()
				.min(Comparator.comparingInt(SysRole::getDsType)).orElse(null);
		// @formatter:on
		// 角色有可能已经删除了
		if (role == null) {
			return null;
		}
		Integer dsType = role.getDsType();

		// 查询全部
		if (DataScopeTypeEnum.ALL.getType() == dsType) {
			dataPermissions.setIsOnly(true);
			return dataPermissions;
		}
		// 自定义
		if (DataScopeTypeEnum.CUSTOM.getType() == dsType && CharSequenceUtil.isNotBlank(role.getDsScope())) {
			String dsScope = role.getDsScope();
			deptList.addAll(
					Arrays.stream(dsScope.split(StrUtil.COMMA)).map(String::toString).collect(Collectors.toList()));
			dataPermissions.setIsOnly(false);
		}
		// 查询本级及其下级
		if (DataScopeTypeEnum.OWN_CHILD_LEVEL.getType() == dsType) {
			// @formatter:off
			List<String> deptIdList = RetOps.of(dataScopeService.getDescendantList(user.getDeptId()))
					.getData()
					.orElseGet(Collections::emptyList)
					.stream()
					.map(SysDeptRelation::getDescendant).collect(Collectors.toList());
			// @formatter:on
			deptList.addAll(deptIdList);
			dataPermissions.setIsOnly(true);
		}
		// 只查询本级
		if (DataScopeTypeEnum.OWN_LEVEL.getType() == dsType) {
			deptList.add(user.getDeptId());
			dataPermissions.setIsOnly(true);
		}

		dataPermissions.setDeptPermissionsList(deptList);
		// 只查询本人
		if (DataScopeTypeEnum.SELF_LEVEL.getType() == dsType) {
			dataPermissions.setUsernamePermissions(user.getUsername());
			dataPermissions.setIsOnly(true);
		}
		return dataPermissions;
	}

}
