package com.example.system.controller;

import com.example.system.model.Result;
import com.example.system.model.UserTable;
import com.example.system.service.UserService;
import com.example.system.utils.JWTUtil;
import com.example.system.utils.MD5Util;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@Resource
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    private final UserService userService;
    private final PasswordEncoder passwordEncoder; // 注入 PasswordEncoder

    public UserController(UserService userService, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder; // 注入 PasswordEncoder
    }

    /**
     * 获取学生总数量
     * @return
     */
    @RequestMapping("/getStudentCount")
    public Object getStudentCount() {
        log.info("获取学生总数量");
        return userService.getStudentCount();
    }

    /**
     * 获取老师总数量
     * @return
     */
    @RequestMapping("/getTeacherCount")
    public Object getTeacherCount() {
        log.info("获取老师总数量");
        return userService.getTeacherCount();
    }

    /**
     * 获取用户总数量
     * @return
     */
    @RequestMapping("/getCount")
    public Object getCount() {
        log.info("获取用户总数量");
        return userService.getCount();
    }

    //批量删除用户
    @DeleteMapping("/deleteList")
    public Object deleteList(@RequestParam("list") List<Integer> list, HttpServletRequest request) {
        log.info("批量删除用户 list: {}", list);
        String toKen =request.getHeader("Authorization");
        Claims claims = JWTUtil.checkToken(toKen);
        Integer a = (Integer) claims.get("userPrivileges");
        // 检查用户是否有权限添加竞赛信息
        if (2 == a) {
            // 如果用户无权限，禁止访问
            return Result.fail("禁止删除用户");
        }
        return userService.deleteList(list);
    }
    //登录
    @PostMapping("/login")
    public Object login(@RequestBody Map<String, String> requestData) {
        String sTId = requestData.get("sTId");
        String password = requestData.get("password");
        System.out.println(requestData);
        log.info("用户登录尝试 -> sTId: {}, password: [PROTECTED]", sTId);

        if (!StringUtils.hasLength(sTId) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码不能为空");
        }

        UserTable user = userService.findBySTId(sTId);

        if (user == null || !MD5Util.verify(password, user.getUserPassword())) {
            return Result.fail("用户名或密码错误");
        }

        log.info("登录成功: 用户ID: {}, 用户权限等级: {}", user.getUserId(), user.getUserPrivileges());
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getUserId());
        claims.put("userName", user.getUserName());
        claims.put("sTId", user.getSTId());
        claims.put("userPrivileges", user.getUserPrivileges());

        String token = JWTUtil.getToken(claims);
        return token;
    }


//    /**
//     * 用户查看个人信息
//     * 假设用户已通过身份验证，并且我们可以从身份验证令牌中提取用户ID
//     *
//     * @param id 用户的学号或员工号
//     * @return 用户的个人信息
//     */
    @GetMapping("/getUserInfo")
    public Object getUserInfo(HttpServletRequest request) {
        log.info("用户查看个人信息");
        //先暂时这样写，因为现在还没有前端的支持
        String toKen =request.getHeader("Authorization");

        System.out.println("Token: " + toKen);
        Claims claims = JWTUtil.checkToken(toKen);
        UserTable user = userService.findBySTId((String) claims.get("sTId"));
        if (user != null) {
            return user; // Assuming UserTable has a method toMap() that converts it to a map
        } else {
            return Result.fail("未找到用户信息");
        }
    }

    //更新用户个人信息 只能更新phone, email, user_password
    @PutMapping("/update")
    public Object updateUser(UserTable user, HttpServletRequest request) {
        String toKen =request.getHeader("Authorization");
        Claims claims = JWTUtil.checkToken(toKen);
        user.setSTId((String) claims.get("sTId"));
        if (!userService.updateUser(user)) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "用户信息更新失败");
        }
        return Result.success("用户信息更新成功");
    }

    //管理员更新用户信息
    @PutMapping("/updateOther")
    public Object updateOther(UserTable user, HttpServletRequest request) {
        String toKen =request.getHeader("Authorization");
        Claims claims = JWTUtil.checkToken(toKen);
        Integer privileges = (Integer) claims.get("userPrivileges");
        if (privileges != 0 && !userService.updateOther(user)) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "用户信息更新失败");
        }
        return Result.success("用户信息更新成功");
    }
    /**
     * 处理创建新用户的请求
     * 只有老师和管理员（权限为0或1）可以添加新用户
     */
    @PostMapping("/create")
    public Object createUser(UserTable user, HttpServletRequest request) {
        log.info("创建新用户 user: {}", user);
        String token =request.getHeader("Authorization");
        Claims claims = JWTUtil.checkToken(token);
        Integer userPrivileges = (Integer) claims.get("userPrivileges");
        if (userPrivileges == null || userPrivileges == 2) {
            return Result.fail("权限不足");
        }
        if (    user.getUserName()       == null
             || user.getUserPrivileges() == null
             || user.getEmail()          == null
             || user.getUserPassword()   == null
             || user.getSTId()           == null
             || user.getCollegeId()      == null)
        {
            return Result.fail("用户信息不全");
        }
        // 用户密码进行加密
        user.setUserPassword(MD5Util.puzzle(user.getUserPassword()));
        return Result.success(userService.createUser(user));
    }
    /**
     * 处理查看所有用户的请求
     * 只有老师和管理员（权限为0或1）可以查看用户列表
     */

    //    查看所有用户信息
    @GetMapping("/getUserAll")
    public Object getUserAll(HttpServletRequest request) {
        log.info("查看所有用户信息");
        HttpSession session = request.getSession(true);
        String toKen =request.getHeader("Authorization");
        Claims claims = JWTUtil.checkToken(toKen);
        List<UserTable> userList = userService.findAllUsers();
//        if (claims != null && ((Integer) claims.get("userPrivileges")) == 2) {
//            // 权限不足
//            return Result.fail("权限不足");
//        }
        return userList;
    }

    // 用户导入接口
    @PostMapping("/user/import")
    public ResponseEntity<String> importUsers(@RequestBody List<UserTable> userDataList) {
        // 检查上传的用户数据列表是否为空
        if (userDataList == null || userDataList.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("上传的用户数据列表不能为空");
        }
        // 设置默认的userStatus值为0
        for (UserTable user : userDataList) {
            if (user.getUserStatus() == null) {
                user.setUserStatus(0);
            }
            if (user.getUserPassword() == null || user.getUserPassword().isEmpty()) {
                // 假设学号字段为sid，将密码设置为123456
                user.setUserPassword("123456");
            }
        }
        try {
            // 保存用户数据到数据库
            userService.importUsers(userDataList);
            return ResponseEntity.ok("用户导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("用户导入失败");
        }
    }

}