package com.chushang.auth.service;

import com.chushang.common.core.constant.SecurityConstants;
import com.chushang.common.core.exception.ResultException;
import com.chushang.common.core.util.IPUtils;
import com.chushang.common.core.util.ServletUtils;
import com.chushang.common.core.web.Result;
import com.chushang.datascope.entity.DataScopeEntity;
import com.chushang.security.utils.SecurityUtils;
import com.chushang.system.entity.enums.LoginStatusEnum;
import com.chushang.system.entity.po.SysLoginInfo;
import com.chushang.system.entity.po.SysUser;
import com.chushang.security.entity.vo.LoginUser;
import com.chushang.system.feign.RemoteLoginInfoService;
import com.chushang.system.feign.RemoteUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * by zhaowenyuan create 2022/5/19 16:49
 */
@Slf4j
@Service
public class UserService {

    @Autowired
    RemoteUserService remoteUserService;
    @Autowired
    RemoteLoginInfoService loginInfoService;
    /**
     * 登录
     */
    public LoginUser<SysUser, DataScopeEntity> login(String username, String password)
    {
        // 查询用户信息
        long start = System.currentTimeMillis();
        Result<LoginUser<SysUser, DataScopeEntity>> rLoginUser = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
        long end = System.currentTimeMillis();
        log.info("time : {}",end - start);
        if (Result.FAIL_CODE == rLoginUser.getCode()){
            throw new ResultException(rLoginUser.getMsg());
        }

        if (ObjectUtils.isEmpty(rLoginUser) || ObjectUtils.isEmpty(rLoginUser.getData()) ){
            recordLoginInfo(username, LoginStatusEnum.LOGIN_FAIL_STATUS, "登录用户不存在");
            throw new ResultException("登录用户：" + username + " 不存在");
        }
        LoginUser<SysUser, DataScopeEntity> loginUser = rLoginUser.getData();
        SysUser sysUser = loginUser.getSysUser();
        Boolean status = sysUser.getStatus();
        if (!status)
        {
            recordLoginInfo(username, LoginStatusEnum.LOGIN_FAIL_STATUS, "用户已停用，请联系管理员");
            throw new ResultException("对不起，您的账号：" + username + " 已停用");
        }
        // 进行比较了
        if (!SecurityUtils.matchesPassword(password, sysUser.getSalt(), sysUser.getPassword()))
        {
            recordLoginInfo(username, LoginStatusEnum.LOGIN_FAIL_STATUS, "用户密码错误");
            throw new ResultException("用户不存在/密码错误");
        }
        recordLoginInfo(username, LoginStatusEnum.LOGIN_SUCCESS, "登录成功");
        loginUser.setSysUser(sysUser);
        return loginUser;
    }

    public static void main(String[] args) {
        String s = SecurityUtils.encryptPassword("123456", "h2HheUVZmF");
        System.out.println(s);
    }

    public void logout(String username) {
        recordLoginInfo(username, LoginStatusEnum.LOGOUT_SUCCESS, "退出成功");
    }

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param loginStatus 状态
     * @param message 消息内容
     */
    public void recordLoginInfo(String username, LoginStatusEnum loginStatus, String message) {
        SysLoginInfo loginInfo = new SysLoginInfo();

        HttpServletRequest request = ServletUtils.getRequest();
        //获取request
        String ipAddr = IPUtils.clientIp(request);
        loginInfo.setUserName(username);
        loginInfo.setIpaddr(ipAddr);
        loginInfo.setMsg(message);
        loginInfo.setStatus(loginStatus);

        try {
            loginInfoService.saveLoginInfo(loginInfo, SecurityConstants.INNER);
        } catch (Exception e) {
            log.error("插入登录日志失败, 失败原因 ", e);
        }
    }

}
