package ink.wgink.login.base.service.user;

import com.alibaba.fastjson.JSONObject;
import ink.wgink.exceptions.SearchException;
import ink.wgink.interfaces.user.IUserDetailCheckService;
import ink.wgink.login.base.exceptions.UserAuthenticationException;
import ink.wgink.service.user.enums.UserStateEnum;
import ink.wgink.service.user.pojo.pos.UserPO;
import ink.wgink.service.user.service.IUserService;
import ink.wgink.service.user.util.UserUtil;
import ink.wgink.util.date.DateUtil;
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;

/**
 * @ClassName: UserDetailServiceImpl
 * @Description: User Detail
 * @Author: WangGeng
 * @Date: 2019/2/18 3:06 PM
 * @Version: 1.0
 **/
@Service
public class UserDetailServiceImpl implements UserDetailsService, IUserDetailCheckService {

    @Autowired
    private IUserService userService;

    public UserDetailServiceImpl() {
        super();
    }

    @Override
    public UserDetails loadUserByUsername(String userInfo) throws UsernameNotFoundException {
        String username;
        try {
            JSONObject userInfoObject = JSONObject.parseObject(userInfo);
            username = userInfoObject.getString("userUsername");
        } catch (Exception e) {
            username = userInfo;
        }
        // 通过用户名查询
        UserPO userPO = userService.getPOByUsername(username.toLowerCase());
        if (null == userPO) {
            throw new UserAuthenticationException("账号不存在");
        }
        if (userPO.getUserState() == UserStateEnum.UN_EXAMINE.getValue()) {
            throw new SearchException("用户未审核");
        }
        if (userPO.getUserState() == UserStateEnum.UN_PASS.getValue()) {
            throw new SearchException("用户审核未通过");
        }
        if (userPO.getUserState() == UserStateEnum.LOCK.getValue()) {
            throw new UserAuthenticationException("账号已锁定");
        }
        if (DateUtil.isDateExpired(userPO.getUserExpiredDate())) {
            throw new UserAuthenticationException("账号已经过期");
        }
        return UserUtil.createLoginUser(userPO);
    }

}
