package com.jwipc.security;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.jwipc.security.dto.CurrentUserDTO;
import com.jwipc.security.prop.SecurityProp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * <p> </p>
 *
 * @author ZhangJie
 * @version 1.0
 * @since JDK 1.8
 */
@Component
@Slf4j
public class LoginUtil {
    private static SecurityProp securityProp;

    @Autowired
    public void setSecurityProp(SecurityProp securityProp) {
        this.securityProp = securityProp;
    }

    public static CurrentUserDTO getCurrentUser() {
        if (!StpUtil.isLogin()) {
            throw new NotLoginException("", "", "");
        }
        final Object user = StpUtil.getSession().get(securityProp.getUserKey());
        if (Objects.isNull(user)) {
            return null;
        }
        final String jsonString = JSON.toJSONString(user);
        return JSON.parseObject(jsonString, CurrentUserDTO.class);
    }

    public static Long getUserId() {
        if (Objects.isNull(getCurrentUser())) {
            return null;
        }
        return getCurrentUser().getUserId();
    }

    public static Long getSupplierId() {
        if (Objects.isNull(getCurrentUser())) {
            return null;
        }
        if (isSupplier()) {
            return getCurrentUser().getSupplierId();
        } else {
            throw new RuntimeException("登录用户不是供应商");
        }

    }

    public static String getSupplierCode() {
        if (Objects.isNull(getCurrentUser())) {
            return null;
        }
        if (isSupplier()) {
            return getCurrentUser().getSupplierCode();
        } else {
            throw new RuntimeException("登录用户不是供应商");
        }

    }

    public static String getName() {
        if (Objects.isNull(getCurrentUser())) {
            return null;
        }
        return getCurrentUser().getName();
    }

    public static String getAccount() {
        if (Objects.isNull(getCurrentUser())) {
            return null;
        }
        return getCurrentUser().getLoginName();
    }

    public static String getDeptCode() {
        if (Objects.isNull(getCurrentUser())) {
            return null;
        }
        return getCurrentUser().getDeptCode();
    }

    public static boolean isSupplier() {
        if (Objects.isNull(getCurrentUser())) {
            return false;
        }
        return !Objects.isNull(getCurrentUser().getSupplierId());
    }

    public static List<String> getRoleCodes() {
        if (Objects.isNull(getCurrentUser())) {
            return Collections.emptyList();
        }
        return getCurrentUser().getRoles();
    }
}
