package com.ff.base.web.service;

import com.ff.base.core.domain.model.LoginUser;
import com.ff.base.enums.MemberStatus;
import com.ff.base.exception.ServiceException;
import com.ff.base.system.domain.SysUser;
import com.ff.base.system.service.ISysConfigService;
import com.ff.base.system.service.ISysUserService;
import com.ff.base.utils.MessageUtils;
import com.ff.base.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 会员验证处理
 *
 * @author ff
 */
@Service
public class MemberDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private ISysConfigService sysConfigService;


    private static final Logger log = LoggerFactory.getLogger(MemberDetailsServiceImpl.class);

    @Override
    public UserDetails loadUserByUsername(String accountName) throws UsernameNotFoundException {
        SysUser user = userService.selectMemberUserByUserName(accountName);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", accountName);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (MemberStatus.MemberStatus_6.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", accountName);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        passwordService.validate(user);
        String defaultCurrency = sysConfigService.selectConfigByKey("default.currency");
        return createLoginUser(user,defaultCurrency);
    }


    public UserDetails createLoginUser(SysUser user,String defaultCurrency) {
        return new LoginUser(user.getUserId(),defaultCurrency, user);
    }
}
