package top.lejings.demo.service.impl;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import top.lejings.demo.mapper.UsersMapper;
import top.lejings.demo.pojo.Users;
import top.lejings.demo.service.UsersService;
import top.lejings.demo.utils.Email;
import top.lejings.demo.utils.JwtUtils;
@Slf4j
@Service
public class UsersServiceImpl implements UsersService {

    @Autowired UsersMapper usersMapper;

    @Autowired
    private JavaMailSender javaMailSender;
    public Users login(Users users){return usersMapper.getByUsernameAndPassword(users) ;}

    @Override
    public boolean registered(Users users) {
       if(usersMapper.findById(users)==null){
           Email email = new Email(javaMailSender);
           email.SendSimpleMail(users.getEmail(),users.getUsername()+",您好。","恭喜您，注册成功");
           usersMapper.registered(users);
           return true;
       }
       else{
           return false;
       }

    }

    @Override
    public boolean findPassword(String email) {

        Users users = usersMapper.findPassword(email);
        if(users == null)
        {
            return false;
        }
        else{
            Email sendEmail = new Email(javaMailSender);
            sendEmail.SendSimpleMail(email,users.getUsername()+"您好！请尽快查看您的密码","您的密码为："+users.getPassword());
            return true;
        }

    }

    @Override
    public void revise(Users users) {

        //根据token解析出id，原用户名，原密码来
        Claims claims = JwtUtils.parseJWT(users.getToken());

        Integer user_id = claims.get("user_id", Integer.class); // 假设 user_id 是字符串类型
        log.info("id为{}",user_id);
        String username = claims.get("username", String.class);
        users.setUser_id(user_id);
        log.info("用户修改信息id为{},将用户名{}修改为{},修改密码为{}",user_id,username,users.getUsername(),users.getPassword());
        usersMapper.revise(users);
    }

    @Override
    public void logout(Users users) {
        //解析令牌，得到user_id，将username设置为用户已注销，password等删除
        //根据token解析出id，原用户名，原密码来
        Claims claims = JwtUtils.parseJWT(users.getToken());

        Integer user_id = claims.get("user_id", Integer.class); // 假设 user_id 是字符串类型
        log.info("注销id为{}",user_id);

        usersMapper.logout(user_id);
    }

}
