package com.infoepoch.pms.dispatchassistant.controller.basic;

import com.infoepoch.pms.dispatchassistant.common.component.RedisTool;
import com.infoepoch.pms.dispatchassistant.common.constant.RedisKeys;
import com.infoepoch.pms.dispatchassistant.common.exception.NotLoginException;
import com.infoepoch.pms.dispatchassistant.common.utils.JsonUtils;
import com.infoepoch.pms.dispatchassistant.common.utils.ServletTool;
import com.infoepoch.pms.dispatchassistant.domain.basic.organization.Organization;
import com.infoepoch.pms.dispatchassistant.domain.basic.organization.OrganizationRoot;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Auth {

    @Autowired
    private RedisTool redisTool;


    /**
     * 取当前登录信息，如未登录抛出NotLoginException
     */
    public User getUserReq() throws NotLoginException {
        User user = getUser();
        if (user != null)
            return user;

        throw new NotLoginException();
    }

    /**
     * 取当前登录信息，如未登录返回null
     */
    public User getUser() {
        String sign = ServletTool.getSign();
        String userStr = redisTool.get(RedisKeys.AUTHED_USER + sign);
        if(userStr == null)
            return null;
        User user = JsonUtils.jsonToObject(userStr, User.class);
        fillOrganizationName(user);
        return user;
    }

    /**
     *
     * @param user
     */
    private void fillOrganizationName(User user) {
        if (user == null)
            return;

        Organization organization = OrganizationRoot.getOrganizationById(user.getOrganizationId());
        user.setOrganizationName(organization == null ? null : organization.getName());
    }
    /**
     * 获取移动端用户信息
     *
     * @return
     * @throws NotLoginException
     */
    public User getMobileUserReq() throws NotLoginException {
        User user = getMobileUser();
        if (user != null)
            return user;
        throw new NotLoginException();
    }
    /**
     * 获取移动端登录用户信息，如未登录返回null
     *
     * @return
     */
    public User getMobileUser() {
        String token = ServletTool.getToken();
        User user = redisTool.get(RedisKeys.AUTHED_USER + token);
        return user;
    }

}
