package com.corewing.app.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.corewing.app.entity.SysUser;
import com.corewing.app.mapper.SysUserMapper;
import com.corewing.app.service.SysUserService;
import com.corewing.app.util.I18nUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * 后台管理用户 Service 实现类
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Override
    public SysUser getByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            return null;
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username);
        return this.getOne(wrapper);
    }

    @Override
    public String login(String username, String password, String loginIp) {
        // 查询用户
        SysUser user = getByUsername(username);
        if (user == null) {
            throw new RuntimeException(I18nUtil.getMessage("error.user.not.found"));
        }

        // 验证密码（MD5加密）
        String encryptPassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        System.out.println(encryptPassword);
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
            throw new RuntimeException(I18nUtil.getMessage("error.password.incorrect"));
        }

        // 检查用户状态
        if (user.getStatus() == 0) {
            throw new RuntimeException(I18nUtil.getMessage("error.account.disabled"));
        }

        // 更新登录信息
        updateLoginInfo(user.getId(), loginIp);

        // 登录成功，使用 Sa-Token 生成 token（使用 sys 作为登录类型区分）
        StpUtil.login(user.getId(), "sys");
        return StpUtil.getTokenValue();
    }

    @Override
    public void updateLoginInfo(Long userId, String loginIp) {
        SysUser user = new SysUser();
        user.setId(userId);
        user.setLoginIp(loginIp);
        user.setLoginTime(LocalDateTime.now());
        this.updateById(user);
    }
}
