package com.test.controller;

import com.test.bean.Result;
import com.test.bean.User;
import com.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping
    public Result addUser(@RequestBody User user) {
        boolean res = userService.addUser(user);
        if (res) {
            User userRes = userService.getUserByPhone(user.getPhone());
            return Result.success(userRes);
        }
        return Result.error("添加用户失败");
    }

    @GetMapping
    public Result getUserByPhone(@RequestParam String phone) {
        User user = userService.getUserByPhone(phone);
        if (user != null && user.getUserId() == null) {
            return Result.error("搜索用户失败");
        }
        return Result.success(user);
    }

    @PutMapping
    public Result updateUser(@RequestBody User user) {
        User userRes = userService.updateUser(user);
        return Result.success(userRes);
    }

    @DeleteMapping
    public Result deleteUser(@RequestParam Integer id) {
        boolean res = userService.deleteUser(id);
        if (res){
            return Result.success();
        }
        return Result.error("删除用户失败");
    }

}
