/**
 * 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.modules.app.entity.UserEntity;
import io.renren.modules.app.form.RePasswordForm;
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 AppRePasswordController {
    @Autowired
    private UserService userService;
    @Autowired
    private SmsCodeService smsCodeService;

     /**
     * 短信验证码
     */
    @PostMapping("/mobilecode")
    @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();
        }
    }

    /**
     * 通过手机验证码重置密码
     * @param form
     * @return
     */
    @PostMapping("repassword")
    @ApiOperation("通过手机验证码重置密码")
    public R rePassword(@RequestBody RePasswordForm form){
        boolean captcha = smsCodeService.validate(form.getUuid(), form.getCode(), form.getMobile());
		if(!captcha){
			return R.error("验证码不正确");
        }
        
        //表单校验
        ValidatorUtils.validateEntity(form);

        UserEntity user = userService.queryByMobile(form.getMobile());
        Long userId = user.getUserId();
        String password = DigestUtils.sha256Hex(form.getPassword());
        userService.updatePassWord(userId, password);

        return R.ok();
    }
}
