package io.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.common.annotation.Login;
import io.common.annotation.LoginUser;
import io.common.utils.Result;
import io.entity.UserEntity;
import io.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@CrossOrigin
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    // UserController.java 添加登录方法
    @PostMapping("/login")
    public Result login(@Valid @RequestBody UserEntity dto) {
        //用户登录
        Map<String, Object> map = userService.login(dto);
        return new Result().ok(map);
    }


    // UserController.java 添加注册方法
    @PostMapping("/register")
    public Result register(@Valid @RequestBody UserEntity dto) {
        // 检查用户名是否已存在
        if (userService.existsUsername(dto.getUsername())) {
            return new Result().error("用户名已存在");
        }
        // 密码加密
        String sha256Hex = DigestUtil.sha256Hex(dto.getPassword());
        UserEntity user = new UserEntity();
        user.setPassword(sha256Hex);
        user.setUsername(dto.getUsername());
        user.setRole("USER"); // 默认启用
        userService.save(user);
        return new Result().ok("注册成功");
    }


    @GetMapping("/page")
    public Page<UserEntity> page(@RequestParam(defaultValue = "1") Integer current,
                                 @RequestParam(defaultValue = "10") Integer size) {
        Page<UserEntity> page = new Page<>(current, size);
        return userService.page(page);
    }

    @Login
    @GetMapping
    public Result list(@Parameter(hidden = true) @RequestAttribute("userId") Long userId) {
        System.out.println(userId);
        return new Result().ok(userService.list()) ; // 查询所有用户
    }

    @PostMapping
    public boolean save(@RequestBody UserEntity user) {
        return userService.save(user); // 新增用户
    }

    @PutMapping
    public boolean update(@RequestBody UserEntity user) {
        return userService.updateById(user); // 更新用户
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Long id) {
        return userService.removeById(id); // 删除用户
    }

    @Login
    @GetMapping("userInfo")
    @Operation(summary = "获取用户信息")
    public Result<UserEntity> userInfo(@Parameter(hidden = true) @LoginUser UserEntity user) {
        return new Result<UserEntity>().ok(user);
    }
}