/**
 * 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.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.service.SmsCodeService;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.utils.JwtUtils;
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.HashMap;
import java.util.Map;

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

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

        smsCodeService.validate(form.getUuid(), form.getCode(), form.getPhone());

        //用户登录
        String symbol = MyUtils.md5(form.getTurename() + form.getPhone());
        UserEntity user =  userService.queryBySymbol(symbol);
        Assert.isNull(user, "手机号错误");
        long userId = user.getUserId();

        //生成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);
    }

    @PostMapping("mobilecode")
    public R mobileCode(@RequestBody Map<String, Object> params) {
        String uuid = (String) params.get("uuid");
        String phone = (String) params.get("phone");

        UserEntity user = userService.queryByPhone(phone);
        if (user == null) {
            return R.error("手机号未注册");
        }

        String res = "";
        try {
            res = smsCodeService.getCode(uuid, phone);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok(res);
    }

    
}
