package com.sdut.labex.controller;

import com.alibaba.fastjson.JSONObject;
import com.sdut.labex.Factory.UserFactory;
import com.sdut.labex.entity.User;
import com.sdut.labex.service.LogService;
import com.sdut.labex.service.UserService;
import com.sdut.labex.utils.ResVo;
import com.sdut.labex.utils.UserHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * File: UserController
 * Created: 2023/6/12
 * Author: springforest
 * Description:
 */
@RestController
@CrossOrigin
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private LogService logService;

    @PostMapping("/login")
    public ResVo login(@RequestBody JSONObject jsonObject) {
        return userService.login(jsonObject.getString("id"), jsonObject.getString("password"));
    }

    @PutMapping("/changePassword")
    public ResVo changePassword(@RequestBody JSONObject jsonObject) {
        String id = UserHolder.getUser().getId();
        String oldPassword = jsonObject.getString("oldPassword");
        String newPassword = jsonObject.getString("newPassword");
        return userService.changePassword(id, oldPassword, newPassword);
    }

    @PostMapping("/addUserBatch")
    public ResVo addBatch(MultipartFile file) {
        return userService.addBatch(file);
    }

    @DeleteMapping("/user/{id}")
    public ResVo delete(@PathVariable("id") String id) {
        return userService.delete(id);
    }

    @PutMapping("/user")
    public ResVo update(@RequestBody JSONObject jsonObject) {
        User user = UserFactory.createUser(jsonObject);
        return userService.update(user);
    }

    @PostMapping("/user/{pageNum}/{pageSize}")
    public ResVo getUser(@RequestBody JSONObject jsonObject, @PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize) {
        User user = UserFactory.createUser(jsonObject);
        return userService.getUser(pageNum, pageSize, user);
    }

    @PostMapping("/user")
    public ResVo add(@RequestBody JSONObject jsonObject) {
        User user = UserFactory.createUser(jsonObject);
        return userService.add(user);
    }

    @GetMapping("/log/{pageNum}/{pageSize}")
    public ResVo getLog(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize) {
        return logService.getLog(pageNum, pageSize);
    }
}
