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

package io.renren.modules.app.controller;

import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.utils.MyUtils;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.RegisterForm;
import io.renren.modules.app.service.SmsCodeService;
import io.renren.modules.app.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
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.Map;

/**
 * 注册
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app")
@Api("APP注册接口")
public class AppRegisterController {
    @Autowired
    private UserService userService;
    @Autowired
    private SmsCodeService smsCodeService;

    @PostMapping("register")
    @ApiOperation("注册")
    public R register(@RequestBody RegisterForm form){
        boolean captcha = smsCodeService.validate(form.getUuid(), form.getCode(), form.getMobile());
		if(!captcha){
			return R.error("验证码不正确");
        }
        //表单校验
        ValidatorUtils.validateEntity(form);

        // 验证手机号格式
        if(!MyUtils.checkPhone(form.getMobile())){
            return R.error("手机号格式不正确");
        }

        UserEntity user = new UserEntity();
        user.setMobile(form.getMobile());
        user.setUsername(form.getUsername());
        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        user.setCreateTime(new Date());
        userService.save(user);

        return R.ok();
    }

    /**
     * 短信验证码
     */
    @PostMapping("/phonecode")
    @ApiOperation("注册短信验证码")
    public R mobileCode(@RequestBody Map<String, Object> params) {
        String uuid = (String) params.get("uuid");
        String mobile = (String) params.get("mobile");

        UserEntity user = userService.queryByMobile(mobile);
        if (user != null) {
            return R.error("手机号已注册, 请登录");
        }

        try {
            String result = smsCodeService.getCode(uuid, mobile);
            return R.ok().put("result", result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }
}
