package com.jumeirah.api.app.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.jumeirah.api.app.service.AppSmsService;
import com.jumeirah.api.app.vo.SmsCode;
import io.geekidea.springbootplus.framework.common.api.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Arrays;

@Service
@Slf4j
public class AppSmsServiceImpl implements AppSmsService {

    /**
     * SpringBoot获取当前环境
     */
    @Value("${spring.profiles.active}")
    private String profiles;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String SMS_REGIEST = "sms:register:%s:%s";

    @Override
    public ApiResult<SmsCode> registerType(String area, String number) {
        String randomCode = getRandomCode();

        // 存入redis
        long expire = 120L;

        Duration expireDuration = Duration.ofSeconds(expire);

        redisTemplate.opsForValue().set(String.format(SMS_REGIEST, area, number), randomCode, expireDuration);

        SmsCode smsCode = new SmsCode();
        smsCode.setCode(randomCode);

        log.info(area + "," + number + ":" + randomCode);

        // TODO 需要补充调用发送代码

        return ApiResult.ok(smsCode);
    }

    String getRandomCode() {
        // 如果为测试环境则生成默认
        if (profiles.equals("dev")) {
            return "666666";
        } else {
            return Arrays.toString(RandomUtil.randomInts(6));
        }
    }
}
