/**
 * Copyright (c) 2022 雷掣 All rights reserved.
 *
 * https://www.lc_crm.com
 *
 * 版权所有，侵权必究！
 */

package io.renren.controller;


import io.renren.annotation.Login;
import io.renren.common.exception.RenException;
import io.renren.common.utils.Result;
import io.renren.common.validator.ValidatorUtils;
import io.renren.dto.LoginDTO;
import io.renren.dto.LoginQuickDTO;
import io.renren.dto.LoginResp;
import io.renren.service.TokenService;
import io.renren.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

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

/**
 * 登录接口
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/api")
@Api(tags="登录接口")
public class ApiLoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;


    @PostMapping("loginByPassword")
    @ApiOperation("登录（密码）")
    public Result<Map<String, Object>> loginByPassword(@RequestBody LoginDTO dto){
        //表单校验
        ValidatorUtils.validateEntity(dto);

        //用户登录
        Map<String, Object> map = userService.login(dto);

        return new Result().ok(map);
    }


    @PostMapping("login")
    @ApiOperation("登录（手机验证码）")
    public Result<Map<String, Object>> login(@RequestBody LoginQuickDTO dto){
        //表单校验
        ValidatorUtils.validateEntity(dto);

        //用户登录
        Map<String, Object> map = userService.loginQuick(dto);
        LoginResp loginResp = new LoginResp();
        loginResp.setToken(map.get("token").toString());
        loginResp.setUserId(map.get("userId").toString());

        return new Result().ok(loginResp);
    }

    @Login
    @PostMapping("logout")
    @ApiOperation("退出")
    public Result logout(HttpServletRequest request){
        String token = request.getHeader("token");
        tokenService.expireToken(token);
        return new Result();
    }


    @GetMapping("getverificationCode")
    @ApiOperation("发送手机短信")
    public Result getverificationCode(String mobile){

        //用户登录
        Boolean flag = userService.getverificationCode(mobile);

        if (flag==false){
            throw new RenException("发送失败");
        }

        return new Result().ok(null);
    }

}