package com.carmaintenance.controller;

import com.carmaintenance.dto.Result;
import com.carmaintenance.entity.User;
import com.carmaintenance.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/users")
@CrossOrigin
public class UserController {

    @Autowired
    private UserRepository userRepository;

    /**
     * 获取所有用户
     */
    @GetMapping
    public Result<List<User>> getAllUsers() {
        List<User> users = userRepository.findAll();
        users.forEach(user -> user.setPassword(null));
        return Result.success(users);
    }

    /**
     * 根据ID获取用户
     */
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Integer id) {
        User user = userRepository.findById(id).orElse(null);
        if (user == null) {
            return Result.notFound("用户不存在");
        }
        user.setPassword(null);
        return Result.success(user);
    }

    /**
     * 根据角色获取用户列表
     */
    @GetMapping("/role/{role}")
    public Result<List<User>> getUsersByRole(@PathVariable String role) {
        try {
            User.UserRole userRole = User.UserRole.valueOf(role);
            List<User> users = userRepository.findByRole(userRole);
            users.forEach(user -> user.setPassword(null));
            return Result.success(users);
        } catch (IllegalArgumentException e) {
            return Result.error("角色参数错误");
        }
    }

    /**
     * 创建用户
     */
    @PostMapping
    public Result<User> createUser(@RequestBody User user) {
        if (userRepository.existsByUsername(user.getUsername())) {
            return Result.error("用户名已存在");
        }
        if (userRepository.existsByPhone(user.getPhone())) {
            return Result.error("手机号已被使用");
        }
        User savedUser = userRepository.save(user);
        savedUser.setPassword(null);
        return Result.success("创建成功", savedUser);
    }

    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    public Result<User> updateUser(@PathVariable Integer id, @RequestBody User user) {
        User existingUser = userRepository.findById(id).orElse(null);
        if (existingUser == null) {
            return Result.notFound("用户不存在");
        }

        if (user.getRealName() != null) existingUser.setRealName(user.getRealName());
        if (user.getPhone() != null) existingUser.setPhone(user.getPhone());
        if (user.getEmail() != null) existingUser.setEmail(user.getEmail());
        if (user.getStatus() != null) existingUser.setStatus(user.getStatus());

        User updatedUser = userRepository.save(existingUser);
        updatedUser.setPassword(null);
        return Result.success("更新成功", updatedUser);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Integer id) {
        if (!userRepository.existsById(id)) {
            return Result.notFound("用户不存在");
        }
        userRepository.deleteById(id);
        return Result.<Void>success("删除成功", null);
    }

    /**
     * 修改密码
     */
    @PutMapping("/{id}/password")
    public Result<Void> changePassword(@PathVariable Integer id,
                                       @RequestParam String oldPassword,
                                       @RequestParam String newPassword) {
        User user = userRepository.findById(id).orElse(null);
        if (user == null) {
            return Result.notFound("用户不存在");
        }

        if (!user.getPassword().equals(oldPassword)) {
            return Result.error("原密码错误");
        }

        user.setPassword(newPassword);
        userRepository.save(user);
        return Result.<Void>success("密码修改成功", null);
    }
}
