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

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dm20151123.Client;
import com.aliyun.dm20151123.models.SingleSendMailRequest;
import com.aliyun.dm20151123.models.SingleSendMailResponse;
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.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Slf4j
public class AliyunEmailSender implements EmailSender {

    private static final String ACCOUNT_NAME = "accountName";
    private static final String REPLY_TO_ADDRESS = "replyToAddress";
    private static final String FROM_ALIAS = "fromAlias";

    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;

            JSONObject jsonObject = JSON.parseObject(message.getExtraInfo());
            SingleSendMailRequest request = new SingleSendMailRequest()
                    .setAccountName(jsonObject.getString(ACCOUNT_NAME))
                    .setAddressType(1)
                    .setReplyToAddress(jsonObject.getBooleanValue(REPLY_TO_ADDRESS))
                    .setToAddress(message.getReceiver())
                    .setSubject(message.getTitle())
                    .setHtmlBody(message.getContent())
                    .setTextBody("")
                    .setFromAlias(jsonObject.getString(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()) {
                    // 邮件接口同步返回成功时，当前平台直接认定本次发送成功。
                    return SendResult.success(now, costTime, null);
                }

                // 邮件服务失败同样统一转换为平台错误码和中文错误信息。
                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();
        }
    }
}
