package com.hs.admin.controller;

import com.hs.admin.common.Result;
import com.hs.admin.model.reqmodel.CodeAndPwd;
import com.hs.admin.service.LoginService;
import com.hs.common.utils.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping()
@Api(tags = {"登录"})
public class LoginController {

    @Autowired
    private LoginService loginServiceImpl;

    @PostMapping("login")
    @ApiOperation(value = "Result«LoginService.LoginInfo»登录")
    public Result<LoginService.LoginInfo> login(@Valid @RequestBody CodeAndPwd codeAndPwd,HttpServletRequest request) {
        String ip = HttpUtil.getIP(request);
        LoginService.LoginInfo loginInfo = loginServiceImpl.login(
                codeAndPwd.getLoginName(),codeAndPwd.getPassword(),ip);
        if(loginInfo.getUser() == null){
            return Result.error(Result.ErrorCode.USERERROR);
        }
        return Result.success(loginInfo);
    }

    @PostMapping("token")
    @ApiOperation("刷新TOKEN")
    public Result<String> refresh(@ApiIgnore HttpServletRequest request) {
        String oldToken = request.getHeader("Authorization");
        String token = loginServiceImpl.refreshToken(oldToken);
        return Result.success(token);
    }
}
