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

import javax.annotation.Resource;

import com.trade.client.enterprise.customer.domain.CustomerUser;
import com.trade.client.enterprise.customer.domain.model.LoginUserInfo;
import com.trade.client.enterprise.customer.service.CustomerPasswordService;
import com.trade.client.enterprise.customer.service.CustomerUserService;
import com.trade.common.utils.LoggerUtil;
import org.slf4j.Logger;
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;

import com.trade.common.exception.ServiceException;
import com.trade.common.utils.StringUtils;

/**
 * 用户验证处理
 *
 * @author WL
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerUtil.logger(LoggerUtil.LogFileNameEnum.SYS_LOG);
    @Resource
    private CustomerPasswordService customerPasswordService;
    @Resource
    private CustomerUserService customerUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        CustomerUser user = customerUserService.findByPhoneOrName(username);
        if (StringUtils.isNull(user)) {
            log.error("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        }
        customerPasswordService.validate(user);
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(CustomerUser user) {
        return new LoginUserInfo(user.getId(), user);
    }
}
