package org.matrix.local.controller;

import com.google.common.collect.ImmutableMap;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.matrix.local.entity.vo.LoginInfo;
import org.matrix.local.entity.vo.UserInfo;
import org.matrix.local.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Api(tags = "用户相关API")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public ResponseEntity<Map<String, String>> login(HttpServletRequest request, @RequestBody LoginInfo loginInfo) {
        String sessionId = request.getSession().getId();
        boolean success = userService.login(loginInfo, sessionId);
        if (success) {
            return ResponseEntity.ok(ImmutableMap.of("message", "登录成功"));
        } else {
            return ResponseEntity.ok(ImmutableMap.of("message", "用户名或密码错误"));
        }
    }

    @ApiOperation("查询当前登录用户")
    @GetMapping("/login/info")
    public ResponseEntity<UserInfo> find(HttpServletRequest request) {
        String sessionId = request.getSession().getId();
        UserInfo userInfo = userService.findBySessionId(sessionId);
        return ResponseEntity.ok(userInfo);
    }

    @ApiOperation("用户登出")
    @GetMapping("/logout")
    public ResponseEntity<UserInfo> logout(HttpServletRequest request) {
        String sessionId = request.getSession().getId();
        UserInfo userInfo = userService.findBySessionId(sessionId);
        return ResponseEntity.ok(userInfo);
    }

}
