package com.njzscloud.common.security.contant;

import cn.hutool.core.collection.CollUtil;
import com.njzscloud.common.core.ienum.DictInt;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 字典代码：client_code
 * 字典名称：客户端代码
 */
@Getter
@RequiredArgsConstructor
public enum ClientCode implements DictInt {
    PC(1, "电脑端"),
    WX_MINI_APP(2, "微信小程序"),
    ;

    private final Integer val;

    private final String txt;

    public static int getClientCode(List<Integer> clients) {
        if (CollUtil.isEmpty(clients)) return 0;
        var clientCode = 0;
        for (var client : clients) {
            clientCode |= client;
        }
        return clientCode;
    }

    public static List<ClientCode> getClients(int clientCode) {
        return Arrays.stream(ClientCode.class.getEnumConstants()).filter(it -> it.hasClient(clientCode)).toList();
    }

    public static boolean valid(int clientCode) {

        Optional<Integer> max = Arrays.stream(ClientCode.class.getEnumConstants())
            .map(ClientCode::getVal)
            .reduce((a, b) -> a | b);
        return max.orElse(0) >= clientCode;
    }

    public static Optional<ClientCode> getClient(int clientCode) {
        return Arrays.stream(ClientCode.class.getEnumConstants()).filter(it -> it.hasClient(clientCode)).findFirst();
    }

    /**
     * 检查是否有登录权限
     */
    public boolean hasClient(int clientCode) {
        return (this.val & clientCode) != 0;
    }
}
