package com.cxyxiaomo.epp.user.service;

import com.cxyxiaomo.epp.common.pojo.User;
import com.cxyxiaomo.epp.common.vo.UserVO;
import com.cxyxiaomo.epp.user.dao.UserDao;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    public User getUserByUsername(String username) {
        return userDao.getUserByUsername(username);
    }

    public User getUserByWxcode(String wxcode) {
        return userDao.getUserByWxcode(wxcode);
    }

    public User getUserById(Integer id) {
        return userDao.getUserById(id);
    }

    public List<User> getUserList(UserVO userVO) {
        List<User> userList = userDao.getUserList(userVO);
        return userList;
    }

    public boolean addUser(User user) {
        user.setId(null);
        if (user.getPermission() == null) {
            // 填充默认值
            user.setPermission("0");
        }
        return userDao.addUser(user);
    }

    public boolean updateUser(User user) {
        return userDao.updateUser(user);
    }

    public boolean deleteUser(Integer userId) {
        return userDao.deleteUserById(userId);
    }

    /**
     * 修改密码的方法
     *
     * @param oldpwd
     * @param newpwd
     * @return
     */
    public boolean updatePwd(Integer userId, String oldpwd, String newpwd) {
        // 获取当前登录的用户信息
        User user = userDao.getUserById(userId);
        // 创建一个密码加密器
        String oldpwdHash = DigestUtils.sha512Hex(oldpwd);
        // 判断旧密码是否匹配 （或者是未设置密码的初始用户）
        if (Objects.equals(oldpwdHash, user.getPassword()) ||
                (Objects.equals(oldpwd, "") && Objects.equals(user.getPassword(), ""))) {
            // 如果匹配，对新密码进行加密
            String newpwdHash = DigestUtils.sha512Hex(newpwd);
            // 调用mapper层的方法，更新数据库中的密码
            userDao.updatePwd(user.getId(), newpwdHash);
            return true;
        } else {
            // 如果不匹配，返回false
            return false;
        }
    }
}
