package com.zhongshu.card.server.core.service.org;

import com.github.microservice.auth.security.type.AuthType;
import com.zhongshu.card.server.core.dao.org.OrganizationDao;
import com.zhongshu.card.server.core.domain.org.Organization;
import com.zhongshu.card.server.core.domain.org.OrganizationUser;
import com.zhongshu.card.server.core.service.base.SuperService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 用户机构权限 查询
 *
 * @author TRX
 * @date 2024/11/14
 */
@Slf4j
@Service
public class UserOrgPermissService extends SuperService {

    @Autowired
    private OrganizationDao organizationDao;

    @Autowired
    private OrganizationUserServiceImpl organizationUserServiceImpl;

    /**
     * 判断用户是否是项目管理员
     *
     * @param projectOid
     * @param userId
     * @return
     */
    public boolean userIsProjectManager(String projectOid, String userId) {
        if (StringUtils.isNotEmpty(projectOid) && StringUtils.isNotEmpty(userId)) {
            Organization projectInfo = organizationDao.findTopByOid(projectOid);
            if (ObjectUtils.isNotEmpty(projectInfo) && projectInfo.getAuthType() == AuthType.Project) {
                List<String> managerUserIds = projectInfo.getManagerUserIds();
                if (ObjectUtils.isNotEmpty(managerUserIds) && managerUserIds.contains(userId)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断用户加入的 项目下的结构oid集合
     *
     * @param projectOid
     * @param userId
     * @return
     */
    public List<String> getUserManagerOids(String projectOid, String userId) {
        return organizationUserServiceImpl.getUserOrgListOids(userId, projectOid);
    }

    /**
     * 查询用户加入的机构列表
     *
     * @param projectOid 项目oid
     * @param userId     用户userId
     * @return
     */
    public List<Organization> getUserOrgList(String projectOid, String userId) {
        List<Organization> list = new ArrayList<>();
        List<OrganizationUser> userOrgList = organizationUserServiceImpl.getUserOrgList(userId, projectOid);
        if (ObjectUtils.isNotEmpty(userOrgList)) {
            list = userOrgList.stream().map(it -> it.getOrganization()).collect(Collectors.toList());
        }
        return list;
    }

}
