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

import cn.hutool.core.util.ObjectUtil;
import com.aliyun.dm20151123.Client;
import com.aliyun.dm20151123.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.njcn.msgpush.module.push.client.sender.EmailSender;
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.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.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Slf4j
public class AliyunEmailSender implements EmailSender {

    private static final String ACCOUNT_NAME = "njcn@shining-electric.cn";
    private static final Integer ADDRESS_TYPE = 1;
    private static final Boolean REPLY_TO_ADDRESS = false;
    private static final String FROM_ALIAS = "南京灿能";

    private final Sender sender;

    private Client emailClient;

    public AliyunEmailSender(AliYunMailSetting aliYunMailSetting, Sender sender) {
        this.sender = sender;
        if (ObjectUtil.isNotNull(aliYunMailSetting)) {
            Config config = new Config()
                    .setAccessKeyId(aliYunMailSetting.getAccessKeyId())
                    .setAccessKeySecret(aliYunMailSetting.getAccessKeySecret())
                    .setRegionId(aliYunMailSetting.getRegionId())
                    .setEndpoint(aliYunMailSetting.getEndpoint());

            try {
                this.emailClient = new Client(config);
            } catch (Exception e) {
                log.error("阿里云邮件客户端初始化失败", e);
                this.emailClient = null;
            }
        }
    }

    @Override
    public SendResult sendEmail(MessageRecordDO message, Map<String, Object> params) {
        if (emailClient == null) {
            return SendResult.configInvalid("当前服务商邮件渠道初始化失败");
        }
        Future<SendResult> future = this.sender.MSG_PUSH_THREAD_POOL_EXECUTOR.submit(() -> {
            RuntimeOptions runtimeOptions = new RuntimeOptions();
            runtimeOptions.autoretry = true;

            SingleSendMailRequest request = new SingleSendMailRequest()
                    .setAccountName(ACCOUNT_NAME)
                    .setAddressType(ADDRESS_TYPE)
                    .setReplyToAddress(REPLY_TO_ADDRESS)
                    .setToAddress(message.getReceiver())
                    .setSubject(message.getTitle())
                    .setHtmlBody(message.getContent())
                    .setTextBody("")
                    .setFromAlias(FROM_ALIAS);

            try {
                LocalDateTime now = LocalDateTime.now();
                long start = now.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                SingleSendMailResponse response = this.emailClient.singleSendMailWithOptions(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()) {
                    message.setThirdPartyId(response.getBody().getEnvId());
                    // 电信短信同步返回成功同样只代表已受理，最终状态以后续回执为准。
                    this.getDownInfo(message);
                    // 邮件接口同步返回成功时，当前平台直接认定本次发送成功。
                    return SendResult.accepted(now, costTime, response.getBody().getEnvId());
                }

                // 邮件服务失败同样统一转换为平台错误码和中文错误信息。
                return this.sender.buildFailureResult(
                        message,
                        String.valueOf(response.getStatusCode()),
                        null,
                        "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();
        }
    }

    private void getDownInfo(MessageRecordDO message) {
        // 回执查询延后执行，给第三方落库和状态变更留出时间。
        this.sender.MSG_CALLBACK_THREAD_POOL_SCHEDULER.schedule(() -> {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            SenderStatisticsDetailByParamRequest request = new SenderStatisticsDetailByParamRequest()
                    .setToAddress(message.getReceiver())
                    .setLength(1);
            try {
                SenderStatisticsDetailByParamResponse detail = this.emailClient.senderStatisticsDetailByParam(request);
                if (detail.statusCode == 200) {
                    List<SenderStatisticsDetailByParamResponseBody.SenderStatisticsDetailByParamResponseBodyDataMailDetail> mailDetailList = detail.body.getData().mailDetail;

                    if (mailDetailList.size() > 0) {
                        SenderStatisticsDetailByParamResponseBody.SenderStatisticsDetailByParamResponseBodyDataMailDetail mailDetail = mailDetailList.get(0);
                        if (mailDetail.getStatus() == 0) {
                            // 回执确认成功后，复用统一成功落库逻辑。
                            this.sender.applyCallbackResult(message, SendResult.success(message.getSendTime(), message.getCostTime(), message.getThirdPartyId()));
                        } else {
                            SendResult failedResult = this.sender.buildFailureResult(
                                    message,
                                    mailDetail.getErrorClassification(),
                                    mailDetail.getErrorClassification(),
                                    "THIRD_PARTY_CALLBACK_FAILED",
                                    "邮件回执返回失败",
                                    false
                            );
                            this.sender.applyCallbackResult(message, failedResult);
                        }
                    } else {
                        SendResult failedResult = this.sender.buildFailureResult(
                                message,
                                null,
                                null,
                                "THIRD_PARTY_CALLBACK_FAILED",
                                "邮件回执返回失败",
                                false
                        );
                        this.sender.applyCallbackResult(message, failedResult);
                    }
                }
            } catch (Exception e) {
                log.error("电信短信回执查询失败", e);
            }
        }, 30, TimeUnit.SECONDS);
    }
}
