package com.hs.api.controller;

import com.hs.api.common.Result;
import com.hs.api.model.reqmodel.CodeAndPwd;
import com.hs.api.model.reqmodel.UpdatePass;
import com.hs.api.model.respmodel.LoginInfo;
import com.hs.api.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;

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

    @Autowired
    private LoginService loginServiceImpl;

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

    @PostMapping("pass")
    @ApiOperation(value = "修改密码")
    public Result updatePass(@RequestBody UpdatePass request) {
        boolean result = loginServiceImpl.updatePass(request.getLoginName(), request.getOldPassword()
                , request.getNewPassword());
        if (result)
            return Result.success(null);
        else
            return Result.error();
    }


    @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);
    }
}
