package com.jd.lightapplication.controller;

import com.jd.lightapplication.common.lang.R;
import com.jd.lightapplication.config.SmsConfig;
import com.jd.lightapplication.model.SysUser;
import com.jd.lightapplication.service.SysUserService;
import com.jd.lightapplication.utils.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/api/sms")
public class SmsController {
    @Resource
    private SmsConfig smsConfig;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SysUserService sysUserService;

    @PostMapping("/sendSms/{phone}")
    public R sendSms(@PathVariable("phone") String phone) {
        SysUser sysUser = sysUserService.getByPhone(phone);
        if (sysUser == null) {
            return R.fail("没有找到相关用户信息");
        }
        //先替换content里面的占位符
        String code = this.getRandom();
        String content = smsConfig.getSmsContent().replace("{doing}", "登录轻应用小程序");
        content = content.replace("{yzm}", code);
        String result = SmsUtil.sendHttpSms(smsConfig.getSmsUrl(), smsConfig.getSmsName(),
                smsConfig.getSmsApid(), smsConfig.getSmsSecret(), phone,
                content, smsConfig.getSmsSign(), "");
        if (result == null) {
            log.error("短信发送失败");
            return R.fail( "短信发送失败");
        } else if ("".equals(result)) {
            //把验证码存到redis
            stringRedisTemplate.opsForValue().set(phone, code, 10, TimeUnit.MINUTES);
            return R.success( "短信发送成功。有效期为十分钟。");
        } else {
            log.error("短信发送失败，错误信息：" + result);
            return R.fail( "短信发送失败");
        }
    }

    public String getRandom() {
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10); //每次随机出一个数字（0-9）
            code = code + r;  //把每次随机出的数字拼在一起
        }
        return code;
    }
}
