/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.controller;

import io.renren.common.utils.MyUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.admin.entity.MemberLoginLogEntity;
import io.renren.modules.admin.service.MemberLoginLogService;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.utils.JwtUtils;
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 java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * APP登录授权
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app")
@Api("APP登录接口")
public class AppLoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private MemberLoginLogService memberLoginLogService;

    /**
     * 登录
     */
    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form, HttpServletRequest request){
        //表单校验
        ValidatorUtils.validateEntity(form);

        // 用户登录 更新最近登录时间ip
        long userId = userService.login(form);

        // 记录登陆日志
        Date loginTime = new Date();
        String loginIp = MyUtils.getIpAddress(request);
        userService.updateLoginTimeIp(userId, loginTime, loginIp);

        MemberLoginLogEntity memberLoginLog = new MemberLoginLogEntity();
        memberLoginLog.setUserId(userId);
        memberLoginLog.setLoginTime(loginTime);
        memberLoginLog.setLoginIp(loginIp);
        memberLoginLogService.save(memberLoginLog);

        //生成token
        String token = jwtUtils.generateToken(userId);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());

        return R.ok(map);
    }
    
}
