package com.ai.da.common.utils;

import com.ai.da.mapper.primary.entity.Account;
import com.ai.da.mapper.primary.entity.TrialOrder;
import com.alibaba.fastjson.JSONObject;
import com.ai.da.common.config.exception.BusinessException;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ses.v20201002.SesClient;
import com.tencentcloudapi.ses.v20201002.models.SendEmailRequest;
import com.tencentcloudapi.ses.v20201002.models.SendEmailResponse;
import com.tencentcloudapi.ses.v20201002.models.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 邮件发送类
 */
@Slf4j
public class SendEmailUtil {
    /**
     * 秘钥id
     */
    private static String SECRET_ID = "AKID52lRwDIBsLaZLtDI9m9LJMAj36wYw50i";
    /**
     * 秘钥key
     */
    private static String SECRET_KEy = "XqujLlywhHfrqcCYfYVHtNgmeIiwxkKf";
    /**
     * 发信地址
     */
    private static String SEND_ADDRESS = "info@aida.com.hk";
    private final static String CODE_CREATE_SEND_ADDRESS = "info@code-create.com.hk";
    /**
     * 登入主题
     */
    public static String LOGIN_SUBJECT = "Log on";
    /**
     * 忘记密码主题
     */
    public static String FORGET_PWD_SUBJECT = "Reset password";
    /**
     * 异常ip
     */
    public static String EXCEPTION_ID_SUBJECT = "Exception ip";
    /**
     * 绑定邮箱
     */
    public static String BIND_MAILBOX_SUBJECT = "绑定邮箱";
    /**
     * 登入模板id
     */
    public static Long LOGIN_TEMPLATE_ID = 58020L;
    /**
     * 修改密码模板id
     */
    public static Long UPDATE_PWD_TEMPLATE_ID = 58022L;
    /**
     * 异常ip模板id
     */
    public static Long EXCEPTION_ID_TEMPLATE_ID = 58021L;
    /**
     * 绑定邮箱模板id
     */
    public static Long BIND_MAILBOX_TEMPLATE_ID = 45619L;


    public static Boolean send(String receiverAddress, String ip, Long templateId, String verifyCode) {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(SECRET_ID, SECRET_KEy);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ses.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendEmailRequest req = new SendEmailRequest();

            req.setFromEmailAddress(SEND_ADDRESS);
            req.setDestination(new String[]{receiverAddress});
            String subject = templateId == LOGIN_TEMPLATE_ID ? LOGIN_SUBJECT :
                    templateId == UPDATE_PWD_TEMPLATE_ID ? FORGET_PWD_SUBJECT :
                            templateId == EXCEPTION_ID_TEMPLATE_ID ? EXCEPTION_ID_SUBJECT : BIND_MAILBOX_SUBJECT;
            req.setSubject(subject);
            req.setTemplate(contractTemplate(templateId, verifyCode, ip));

            // 返回的resp是一个SendEmailResponse的实例，与请求对象对应
            SendEmailResponse resp = client.SendEmail(req);
            // 输出json格式的字符串回包
            log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
            return Boolean.TRUE;
        } catch (TencentCloudSDKException e) {
            log.info("邮件发送失败###{}", e.toString());
            throw new BusinessException("failed.to.send.mail");
        }
    }

    private static Template contractTemplate(Long templateId, String verifyCode, String ip) {
        Template template = new Template();
        template.setTemplateID(templateId);

        JSONObject jsonObject = new JSONObject();
        if (templateId == EXCEPTION_ID_TEMPLATE_ID) {
            jsonObject.put("exceptionIp", ip);
            jsonObject.put("loginTime", DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS));
        } else {
            jsonObject.put("code", verifyCode);
        }
        template.setTemplateData(jsonObject.toJSONString());
        return template;
    }

    /**
     * 发送不同类型的邮件
     *
     * @param receiverAddress 收件人邮箱地址
     * @param senderAddress   发件人邮箱地址
     * @param emailType       邮件类型：1 - 提交试用请求，2 - 审批通过，3 - 试用请求通过通知
     * @return 发送结果
     */
    private final static Long YOUR_TRIAL_TEMPLATE_ID = 117214L;
    private final static Long APPROVAL_TEMPLATE_ID = 117215L;
    private final static Long NOTIFICATION_TEMPLATE_ID = 117216L;
    public static void sendCustomEmail(String receiverAddress, String senderAddress, TrialOrder trialOrder, int emailType) {
        try {
            // 实例化一个认证对象
            Credential cred = new Credential(SECRET_ID, SECRET_KEy);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ses.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
            SendEmailRequest req = new SendEmailRequest();
            if (StringUtils.isEmpty(senderAddress)) {
                senderAddress = SEND_ADDRESS;
            }
            req.setFromEmailAddress(senderAddress);
            req.setDestination(new String[]{receiverAddress});

            // 根据邮件类型设置不同的主题和模板
            String subject = "";
            Template template = new Template();
            switch (emailType) {
                case 1:
                    subject = "试用订单请求";
                    template.setTemplateID(YOUR_TRIAL_TEMPLATE_ID);
                    template.setTemplateData(buildTrialOrderData(trialOrder));
                    break;
                case 2:
                    subject = "试用订单审批通过";
                    template.setTemplateID(APPROVAL_TEMPLATE_ID);
                    template.setTemplateData(buildApprovalData(trialOrder));
                    break;
                case 3:
                    subject = "Approval Confirmation for AiDA System Trial Access";
                    template.setTemplateID(NOTIFICATION_TEMPLATE_ID);
                    template.setTemplateData(buildNotificationData(trialOrder));
                    break;
                default:
                    break;
            }

            req.setSubject(subject);
            req.setTemplate(template);

            // 发送邮件
            SendEmailResponse resp = client.SendEmail(req);
            log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.info("邮件发送失败###{}", e.toString());
            throw new BusinessException("failed.to.send.mail");
        }
    }
    private final static Long WILLBEEXPIRED_TEMPLATE_ID = 118178L;
    public static void sendWillBeExpiredEmail(Account account, String senderAddress) {
        try {
            // 实例化一个认证对象
            Credential cred = new Credential(SECRET_ID, SECRET_KEy);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ses.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
            SendEmailRequest req = new SendEmailRequest();
            if (StringUtils.isEmpty(senderAddress)) {
                senderAddress = SEND_ADDRESS;
            }
            req.setFromEmailAddress(senderAddress);
            req.setDestination(new String[]{account.getUserEmail()});

            // 根据邮件类型设置不同的主题和模板
            String subject = "";
            Template template = new Template();
            subject = "Renewal notice";
            template.setTemplateID(WILLBEEXPIRED_TEMPLATE_ID);
            template.setTemplateData(buildAccountData(account));

            req.setSubject(subject);
            req.setTemplate(template);

            // 发送邮件
            SendEmailResponse resp = client.SendEmail(req);
            log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.info("邮件发送失败###{}", e.toString());
            throw new BusinessException("failed.to.send.mail");
        }
    }

    private static String buildAccountData(Account account) {
        JSONObject jsonObject = new JSONObject();
        // 设置试用订单相关数据
        jsonObject.put("userName", account.getUserName());

        // 用户到期时间戳
        Long timestamp = account.getValidEndTime(); // 替换为你的时间戳
        if (null != timestamp) {
            // 获取当前时间戳
            Long currentTimestamp = System.currentTimeMillis();

            // 计算时间差（毫秒）
            long timeDifference = currentTimestamp - timestamp;

            // 向上取整计算天数
            long days = (timeDifference + 24 * 60 * 60 * 1000 - 1) / (24 * 60 * 60 * 1000);
            jsonObject.put("days", days);
        }
        return jsonObject.toJSONString();
    }

    // 构建试用订单数据
    private static String buildTrialOrderData(TrialOrder trialOrder) {
        JSONObject jsonObject = new JSONObject();
        // 设置试用订单相关数据
        jsonObject.put("surname", trialOrder.getSurname());
        jsonObject.put("givenName", trialOrder.getGivenName());
        jsonObject.put("userName", trialOrder.getUserName());
        jsonObject.put("email", trialOrder.getEmail());
        jsonObject.put("country", trialOrder.getCountry());
        return jsonObject.toJSONString();
    }

    // 构建审批通过数据
    private static String buildApprovalData(TrialOrder trialOrder) {
        JSONObject jsonObject = new JSONObject();
        // 设置审批通过相关数据
        jsonObject.put("surname", trialOrder.getSurname());
        jsonObject.put("givenName", trialOrder.getGivenName());
        jsonObject.put("userName", trialOrder.getUserName());
        jsonObject.put("email", trialOrder.getEmail());
        jsonObject.put("country", trialOrder.getCountry());
        return jsonObject.toJSONString();
    }

    // 构建试用订单通过通知数据
    private static String buildNotificationData(TrialOrder trialOrder) {
        JSONObject jsonObject = new JSONObject();
        // 设置试用订单通过通知相关数据
        jsonObject.put("title", trialOrder.getTitle());
        jsonObject.put("surname", trialOrder.getSurname());
        jsonObject.put("givenName", trialOrder.getGivenName());
        jsonObject.put("userName", trialOrder.getUserName());
        jsonObject.put("email", trialOrder.getEmail());
        return jsonObject.toJSONString();
    }

    private final static Long UPGRADE_NOTIFICATION_ID = 118855L;
    public static void sendUpgradeNotification(Account account, String senderAddress) {
        try {
            // 实例化一个认证对象
            Credential cred = new Credential(SECRET_ID, SECRET_KEy);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ses.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
            SendEmailRequest req = new SendEmailRequest();
            if (StringUtils.isEmpty(senderAddress)) {
                senderAddress = CODE_CREATE_SEND_ADDRESS;
            }
            req.setFromEmailAddress(senderAddress);
            req.setDestination(new String[]{account.getUserEmail()});

            // 根据邮件类型设置不同的主题和模板
            String subject = "";
            Template template = new Template();
            subject = "Notice: AiDA 3.0 Website Maintenance Downtime";
            template.setTemplateID(UPGRADE_NOTIFICATION_ID);
            template.setTemplateData(buildAccountData(account));

            req.setSubject(subject);
            req.setTemplate(template);

            // 发送邮件
            SendEmailResponse resp = client.SendEmail(req);
            log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.info("邮件发送失败###{}", e.toString());
            throw new BusinessException("failed.to.send.mail");
        }
    }
}
