package com.zksy.common.sms;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendBatchSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendBatchSmsResponse;
import com.google.gson.Gson;
import com.zksy.common.utils.StringUtils;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Slf4j
@Component
@ConditionalOnProperty(prefix = "aliyun.sms", name = "access-key-id")
public class SmsTemplate {

    private final SmsProperties properties;
    private final AsyncClient client;

    @Autowired
    public SmsTemplate(SmsProperties properties) {
        this.properties = properties;
        this.client = initClient();
    }

    private AsyncClient initClient() {
        try {
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId(properties.getAccessKeyId())
                    .accessKeySecret(properties.getAccessKeySecret())
                    .build());

            return AsyncClient.builder()
                    .region(properties.getRegionId())
                    .credentialsProvider(provider)
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    .setEndpointOverride("dysmsapi.aliyuncs.com")
                                    .setConnectTimeout(Duration.ofSeconds(30))
                    )
                    .build();
        } catch (Exception e) {
            log.error("阿里云短信客户端初始化失败", e);
            throw new RuntimeException("短信服务初始化异常", e);
        }
    }

    public Map<String, Boolean> sendBatchSms(List<String> phoneNumbers, String templateParam) {
        return sendBatchSms(phoneNumbers, templateParam, properties.getTemplateCode());
    }

    public Map<String, Boolean> sendBatchSms(List<String> phoneNumbers, String templateParam, String templateCode) {
        if (phoneNumbers == null || phoneNumbers.isEmpty()) {
            log.warn("批量发送短信失败：手机号列表为空");
            return Collections.emptyMap();
        }
        if (StringUtils.isEmpty(templateCode)) {
            log.warn("批量发送短信失败：模板编码为空");
            return phoneNumbers.stream().collect(Collectors.toMap(p -> p, p -> false));
        }

        try {
            List<String> signNames = phoneNumbers.stream()
                    .map(phone -> properties.getSignName())
                    .collect(Collectors.toList());

            List<String> templateParams = phoneNumbers.stream()
                    .map(phone -> templateParam)
                    .collect(Collectors.toList());

            SendBatchSmsRequest request = SendBatchSmsRequest.builder()
                    .phoneNumberJson(new Gson().toJson(phoneNumbers))
                    .signNameJson(new Gson().toJson(signNames))
                    .templateCode(templateCode)
                    .templateParamJson(new Gson().toJson(templateParams))
                    .build();

            CompletableFuture<SendBatchSmsResponse> response = client.sendBatchSms(request);
            SendBatchSmsResponse resp = response.get();

            log.info("批量短信发送响应: templateCode={}, code={}", templateCode, resp.getBody().getCode());
            return phoneNumbers.stream()
                    .collect(Collectors.toMap(
                            phone -> phone,
                            phone -> "OK".equals(resp.getBody().getCode())
                    ));
        } catch (Exception e) {
            log.error("批量短信发送失败: templateCode={}, error={}", templateCode, e.getMessage());
            return phoneNumbers.stream()
                    .collect(Collectors.toMap(
                            phone -> phone,
                            phone -> false
                    ));
        }
    }

    public Map<String, Boolean> sendMaintainNotify(List<String> phoneNumbers,
                                                    String deviceName, String deviceNo,
                                                    String location, String faultDesc) {
        String maintainTemplateCode = properties.getMaintainTemplateCode();
        if (StringUtils.isEmpty(maintainTemplateCode)) {
            log.warn("维修派单短信模板未配置（aliyun.sms.maintain-template-code），跳过发送");
            return phoneNumbers != null
                    ? phoneNumbers.stream().collect(Collectors.toMap(p -> p, p -> false))
                    : Collections.emptyMap();
        }

        com.alibaba.fastjson2.JSONObject params = new com.alibaba.fastjson2.JSONObject();
        params.put("deviceName", StringUtils.isNotEmpty(deviceName) ? deviceName : "未知设备");
        params.put("deviceNo", StringUtils.isNotEmpty(deviceNo) ? deviceNo : "无");
        params.put("location", StringUtils.isNotEmpty(location) ? location : "暂无位置信息");
        params.put("faultDesc", StringUtils.isNotEmpty(faultDesc) ? faultDesc : "请查看工单详情");

        return sendBatchSms(phoneNumbers, params.toJSONString(), maintainTemplateCode);
    }
}
