package com.trade.client.enterprise.customer.service.impl;

import com.trade.client.enterprise.customer.domain.model.LoginMo;
import com.trade.client.enterprise.customer.domain.model.LoginUserInfo;
import com.trade.client.enterprise.customer.service.CustomerUserLoginService;
import com.trade.client.enterprise.customer.service.ICTokenService;
import com.trade.common.constant.Constants;
import com.trade.common.constant.HttpStatus;
import com.trade.common.context.AuthenticationContextHolder;
import com.trade.common.exception.ServiceException;
import com.trade.common.utils.LoggerUtil;
import com.trade.common.utils.StringUtils;
import org.slf4j.Logger;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 客户登录业务实现类
 * @Author: wanglang
 * @Date: 2024/5/22 16:42
 * @Version: 1.0
 */
@Service
public class CustomerUserLoginServiceImpl implements CustomerUserLoginService {

    private static final Logger log = LoggerUtil.logger(LoggerUtil.LogFileNameEnum.SYS_LOG);;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private ICTokenService tokenService;

    @Override
    public Map<String, String> login(LoginMo login) {
        if (StringUtils.isEmpty(login.getUserName()) || StringUtils.isEmpty(login.getPassword())) {
            throw new ServiceException("账号与密码不能为空", HttpStatus.BAD_REQUEST);
        }
        Map<String, String> tokenMap = new HashMap<>();
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    login.getUserName(), login.getPassword());
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            log.error("用户={},登录失败={}", login.getUserName(), e);
            if (e instanceof BadCredentialsException) {
                throw new ServiceException("账号或密码错误", HttpStatus.BAD_REQUEST);
            } else {
                throw new ServiceException("登录失败，请检查登录名与密码", HttpStatus.ERROR);
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        LoginUserInfo loginUser = (LoginUserInfo) authentication.getPrincipal();
        // 生成token
        String token = tokenService.createToken(loginUser);
        tokenMap.put(Constants.TOKEN, token);
        return tokenMap;
    }
}
