package com.rj.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rj.common.PasswordUtil;
import com.rj.entity.sys.User;
import com.rj.mapper.sys.UserMapper;
import com.rj.pojo.sys.LoginRequest;
import com.rj.pojo.sys.LoginResponse;
import com.rj.service.sys.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 系统生成
 * @since 2025-08-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        // 根据用户名查询用户（登录时不走多租户拦截器）
//        User user = this.baseMapper.selectByUserNameIgnoreTenant(loginRequest.getUserName());
        User user = this.baseMapper.selectByPhoneIgnoreTenant(loginRequest.getUserName());

        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证密码
        if (!PasswordUtil.verifyPassword(loginRequest.getPassword(), user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        
        // 生成token
        String token = UUID.randomUUID().toString().replace("-", "")+"+++###==="+user.getRole()+"+++###==="+user.getScenario();
        token = PasswordUtil.encryptPasswordWithDefaultSalt(token);
        // 更新用户的token（登录时不走多租户拦截器，避免添加 tenant_id = null 的限制）
        user.setToken(token);
        this.baseMapper.updateByIdIgnoreTenant(user);
        
        // 构建登录响应
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setUserId(user.getUserId());
        loginResponse.setUserName(user.getUserName());
        loginResponse.setEmail(user.getEmail());
        loginResponse.setPhone(user.getPhone());
        loginResponse.setAvatar(user.getAvatar());
        loginResponse.setToken(token);
        loginResponse.setLoginTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        loginResponse.setTenantId(user.getTenantId());
        loginResponse.setRoleName(user.getRoleName());
        loginResponse.setScenario(user.getScenario());

        return loginResponse;
    }

    @Override
    public User getUserByUserName(String userName) {
        // 供其他业务使用的通用查询，保持按租户隔离
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, userName);
        return this.getOne(queryWrapper);
    }

    @Override
    public User getUserByToken(String token) {
        // 用于 token 验证等场景，需跨租户查询用户
        return this.baseMapper.selectByTokenIgnoreTenant(token);
    }

    @Override
    public User getUserInfoByToken(String token) {
        // 获取用户详细信息，同样使用跨租户查询
        return this.baseMapper.selectByTokenIgnoreTenant(token);
    }

}
