package com.njcn.product.event.transientes.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.SM3;
import cn.hutool.json.JSONObject;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.product.event.transientes.pojo.dto.MsgDTO;
import com.njcn.product.event.transientes.pojo.dto.SmsResponseDTO;
import com.njcn.product.event.transientes.pojo.dto.SmsSendDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: cdf
 * @CreateTime: 2025-10-15
 * @Description: 短信工具
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class SmsUtils {


    private final RestTemplate restTemplate;

    @Value("${smsServer.info}")
    private String smsServer;

    @Value("${smsServer.account}")
    private String account;

    @Value("${smsServer.password}")
    private String password;


    public List<SmsResponseDTO.SmsItem> sendSmSToUser(List<SmsSendDTO.ItemInner> temList) {
        SmsSendDTO smsSendDTO = new SmsSendDTO();
        smsSendDTO.setServiceCode("01001101");
        smsSendDTO.setAccount(account);

        String nowTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern(DatePattern.PURE_DATETIME_PATTERN));
        String sm3Hash = new SM3().digestHex(account + password + nowTime);
        smsSendDTO.setToken(sm3Hash);
        smsSendDTO.setTs(nowTime);
        smsSendDTO.setItems(temList);

        log.info("短信请求实体{}", smsSendDTO);

        String url = smsServer + "/sms/msg";
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>(new JSONObject(smsSendDTO).toString(), headers);

            ResponseEntity<SmsResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    requestEntity,
                    SmsResponseDTO.class
            );
            // 处理响应
            return handleSmsResponse(response);
        } catch (Exception e) {
            log.error("短信接口调用失败", e);
            return new ArrayList<>();
        }
    }

    private List<SmsResponseDTO.SmsItem> handleSmsResponse(ResponseEntity<SmsResponseDTO> response) {
        if (response.getStatusCode() == HttpStatus.OK) {
            SmsResponseDTO smsResponse = response.getBody();
            if (smsResponse != null && "0".equals(smsResponse.getCode())) {
                log.info("短信发送成功，batchId: {},发送条数{}", smsResponse.getBatchId(),smsResponse.getItems().size());
                return smsResponse.getItems();
            } else {
                log.error("短信发送失败: {}", (smsResponse != null ? smsResponse.getMessage() : "API 返回异常"));
                return new ArrayList<>();
            }
        } else {
            log.error("HTTP 请求失败，状态码: {}", response.getStatusCode());
            return new ArrayList<>();
        }
    }

}
