package org.springblade.plugin.workflow.core.user;

import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.system.pojo.entity.User;
import org.springblade.system.feign.IUserSearchClient;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 系统用户
 * 统一用户入口，防止更改包名的情况再次出现
 *
 * @author ssc
 */
@Service
public class WfUserService {

    private static IUserSearchClient userSearchService;

    private static IUserSearchClient getUserSearchService() {
        if (userSearchService == null) {
            userSearchService = SpringUtil.getBean(IUserSearchClient.class);
        }
        return userSearchService;
    }

    public List<WfUser> listByUser(List<Long> userId) {
        R<List<User>> r = getUserSearchService().listByUser(Func.join(userId));
        if (r == null) {
            return new ArrayList<>();
        }
		// 根据传入的id重新排序
		Map<Long, User> userMap = r.getData().stream()
			.collect(Collectors.toMap(User::getId, Function.identity()));

		return userId.stream()
			.map(id -> {
				User user = userMap.get(id);
				return user != null ? BeanUtil.copyProperties(user, WfUser.class) : null;
			})
			.filter(Objects::nonNull)
			.collect(Collectors.toList());
    }

    public List<WfUser> listByDept(List<Long> deptId) {
        R<List<User>> r = getUserSearchService().listByDept(Func.join(deptId));
        if (r == null) {
            return new ArrayList<>();
        }
        return BeanUtil.copyProperties(r.getData(), WfUser.class);
    }

    public List<WfUser> listByPost(List<Long> postId) {
        R<List<User>> r = getUserSearchService().listByPost(Func.join(postId));
        if (r == null) {
            return new ArrayList<>();
        }
        return BeanUtil.copyProperties(r.getData(), WfUser.class);
    }

    public List<WfUser> listByRole(List<Long> roleId) {
        R<List<User>> r = getUserSearchService().listByRole(Func.join(roleId));
        if (r == null) {
            return new ArrayList<>();
        }
        return BeanUtil.copyProperties(r.getData(), WfUser.class);
    }
}
