package com.njzscloud.supervisory.sys.auth.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njzscloud.common.security.contant.AuthWay;
import com.njzscloud.common.security.support.*;
import com.njzscloud.common.security.util.SecurityUtil;
import com.njzscloud.supervisory.biz.pojo.result.SearchCompanyResult;
import com.njzscloud.supervisory.sys.auth.mapper.AuthMapper;
import com.njzscloud.supervisory.sys.auth.pojo.result.MyResult;
import com.njzscloud.supervisory.sys.user.pojo.entity.UserEntity;
import com.njzscloud.supervisory.sys.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Slf4j
@Service
@RequiredArgsConstructor
public class AuthService implements IUserService, IResourceService, IRoleService {
    private final AuthMapper authMapper;
    private final UserService userService;

    @Override
    public UserDetail selectUser(String account, AuthWay authWay) {
        switch (authWay) {
            case PASSWORD:
                return authMapper.selectUser(Wrappers.query().eq("a.username", account).eq("a.deleted", 0));
            case PHONE:
                return authMapper.selectUser(Wrappers.query().eq("a.phone", account).eq("a.deleted", 0));
            case WECHAT:
            case WECHAT_MINI:
            default:
                return null;
        }
    }

    @Override
    public Resource selectResourceByUserId(Long userId) {
        List<MenuResource> menuResources = authMapper.selectUserMenu(userId);
        List<EndpointResource> endpointResource = authMapper.selectUserEndpoint(userId);
        return new Resource()
                .setMenu(menuResources)
                .setEndpoint(endpointResource);
    }

    @Override
    public Set<String> selectRoleByUserId(Long userId) {
        return authMapper.selectRoleByUserId(userId);
    }

    /**
     * 获取当前登录人信息
     */
    public MyResult my() {
        Long userId = SecurityUtil.currentUserId();
        UserEntity userEntity = userService.getById(userId);
        List<MenuResource> menuResources = authMapper.selectUserMenu(userId);
        List<EndpointResource> endpointResources = authMapper.selectUserEndpoint(userId);
        SearchCompanyResult company = authMapper.selectCompanyInfo(userId);

        return BeanUtil.copyProperties(userEntity, MyResult.class).setMenus(menuResources).setEndpoints(endpointResources).setCompany(company);
    }

}
