package com.izouma.wenlvju.repo;

import com.izouma.wenlvju.domain.User;
import com.izouma.wenlvju.enums.AuthorityName;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.security.Authority;
import com.izouma.wenlvju.security.JwtTokenUtil;
import com.izouma.wenlvju.security.JwtUserFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Collections;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepoTest {
    @Autowired
    private UserRepo     userRepo;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Test
    public void testUser() {
        User user = User.builder()
                .username("root")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_ADMIN)))
                .avatar("")
                .build();
        userRepo.save(user);
    }

    @Test
    public void createUser() {

        User user = userRepo.findByUsernameAndDelFalse("chengban11");
        user.setPassword(new BCryptPasswordEncoder().encode("123456"));
        userRepo.save(user);
    }

    @Test
    public void findAllByAuthoritiesContains() {
        List<User> list = userRepo.findAllByAuthoritiesContainsAndDelFalse(Authority.builder()
                .name("ROLE_ADMIN")
                .build());
        System.out.println(list);
    }

    @Test
    public void test() {
        System.out.println(userRepo.findAllByDistrictAndAuthoritiesContainsAndDelFalse("秦淮区", Authority.get(AuthorityName.ROLE_DISTRICT)));
    }

    @Test
    public void test1() {
        List<User> users = userRepo.findAllByAuthoritiesContainsAndDelFalse(Authority.get(AuthorityName.ROLE_EXPERT));
        users.forEach(user -> {
//            user.setPosition(user.getExpert().getPosition());
//            user.setWork(user.getExpert().getWork());
//            userRepo.save(user);
        });
    }

    @Test
    public void test2() {
        User user = userRepo.findById(1L).orElseThrow(new BusinessException("无用户"));
        System.out.println(new BCryptPasswordEncoder().matches("123456", user.getPassword()));
    }

    @Test
    public void test3() {
        System.out.println(jwtTokenUtil.generateToken(JwtUserFactory.create(userRepo.findById(469L)
                .orElseThrow(new BusinessException("用户不存在")))));
    }

}
