package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.common.Result;
import com.zhentao.dto.LoginRequest;
import com.zhentao.dto.LoginResponse;
import com.zhentao.pojo.Users;
import com.zhentao.service.UsersService;
import com.zhentao.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/login")
@CrossOrigin
public class UserController {

    @Autowired
    private UsersService usersService;

    @Autowired
    private JwtUtil jwtUtil;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 手机号+密码登录
     */
    @PostMapping("/password")
    public Result<LoginResponse> loginByPhone(@RequestBody LoginRequest request) {
        System.out.println("=== 登录请求 ===");
        System.out.println("手机号: " + request.getPhone());
        System.out.println("密码: " + (request.getPassword() != null ? "已提供" : "未提供"));
        
        if (request == null || request.getPhone() == null || request.getPassword() == null) {
            return Result.error(400, "手机号或密码不能为空");
        }

        // 根据手机号查询用户
        System.out.println("查询用户，手机号: " + request.getPhone());
        Users user = usersService.getOne(new LambdaQueryWrapper<Users>()
                .eq(Users::getPhone, request.getPhone())
                .eq(Users::getStatus, 1), false);

        if (user == null) {
            System.out.println("❌ 未找到用户，手机号: " + request.getPhone());
            return Result.error(401, "账号或密码错误");
        }
        
        System.out.println("✅ 找到用户: " + user.getNickname() + " (ID: " + user.getUserId() + ")");

        // 校验密码：兼容历史明文密码并自动迁移为bcrypt
        String storedPassword = user.getPassword();
        System.out.println("存储的密码格式: " + (storedPassword != null ? storedPassword.substring(0, Math.min(10, storedPassword.length())) + "..." : "null"));
        
        boolean looksBcrypt = storedPassword != null && (
                storedPassword.startsWith("$2a$") || storedPassword.startsWith("$2b$") || storedPassword.startsWith("$2y$")
        );
        
        boolean matches;
        if (looksBcrypt) {
            System.out.println("使用bcrypt验证密码...");
            matches = passwordEncoder.matches(request.getPassword(), storedPassword);
        } else {
            System.out.println("使用明文密码验证...");
            matches = request.getPassword().equals(storedPassword);
            if (matches) {
                System.out.println("首次登录，将密码加密存储");
                // 首次登录成功时，将明文密码迁移为bcrypt哈希
                user.setPassword(passwordEncoder.encode(request.getPassword()));
                usersService.updateById(user);
            }
        }

        if (!matches) {
            System.out.println("❌ 密码验证失败");
            return Result.error(401, "账号或密码错误");
        }
        
        System.out.println("✅ 密码验证成功");

        // 更新最后登录时间
        user.setLastLoginAt(new Date());
        usersService.updateById(user);

        // 生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getUserId());
        claims.put("nickname", user.getNickname());
        claims.put("phone", user.getPhone());
        String token = jwtUtil.generateToken(claims);
        
        System.out.println("✅ JWT token生成成功");

        // 构造响应，避免泄露密码
        user.setPassword(null);
        LoginResponse resp = new LoginResponse();
        resp.setToken(token);
        resp.setUser(user);
        
        System.out.println("✅ 登录成功，返回用户信息");
        System.out.println("返回的用户ID: " + user.getUserId() + " (类型: " + user.getUserId().getClass().getSimpleName() + ")");

        return Result.success(resp);
    }
    
    /**
     * 重置用户密码为简单密码（仅用于测试）
     */
    @PostMapping("/reset-password")
    public Result<String> resetPassword(@RequestParam String phone, @RequestParam String newPassword) {
        System.out.println("=== 重置密码请求 ===");
        System.out.println("手机号: " + phone);
        
        try {
            Users user = usersService.getOne(new LambdaQueryWrapper<Users>()
                    .eq(Users::getPhone, phone), false);
                    
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 设置新密码
            user.setPassword(newPassword); // 明文密码，登录时会自动加密
            usersService.updateById(user);
            
            System.out.println("✅ 密码重置成功，用户: " + user.getNickname());
            return Result.success("密码重置成功，新密码: " + newPassword);
        } catch (Exception e) {
            System.err.println("密码重置失败: " + e.getMessage());
            return Result.error("密码重置失败: " + e.getMessage());
        }
    }
    
    /**
     * 测试接口 - 验证login服务是否正常工作
     */
    @PostMapping("/test")
    public Result<String> testLogin() {
        System.out.println("=== Login服务测试接口 ===");
        System.out.println("服务时间: " + new Date());
        
        try {
            // 测试查询用户ID=1
            Users user = usersService.getOne(new LambdaQueryWrapper<Users>()
                    .eq(Users::getUserId, 1), false);
            
            if (user != null) {
                String testResult = String.format(
                    "Login服务正常！\n测试用户信息:\n- ID: %d\n- 昵称: %s\n- 手机: %s", 
                    user.getUserId(), 
                    user.getNickname(),
                    user.getPhone()
                );
                System.out.println("测试成功: " + testResult);
                return Result.success(testResult, "login_service_ok");
            } else {
                return Result.error("未找到测试用户(ID=1)");
            }
        } catch (Exception e) {
            System.err.println("Login服务测试失败: " + e.getMessage());
            e.printStackTrace();
            return Result.error("服务异常: " + e.getMessage());
        }
    }
}
