package com.ruoyi.web.service.front;

import java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.generator.domain.front.FrontUser;
import com.ruoyi.generator.service.front.IFrontUserService;

@Component
public class FrontAuthService
{
    @Autowired
    private IFrontUserService frontUserService;

    @Autowired
    private TokenService tokenService;

    public String login(String username, String password)
    {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            throw credentialException();
        }

        FrontUser frontUser = frontUserService.selectByUsername(username);
        if (frontUser == null || StringUtils.isEmpty(frontUser.getPassword())
                || !matchesPassword(password, frontUser.getPassword()))
        {
            throw credentialException();
        }
        if (UserStatus.DISABLE.getCode().equals(frontUser.getStatus()))
        {
            throw new ServiceException("前台账号已停用");
        }
        if (UserStatus.DELETED.getCode().equals(frontUser.getDelFlag()))
        {
            throw new ServiceException("前台账号已删除");
        }

        SysUser tokenUser = new SysUser();
        tokenUser.setUserId(frontUser.getUserId());
        tokenUser.setUserName(frontUser.getUsername());
        tokenUser.setNickName(StringUtils.nvl(frontUser.getNickname(), frontUser.getUsername()));
        tokenUser.setPassword(frontUser.getPassword());

        LoginUser loginUser = new LoginUser(frontUser.getUserId(), null, tokenUser, Collections.emptySet());
        loginUser.setLoginType(Constants.LOGIN_TYPE_FRONT);
        String token = tokenService.createToken(loginUser);
        frontUserService.updateLastLoginTime(frontUser.getUserId());
        return token;
    }

    public FrontUser profile(Long userId)
    {
        FrontUser frontUser = frontUserService.selectById(userId);
        if (frontUser != null)
        {
            frontUser.setPassword(null);
        }
        return frontUser;
    }

    private boolean matchesPassword(String password, String encodedPassword)
    {
        try
        {
            return SecurityUtils.matchesPassword(password, encodedPassword);
        }
        catch (IllegalArgumentException e)
        {
            return false;
        }
    }

    private ServiceException credentialException()
    {
        return new ServiceException("用户名或密码错误");
    }
}
