package com.hys.app.framework.context.user;

import cn.hutool.core.util.ObjectUtil;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.framework.security.model.Admin;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 用户上下文
 * Created by kingapex on 2018/3/12.
 *
 * @author kingapex
 * @version 1.0
 * @since 7.0.0
 * 2018/3/12
 */
public class AdminUserContext {

    /**
     * 获取当前管理员
     *
     * @return
     */
    public static Admin getAdmin() {


        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        }
        Object someOne = authentication.getDetails();
        if (someOne != null && someOne instanceof Admin) {
            return (Admin) someOne;
        }
        return null;


    }

    /**
     * 获取当前管理员id
     *
     * @return
     */
    public static Long getAdminUserId() {
        Admin admin = getAdmin();
        if (admin == null) {
            return null;
        }
        return admin.getUid();
    }

    /**
     * 获取当前管理员账号
     *
     * @return
     */
    public static String getAdminUserName() {
        Admin admin = getAdmin();
        if (admin == null) {
            return null;
        }
        return admin.getUsername();
    }

    /**
     * 获取当前管理员账号
     *
     * @return
     */
    public static Long getCompanyId() {
        Admin admin = getAdmin();
        if (admin == null) {
            return null;
        }
        return admin.getCompanyId();
    }

    /**
     * 获取当前管理员账号
     *
     * @return
     */
    public static Long hasCompany() {
        Admin admin = getAdmin();
        if (admin == null) {
            throw new ServiceException("未查询到人员信息");
        }
        if (ObjectUtil.isNull(admin.getCompanyId())) {
            throw new ServiceException("平台工作人员不允许操作公司内部业务");
        }
        return admin.getCompanyId();
    }

    /**
     * 获取当前管理员账号
     *
     * @return
     */
    public static void compareCompany(Long companyId) {
        if (ObjectUtil.isNull(getCompanyId())) {
            throw new ServiceException("平台工作人员不允许操作公司内部业务");
        }
        if (!getCompanyId().equals(companyId)) {
            throw new ServiceException("你无权操作此数据");
        }
    }

    /**
     * 获取当前管理员
     *
     * @return
     */
    public static Boolean hasFound() {
        Admin admin = getAdmin();
        if (admin != null && admin.getFounder() == 1) {
            return true;
        }
        return false;
    }
}
