package com.chushang.auth.service;

import com.chushang.common.core.enums.PassCodeEnum;
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.security.entity.po.DataScopeEntity;
import com.chushang.security.utils.SecurityUtils;
import com.chushang.system.entity.enums.LoginStatusEnum;
import com.chushang.system.entity.po.SysLoginInfo;
import com.chushang.security.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 login(String username, String password, String appCode)
    {
        PassCodeEnum pce = PassCodeEnum.getEnumByCode(appCode);
        if (pce.getOpenReg()) {
            // 查询用户信息
            long start = System.currentTimeMillis();
            Result<LoginUser> 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.ACCOUNT_EMPTY);
                throw new ResultException("登录用户：" + username + " 不存在");
            }
            LoginUser loginUser = rLoginUser.getData();
            SysUser sysUser = loginUser.getSysUser();
            Boolean isPlatform = sysUser.getIsPlatform();
            if (!isPlatform && !PassCodeEnum.PLATFORM.equals(pce)){
                recordLoginInfo(username, LoginStatusEnum.ACCOUNT_TYPE_ERROR);
                throw new ResultException("对不起，您的账号：" + username + " 不是平台账号");
            }
            Boolean status = sysUser.getStatus();
            if (!status)
            {
                recordLoginInfo(username, LoginStatusEnum.ACCOUNT_STATUS_ERROR);
                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;
        } else {
            throw new ResultException("非法请求端");
        }
    }

    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 状态
     */
    public void recordLoginInfo(String username, LoginStatusEnum loginStatus) {
        SysLoginInfo loginInfo = new SysLoginInfo();

        HttpServletRequest request = ServletUtils.getRequest();
        //获取request
        String ipAddr = IPUtils.clientIp(request);
        loginInfo.setUsername(username);
        loginInfo.setIpaddr(ipAddr);
        loginInfo.setMsg(loginStatus.getDesc());
        loginInfo.setStatus(loginStatus);
        try {
            loginInfoService.saveLoginInfo(loginInfo, SecurityConstants.INNER);
        } catch (Exception e) {
            log.error("插入登录日志失败, 失败原因 ", e);
        }
    }

}
