package com.securitycontrol.auth.service;

import com.securitycontrol.system.api.domain.decision.SysMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.securitycontrol.common.core.constant.SecurityConstants;
import com.securitycontrol.common.core.domain.Result;
import com.securitycontrol.common.core.enums.UserStatus;
import com.securitycontrol.common.core.exception.ServiceException;
import com.securitycontrol.common.core.utils.StringUtils;
import com.securitycontrol.system.api.RemoteUserService;
import com.securitycontrol.system.api.domain.SysUser;
import com.securitycontrol.system.api.model.LoginUser;

import java.util.List;

/**
 * 登录校验方法
 *
 * @author czc
 */
@Component
public class SysLoginService
{
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password,List<SysMenu> list)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("用户/密码必须填写",201);
        }

        // 查询用户信息
        Result<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            throw new ServiceException("登录用户：" + username + " 不存在",201);
        }

        if (Result.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除",201);
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            throw new ServiceException("对不起，您的账号：" + username + " 已锁定",201);
        }
        passwordService.validate(user, password);
        if(list==null){
            Result<List<SysMenu>> menu = remoteUserService.getAllMenuList(user.getUserId()+"", SecurityConstants.INNER);
            list=menu.getData();
        }
        Result<List<SysMenu>> menu = remoteUserService.getAllMenuList(user.getUserId()+"", SecurityConstants.INNER);
        userInfo.getSysUser().setMenus(list);
        recordLogService.recordLogininfor(username, "用户登录", "系统登录");
        return userInfo;
    }

    public void logout(String loginName)
    {
        recordLogService.recordLogininfor(loginName, "用户登出", "退出登录");
    }

}
