package com.jiayue.ipp.common.security.user.impl;

import com.jiayue.ipp.common.data.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author Yh
 */
@Service
@Slf4j
public class JwtUserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    SysUserServiceImpl sysUserServiceImpl;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = null;
        String password = null;
        SysUser sysUser = sysUserServiceImpl.findByUserName(username);
//        if ("admin".equals(username)) {
//            if (sysUser == null || sysUser.getUserName().isEmpty()) {
//                sysUser = new SysUser();
//                sysUser.setUserName("admin");
//                sysUser.setPassWord("!QAZ2wsx");
//                sysUser.setName("admin");
//                sysUser.setPwdErrNum(0);
//                sysUser.setLockTime(0L);
//                sysUser.setStatus("0");
//                sysUserService.save(sysUser);
//            }
//        }
        if(sysUser == null){
            password = passwordEncoder.encode("sda21dsad13214sda22dsa@#$#$%!ds1d1");
        }else {
            password = passwordEncoder.encode(sysUser.getPassWord());
            if (sysUser.getStatus().equals("1") && (System.currentTimeMillis() - sysUser.getLockTime()) < 300000) {
                password = passwordEncoder.encode("sda21dsad13214sda22dsa@#$#$%!ds1d1");
            }

            if (sysUser.getStatus().equals("2")) {
                password = passwordEncoder.encode("sda21dsad13214sda22dsa@#$#$%!ds1d1");
            }
        }
        user = new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList(username.toUpperCase()));
        return user;
    }
}
