package com.yinlihupo.enlish.service.service.user;

import cn.dev33.satoken.stp.StpUtil;
import com.yinlihupo.enlish.service.constant.UserRedisConstants;
import com.yinlihupo.enlish.service.domain.dataobject.UserDO;
import com.yinlihupo.enlish.service.domain.mapper.UserDOMapper;
import com.yinlihupo.enlish.service.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class UserServiceImpl implements UserService {


    @Resource
    private UserDOMapper userDOMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDO findUser() {
        String loginIdStr =(String) StpUtil.getLoginId();
        Long loginId = Long.parseLong(loginIdStr);
        return userDOMapper.selectById(loginId);
    }

    @Override
    public List<UserDO> findUsersList(int page, int limit, String name) {

        return userDOMapper.selectUserDOList(name, (page - 1) * limit, limit);
    }

    @Override
    public Integer findUserTotal() {
        return userDOMapper.selectUserTotal();
    }

    @Override
    public void createUser(UserDO userDO) {
        userDOMapper.insert(userDO);
    }

    @Override
    public void updateUserInfo(String password, String reqCode, String phone, String name) {
        long id = Integer.parseInt(String.valueOf(StpUtil.getLoginId()));
        UserDO userDO = userDOMapper.selectById(id);

        String key = UserRedisConstants.buildUserLoginCode(userDO.getPhone());
        String code = Objects.requireNonNull(redisTemplate.opsForValue().get(key)).toString();
        if (code == null || !code.equals(reqCode)) {
            throw new RuntimeException("验证码错误");
        }

        if (password != null) {
            password = passwordEncoder.encode(password);
        }
        userDOMapper.updateUserInfo(id, name, password, phone);
    }

}
