package com.innovation.platform.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.innovation.platform.common.Result;
import com.innovation.platform.entity.SysUser;
import com.innovation.platform.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户管理控制器
 */
@Tag(name = "用户管理", description = "用户 CRUD 接口")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final SysUserService sysUserService;

    @Operation(summary = "获取用户列表（分页）")
    @GetMapping
    public Result<PageResult<SysUser>> getUserList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer roleType,
            @RequestParam(required = false) Integer status
    ) {
        Page<SysUser> userPage = sysUserService.getUserList(page, size, keyword, roleType, status);
        return Result.success("查询成功", toPageResult(userPage));
    }

    @Operation(summary = "获取用户详情")
    @GetMapping("/{id}")
    public Result<SysUser> getUserById(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success("查询成功", user);
    }

    @Operation(summary = "创建用户")
    @PostMapping
    public Result<SysUser> createUser(@RequestBody CreateUserRequest request) {
        try {
            SysUser user = sysUserService.createUser(request);
            return Result.success("创建成功", user);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "更新用户")
    @PutMapping("/{id}")
    public Result<SysUser> updateUser(@PathVariable Long id, @RequestBody UpdateUserRequest request) {
        try {
            SysUser user = sysUserService.updateUser(id, request);
            return Result.success("更新成功", user);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        try {
            sysUserService.deleteUser(id);
            return Result.success("删除成功", null);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "获取教师列表")
    @GetMapping("/teachers")
    public Result<List<SysUser>> getTeacherList() {
        List<SysUser> teachers = sysUserService.getTeacherList();
        return Result.success("查询成功", teachers);
    }

    @Operation(summary = "修改密码")
    @PostMapping("/change-password")
    public Result<Void> changePassword(
            @RequestParam String oldPassword,
            @RequestParam String newPassword
    ) {
        try {
            sysUserService.changePassword(oldPassword, newPassword);
            return Result.success("修改成功", null);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "更新个人资料")
    @PutMapping("/profile")
    public Result<SysUser> updateProfile(@RequestBody UpdateProfileRequest request) {
        try {
            SysUser user = sysUserService.updateProfile(request);
            return Result.success("更新成功", user);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    private <T> PageResult<T> toPageResult(Page<T> page) {
        PageResult<T> result = new PageResult<>();
        result.setList(page.getRecords());
        result.setTotal(page.getTotal());
        result.setPage((int) page.getCurrent());
        result.setSize((int) page.getSize());
        return result;
    }

    @Data
    public static class PageResult<T> {
        private List<T> list;
        private Long total;
        private Integer page;
        private Integer size;
    }

    @Data
    public static class CreateUserRequest {
        private String username;
        private String password;
        private String realName;
        private Integer gender;
        private String phone;
        private String email;
        private String avatar;
        private Integer roleType;
    }

    @Data
    public static class UpdateUserRequest {
        private String realName;
        private Integer gender;
        private String phone;
        private String email;
        private String avatar;
        private Integer roleType;
        private Integer status;
    }

    @Data
    public static class UpdateProfileRequest {
        private String realName;
        private String phone;
        private String email;
        private String avatar;
    }
}
