package com.vctgo.auth.service;

import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.vctgo.auth.form.SmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @CreateTime: 2024/9/4 下午7:15
 * @Description:
 * @Email: f2965573933@163.com
 * @Author: FanJiaBao
 */
@Service
public class SmsService {

    @Value("${sms.api-url}")
    private String apiUrl;
    @Value("${sms.sp-code}")
    private String spCode;
    @Value("${sms.login-name}")
    private String loginName;
    @Value("${sms.password}")
    private String password;

    @Autowired
    private CaptchaRedisService captchaRedisService;

    private final RestTemplate restTemplate;

    public SmsService() {
        this.restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory());
    }

    public Map<String, Object> sendSms(String account) {
        // 限制：每个账号每 60 秒只能发送一次验证码，且每小时最多发送 5 次
        int intervalSeconds = 60; // 发送间隔 60 秒
        int maxAttemptsPerHour = 10; // 每小时最多 5 次
        String redisKey = "sms:send:" + account;
        String redisCountKey = "sms:send:count:" + account;

        // 检查发送间隔限制
        Long lastSendTime = captchaRedisService.getLastSendTime(redisKey);
        if (lastSendTime != null && System.currentTimeMillis() - lastSendTime < intervalSeconds * 1000) {
            return createErrorResponse("发送过于频繁，请稍后再试");
        }

        // 检查发送次数限制
        Integer sendCount = captchaRedisService.getSendCount(redisCountKey);
        if (sendCount != null && sendCount >= maxAttemptsPerHour) {
            return createErrorResponse("1小时内最多发送 " + maxAttemptsPerHour + " 次验证码");
        }

        // 生成验证码
        String smsCode = generateSmsCode();
        String signature = "【大唐云科技】";
        String messageContent = signature + smsCode;

        // 构建请求参数
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("SpCode", spCode);
        body.add("LoginName", loginName);
        body.add("Password", password);
        body.add("MessageContent", messageContent);
        body.add("UserNumber", account);
        body.add("SerialNumber", generateSerialNumber());
        body.add("ScheduleTime", "");

        // 发送 POST 请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(body, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, request, String.class);

        Map<String, Object> result = new HashMap<>();
        if (response.getStatusCode() == HttpStatus.OK) {
            // 解析响应
            String responseBody = response.getBody();
            String[] params = responseBody.split("&");
            for (String param : params) {
                String[] keyValue = param.split("=");
                if (keyValue.length == 2) {
                    result.put(keyValue[0], keyValue[1]);
                } else {
                    result.put(keyValue[0], "");
                }
            }

            // 发送成功
            if ("0".equals(result.get("result"))) {
                captchaRedisService.saveSmsCode(account, smsCode, 5);
                captchaRedisService.saveLastSendTime(redisKey, System.currentTimeMillis(), intervalSeconds); // 保存发送时间
                captchaRedisService.incrementSendCount(redisCountKey, 1, 1, 3600); // 计数加1，有效期1小时
            }
        } else {
            result.put("result", "1"); // 错误标识
            result.put("description", "短信发送失败，状态码：" + response.getStatusCode());
        }

        return result;
    }

    // 错误响应
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("result", "1");
        errorResponse.put("description", message);
        return errorResponse;
    }


    private String generateSmsCode() {
        return String.format("%06d", new Random().nextInt(999999));
    }

    private String generateSerialNumber() {
        return String.format("%020d", new Random().nextLong()); // 生成20位数字的流水号
    }

}

