package com.rj.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.common.PasswordUtil;
import com.rj.entity.sys.User;
import com.rj.pojo.sys.LoginRequest;
import com.rj.pojo.sys.LoginResponse;
import com.rj.service.sys.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 系统生成
 * @since 2025-08-07
 */
@RestController
@RequestMapping("/api/sys/user")
@Tag(name = "用户管理", description = "用户管理相关接口")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "根据用户名和密码进行登录验证")
    public ResponseEntity<Map<String, Object>> login(
            @Parameter(description = "登录信息", required = true)
            @Valid @RequestBody LoginRequest loginRequest) {
        Map<String, Object> result = new HashMap<>();
        try {
            LoginResponse loginResponse = userService.login(loginRequest);
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("data", loginResponse);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "登录失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 新增用户
     */
    @PostMapping("/add")
    @Operation(summary = "新增用户", description = "添加新的用户信息")
    public ResponseEntity<Map<String, Object>> addUser(
            @Parameter(description = "用户信息", required = true)
            @RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查用户名是否已存在
            User existingUser = userService.getUserByUserName(user.getUserName());
            if (existingUser != null) {
                result.put("success", false);
                result.put("message", "用户名已存在");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 保存原始密码并加密
            if (user.getPassword() != null && !user.getPassword().trim().isEmpty()) {
                // 保存原始密码
                user.setOriginalPassword(user.getPassword());
                // 对密码进行加密
                String encryptedPassword = PasswordUtil.encryptPasswordWithDefaultSalt(user.getPassword());
                user.setPassword(encryptedPassword);
            }
            
            boolean success = userService.save(user);
            if (success) {
                result.put("success", true);
                result.put("message", "用户添加成功");
                result.put("data", user);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "用户添加失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "用户添加异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID查询用户
     */
    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询用户", description = "根据用户ID获取用户详细信息")
    public ResponseEntity<Map<String, Object>> getUserById(
            @Parameter(description = "用户ID", required = true)
            @PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = userService.getById(id);
            if (user != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", user);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "用户不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据用户名查询用户
     */
    @GetMapping("/getByUserName")
    @Operation(summary = "根据用户名查询用户", description = "根据用户名查询用户信息")
    public ResponseEntity<Map<String, Object>> getUserByUserName(
            @Parameter(description = "用户名", required = true)
            @RequestParam String userName) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUserName, userName);
            List<User> userList = userService.list(queryWrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", userList);
            result.put("count", userList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据电话查询用户
     */
    @GetMapping("/getByPhone")
    @Operation(summary = "根据电话查询用户", description = "根据用户电话查询用户信息")
    public ResponseEntity<Map<String, Object>> getUserByPhone(
            @Parameter(description = "用户电话", required = true)
            @RequestParam String phone) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            List<User> userList = userService.list(queryWrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", userList);
            result.put("count", userList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 分页查询用户列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询用户列表", description = "分页查询用户信息列表")
    public ResponseEntity<Map<String, Object>> getUserList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "用户名（模糊查询）")
            @RequestParam(required = false) String userName,
            @Parameter(description = "邮箱（模糊查询）")
            @RequestParam(required = false) String email,
            @Parameter(description = "电话（模糊查询）")
            @RequestParam(required = false) String phone) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<User> page = new Page<>(current, size);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (userName != null && !userName.trim().isEmpty()) {
                queryWrapper.like(User::getUserName, userName);
            }
            if (email != null && !email.trim().isEmpty()) {
                queryWrapper.like(User::getEmail, email);
            }
            if (phone != null && !phone.trim().isEmpty()) {
                queryWrapper.like(User::getPhone, phone);
            }
            
            // 按用户ID倒序排列
            queryWrapper.orderByDesc(User::getUserId);
            
            Page<User> userPage = userService.page(page, queryWrapper);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", userPage.getRecords());
            result.put("total", userPage.getTotal());
            result.put("current", userPage.getCurrent());
            result.put("size", userPage.getSize());
            result.put("pages", userPage.getPages());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    @Operation(summary = "更新用户信息", description = "更新用户详细信息")
    public ResponseEntity<Map<String, Object>> updateUser(
            @Parameter(description = "用户信息", required = true)
            @RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (user.getUserId() == null) {
                result.put("success", false);
                result.put("message", "用户ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 检查用户名是否已被其他用户使用
            User existingUser = userService.getById(user.getUserId());
            if (!existingUser.getOriginalPassword().equals(user.getOriginalPassword())){
                result.put("success", false);
                result.put("message", "原始密码错误");
                return ResponseEntity.badRequest().body(result);
            }

            // 如果密码不为空，则保存原始密码并加密
            if (user.getPassword() != null && !user.getPassword().trim().isEmpty()) {
                // 保存原始密码
                user.setOriginalPassword(user.getPassword());
                // 对密码进行加密
                String encryptedPassword = PasswordUtil.encryptPasswordWithDefaultSalt(user.getPassword());
                user.setPassword(encryptedPassword);
            }
            
            boolean success = userService.updateById(user);
            
            if (success) {
                result.put("success", true);
                result.put("message", "用户信息更新成功");
                result.put("data", user);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "用户信息更新失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID删除用户
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除用户", description = "根据用户ID删除用户信息")
    public ResponseEntity<Map<String, Object>> deleteUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = userService.removeById(id);
            if (success) {
                result.put("success", true);
                result.put("message", "用户删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "用户删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 批量删除用户
     */
    @DeleteMapping("/batchDelete")
    @Operation(summary = "批量删除用户", description = "根据用户ID列表批量删除用户信息")
    public ResponseEntity<Map<String, Object>> batchDeleteUsers(
            @Parameter(description = "用户ID列表", required = true)
            @RequestBody List<Integer> ids) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (ids == null || ids.isEmpty()) {
                result.put("success", false);
                result.put("message", "用户ID列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            boolean success = userService.removeByIds(ids);
            if (success) {
                result.put("success", true);
                result.put("message", "批量删除成功，共删除 " + ids.size() + " 条记录");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "批量删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取用户统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取用户统计信息", description = "获取用户总数等统计信息")
    public ResponseEntity<Map<String, Object>> getUserStatistics() {
        Map<String, Object> result = new HashMap<>();
        try {
            long totalCount = userService.count();
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalUsers", totalCount);
            
            result.put("success", true);
            result.put("message", "统计信息获取成功");
            result.put("data", statistics);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "统计信息获取异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
