package com.njcn.msgpush.module.push.client.sender.impl.sms;

import cn.hutool.core.util.ObjectUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsRequest;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.njcn.msgpush.module.push.client.sender.SendResult;
import com.njcn.msgpush.module.push.client.sender.Sender;
import com.njcn.msgpush.module.push.client.sender.SmsSender;
import com.njcn.msgpush.module.push.client.setting.impl.AliYunMailSetting;
import com.njcn.msgpush.module.push.dal.dataobject.message.MessageRecordDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Slf4j
public class AliyunSmsSender implements SmsSender {

    public static final String OK = "OK";

    private final Sender sender;

    private Client smsClient;

    public AliyunSmsSender(AliYunMailSetting aliYunSmsSetting, Sender sender) {
        this.sender = sender;
        if (ObjectUtil.isNotNull(aliYunSmsSetting)) {
            Config config = new Config()
                    .setAccessKeyId(aliYunSmsSetting.getAccessKeyId())
                    .setAccessKeySecret(aliYunSmsSetting.getAccessKeySecret())
                    .setRegionId(aliYunSmsSetting.getRegionId())
                    .setEndpoint(aliYunSmsSetting.getEndpoint());
            try {
                this.smsClient = new Client(config);
            } catch (Exception e) {
                log.error("阿里云短信客户端初始化失败", e);
                this.smsClient = null;
            }
        }
    }

    @Override
    public SendResult sendSms(MessageRecordDO message) {
        if (smsClient == null) {
            return SendResult.configInvalid("当前服务商短信渠道初始化失败");
        }
        Future<SendResult> future = this.sender.MSG_PUSH_THREAD_POOL_EXECUTOR.submit(() -> {
            RuntimeOptions runtimeOptions = new RuntimeOptions();
            runtimeOptions.autoretry = true;
            SendSmsRequest request = new SendSmsRequest()
                    .setPhoneNumbers(message.getReceiver())
                    .setSignName(message.getTitle())
                    .setTemplateCode(message.getTemplateCode())
                    .setTemplateParam(message.getTemplateParams());
            try {
                LocalDateTime now = LocalDateTime.now();
                long start = now.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                SendSmsResponse response = this.smsClient.sendSmsWithOptions(request, runtimeOptions);
                LocalDateTime end = LocalDateTime.now();
                int costTime = (int) (end.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() - start);
                message.setSendTime(now);
                message.setCostTime(costTime);
                if (HttpStatus.OK.value() == response.getStatusCode() && response.getBody() != null && OK.equals(response.getBody().getCode())) {
                    String bizId = response.getBody().getBizId();
                    message.setThirdPartyId(bizId);
                    // 阿里云短信同步接口只表示“已受理”，最终是否送达依赖后续回执查询。
                    this.getDownInfo(bizId, message);
                    return SendResult.accepted(now, costTime, bizId);
                }
                String providerRawCode = response.getBody() == null ? null : response.getBody().getCode();
                String providerRawMessage = response.getBody() == null ? null : response.getBody().getMessage();
                // 第三方失败统一在这里映射为平台错误码和中文错误信息。
                return this.sender.buildFailureResult(
                        message,
                        providerRawCode,
                        providerRawMessage,
                        "THIRD_PARTY_CALL_FAILED",
                        "第三方服务调用失败",
                        false
                );
            } catch (Exception e) {
                log.error("阿里云短信发送失败", e);
                return this.sender.buildCallFailedResult("第三方服务调用失败");
            }
        });
        try {
            return future.get(3, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("阿里云短信发送超时或执行异常", e);
            return this.sender.buildTimeoutResult();
        }
    }

    @Override
    public List<SendResult> sendBatchSms(List<MessageRecordDO> messageList) {
        List<SendResult> results = new ArrayList<>();
        for (MessageRecordDO message : messageList) {
            results.add(this.sendSms(message));
        }
        return results;
    }

    @Override
    public void queryTemplate(String templateIdentifier) {
    }

    private void getDownInfo(String bizId, MessageRecordDO message) {
        // 回执存在延迟，这里延后查询，避免刚发送完就拿不到最终状态。
        this.sender.MSG_CALLBACK_THREAD_POOL_SCHEDULER.schedule(() -> {
            QuerySendDetailsRequest request = new QuerySendDetailsRequest()
                    .setPhoneNumber(message.getReceiver())
                    .setBizId(bizId)
                    .setSendDate(message.getSendTime().format(DateTimeFormatter.ofPattern("yyyyMMdd")))
                    .setCurrentPage(1L)
                    .setPageSize(10L);
            try {
                QuerySendDetailsResponse response = this.smsClient.querySendDetails(request);
                if (response.getBody() == null || response.getBody().getSmsSendDetailDTOs() == null || response.getBody().getSmsSendDetailDTOs().getSmsSendDetailDTO() == null) {
                    return;
                }
                response.getBody().getSmsSendDetailDTOs().getSmsSendDetailDTO().forEach(detail -> {
                    if (!"DELIVERED".equals(detail.getErrCode())) {
                        SendResult failedResult = this.sender.buildFailureResult(
                                message,
                                detail.getErrCode(),
                                null,
                                "THIRD_PARTY_CALLBACK_FAILED",
                                "短信回执返回失败",
                                false
                        );
                        this.sender.applyCallbackResult(message, failedResult);
                    } else {
                        // 送达成功后，统一复用主流程成功状态更新逻辑。
                        this.sender.applyCallbackResult(
                                message,
                                SendResult.success(message.getSendTime(), message.getCostTime(), message.getThirdPartyId())
                        );
                    }
                });
            } catch (Exception e) {
                log.error("阿里云短信回执查询失败", e);
            }
        }, 20, TimeUnit.SECONDS);
    }
}
