package com.stdproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stdproject.entity.AppUser;
import com.stdproject.mapper.AppUserMapper;
import com.stdproject.service.IAppUserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;

/**
 * <p>
 * 应用系统_系统用户 服务实现类
 * </p>
 *
 * @author StdProject
 * @since 2023-12-07
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public AppUser findByUsername(String username) {
        return getOne(new QueryWrapper<AppUser>().eq("username", username).select( "id", "username","password","status", "orgid", "usertype","nickname"));
    }

    @Override
    public String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return authentication.getName();
        }
        return null;
    }

    @Override
    public AppUser getCurrentUser() {
        String username = getCurrentUsername();
        if (StringUtils.hasText(username)) {
            return findByUsername(username);
        }
        return null;
    }

    @Override
    public boolean changePassword(String username, String oldPassword, String newPassword) {
        if (!StringUtils.hasText(username) || !StringUtils.hasText(oldPassword) || !StringUtils.hasText(newPassword)) {
            return false;
        }

        // 获取完整的用户信息（包含密码）
        AppUser user = getOne(new QueryWrapper<AppUser>().eq("username", username));
        if (user == null) {
            return false;
        }

        // 验证原密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return false;
        }

        // 更新新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        user.setPwdresettime(LocalDateTime.now());

        return updateById(user);
    }
}
