package com.bonus.sgzb.system.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.druid.util.StringUtils;
import com.bonus.sgzb.common.core.exception.ServiceException;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.redis.service.RedisService;
import com.bonus.sgzb.system.service.ISysSmsService;
import org.springframework.stereotype.Service;

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

import static com.bonus.sgzb.common.core.web.domain.AjaxResult.success;

/**
 * Description: 短信发送
 *
 * @Author 阮世耀
 * @Create 2023/12/11 15:49
 * @Version 1.0
 */
@Service
public class SysSmsServiceImpl implements ISysSmsService {

    @Resource
    private RedisService redisService;

    @Override
    public AjaxResult sendSms(String phone, String msg) {
        return sendCodeByPhone(phone, msg);
    }

    @Override
    public AjaxResult codeLogin(String phone) {
        // 校验手机号码
        return sendCodeByPhone(phone, null);
    }


    /**
     * 发送验证码到手机
     * @param phone 手机号码
     * @return AjaxResult对象
     */
    private AjaxResult sendCodeByPhone(String phone, String msg) {
        // 校验手机号码
        if (phone == null || phone.length() != 11) {
            return AjaxResult.error("手机号码不正确");
        }
        String code = getSixBitCode();
        // 校验验证码
        if (code.length() != 6) {
            return AjaxResult.error("验证码格式不正确");
        }
        // 发送短信
        try {
            String url = "http://api.ktsms.cn/sms_token?ddtkey=bonus&secretkey=KtyBns@Admin2023!";
            String content = url + "&mobile=" + phone + "&content=【智慧仓储】您正在进行短信验证，验证码:" + code + "，请在5分钟内完成验证。";
            String body = HttpRequest.post(content).execute(false).body();
            System.out.println("发送短信：" + phone + "，验证码：" + code + "，返回结果：" + body);
            if (body == null || !body.contains("success")) {
                return AjaxResult.error("发送失败");
            }
            // 存储验证码至Redis中，键值为：code_15588886157 , 有效期5，时间颗粒度为MINUTES:分钟
            redisService.setCacheObject("code_" + phone, code, 5L, TimeUnit.MINUTES);
            return success("手机号：" + phone + "，用户登录验证码：" + code + "，返回结果：" + body);
        } catch (Exception e) {
            return AjaxResult.error("发送失败:" + e.getMessage());
        }
    }


    /**
     * 判断验证码是否存在Redis中
     *
     * @param phone 手机号码
     * @param code  用户填入的验证码
     * @return 校验结果
     * @throws ServiceException 异常信息
     */
    @Override
    public boolean checkCode(String phone, String code) {
        String redisCode = redisService.getCacheObject("code_" + phone);
        if (StringUtils.isEmpty(redisCode)) {
            throw new ServiceException("验证码失效", 403);
        }
        if (!StringUtils.equals(redisCode.split("_")[0], code)) {
            throw new ServiceException("验证码错误", 401);
        } else {
            redisService.deleteObject("code_" + phone);
            return true;
        }
    }

    /**
     * 随机生成6位验证码
     */
    private String getSixBitCode() {
        //随机数
        StringBuilder sb = new StringBuilder();
        Random rand = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(rand.nextInt(10));
        }
        return sb.toString();
    }



}
