package com.easyproject.core.web.service;

import com.easyproject.common.core.domain.entity.ClientMember;
import com.easyproject.common.core.domain.model.LoginMember;
import com.easyproject.common.utils.MessageUtils;
import com.easyproject.clientbus.service.member.IClientMemberService;
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;
import com.easyproject.common.enums.UserStatus;
import com.easyproject.common.exception.ServiceException;
import com.easyproject.common.utils.StringUtils;

/**
 * 用户验证处理
 *
 * @author java001
 */
@Service
public class MemberDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(MemberDetailsServiceImpl.class);

    @Autowired
    private IClientMemberService memberService;

    @Autowired
    private MemberPasswordService passwordService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        ClientMember member = memberService.selectMemberByMemberName(username);
        if (StringUtils.isNull(member))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("member.login.verify"));
        }
        else if (UserStatus.DELETED.getCode().equals(member.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("member.login.verify"));
        }
        else if (UserStatus.DISABLE.getCode().equals(member.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("member.login.account.error"));
        }

        passwordService.validate(member);

        return createLoginUser(member);
    }

    public UserDetails createLoginUser(ClientMember member)
    {
        return new LoginMember(member.getId(),  member);
    }
}
