package com.ai.da.common.utils;

import com.ai.da.mapper.primary.entity.Account;
import com.ai.da.mapper.primary.entity.TrialOrder;
import com.ai.da.model.dto.AffiliateEmailParamsDTO;
import com.ai.da.model.dto.SubscriptionEmailParamsDTO;
import com.alibaba.fastjson.JSONObject;
import com.ai.da.common.config.exception.BusinessException;
import com.alibaba.fastjson2.JSON;
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.Attachment;
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.Base64;
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 = "绑定邮箱";
    public static String CHANGE_MAILBOX_SUBJECT = "Change Mailbox";
    /**
     * 登入模板id
     */
    public static Long LOGIN_TEMPLATE_ID = 58020L;
    public static Long PORTFOLIO_REGISTER_ID = 124847L;
    /**
     * 修改密码模板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 Long BIND_MAILBOX_TEMPLATE_ID = 132754L;

    public static Long CHANGE_MAILBOX_TEMPLATE_ID = 128210L;


    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 :
                                    templateId == CHANGE_MAILBOX_TEMPLATE_ID ? CHANGE_MAILBOX_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;
    private final static Long NOTIFICATION_CHINESE_TEMPLATE_ID = 122229L;
    private final static Long TRIAL_ORDER_LIST_ID = 122273L;
    private final static Long NO_TRIAL_ORDER_LIST_ID = 122591L;

    public static void sendCustomEmail(String receiverAddress, String senderAddress, TrialOrder trialOrder, int emailType, String country, boolean link) {
        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";
                    if (country.equals("China")) {
                        template.setTemplateID(NOTIFICATION_CHINESE_TEMPLATE_ID);
                    } else {
                        template.setTemplateID(NOTIFICATION_TEMPLATE_ID);
                    }
                    template.setTemplateData(buildNotificationData(trialOrder, link));
                    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");
        }
    }

    public static void sendExcelEmail(String receiverAddress, String senderAddress, byte[] fileContent, String fileName) {
        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();
            subject = "昨日试用订单数据";
            template.setTemplateID(TRIAL_ORDER_LIST_ID);

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

            Attachment attachment = new Attachment();
            attachment.setFileName(fileName); // 设置附件文件名
            // 设置附件内容
            attachment.setContent(Base64.getEncoder().encodeToString(fileContent));
            req.setAttachments(new Attachment[]{attachment});
            // 发送邮件
            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");
        }
    }


    public static void sendNoExcelEmail(String receiverAddress, 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[]{receiverAddress});

            // 根据邮件类型设置不同的主题和模板
            String subject = "";
            Template template = new Template();
            subject = "昨日试用订单数据";
            template.setTemplateID(NO_TRIAL_ORDER_LIST_ID);

            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, boolean link) {
        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());
        if (link) {
            jsonObject.put("days", 14);
        } else {
            jsonObject.put("days", 5);
        }
        return jsonObject.toJSONString();
    }

    private final static Long UPGRADE_NOTIFICATION_ID = 146605L;
    //    private final static Long UPGRADE_NOTIFICATION_ID = 146551L;
    private final static Long UPGRADE_SUCCESS_NOTIFICATION_ID = 118856L;
    private final static Long UPGRADE_NOTIFICATION_ID_CHINESE = 146604L;
    //    private final static Long UPGRADE_NOTIFICATION_ID_CHINESE = 146552L;
    private final static Long UPGRADE_SUCCESS_NOTIFICATION_ID_CHINESE = 122899L;

    public static void sendUpgradeNotification(Account account, String senderAddress, Integer type) {
        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();
            if (type == 1) {
                subject = "AiDA 3.1.0 System Maintenance Announcement";
                template.setTemplateID(UPGRADE_NOTIFICATION_ID);
            }else {
                subject = "AiDA 3.1.0 系统维护公告";
                template.setTemplateID(UPGRADE_NOTIFICATION_ID_CHINESE);
            }
//            if (type == 1) {
//                subject = "Successful System Upgrade and New Features in AiDA 3.0";
//                template.setTemplateID(UPGRADE_SUCCESS_NOTIFICATION_ID);
//            }else {
//                subject = "系统升级成功和AiDA 3.0新功能";
//                template.setTemplateID(UPGRADE_SUCCESS_NOTIFICATION_ID_CHINESE);
//            }
            template.setTemplateData(buildAccountData(account));

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

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

    // todo ?需要保留吗
    private final static Long QUESTIONNAIRE_FEEDBACK_EN_ID = 124151L;
    private final static Long QUESTIONNAIRE_FEEDBACK_CN_ID = 124156L;

    public static void questionnaireRelatedNotify(String userName, String email, String language) {
        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();
            req.setFromEmailAddress(CODE_CREATE_SEND_ADDRESS);
            req.setDestination(new String[]{email});

            // 根据邮件类型设置不同的主题和模板
            Template template = new Template();
            String subject = "Thank You for Completing the AiDA System Survey";
            template.setTemplateID(QUESTIONNAIRE_FEEDBACK_EN_ID);
            if (language.equals("CN")) {
                subject = "感谢您完成AiDA系统问卷调查";
                template.setTemplateID(QUESTIONNAIRE_FEEDBACK_CN_ID);
            }

            JSONObject parameter = new JSONObject();
            parameter.put("userName", userName);

            template.setTemplateData(parameter.toJSONString());

            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 NEW_USER_PAYMENT_NOTIFICATION_EN = 124889L;
    private final static Long NEW_USER_PAYMENT_NOTIFICATION_CN = 124888L;
    private final static Long RENEWAL_NOTIFICATION_FOR_OLD_USER_EN = 124892L;
    private final static Long RENEWAL_NOTIFICATION_FOR_OLD_USER_CN = 124891L;

    public static void notificationForPaidUser(String receiverAddress, int emailType, String country, String userName, String date) {
        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();
            req.setFromEmailAddress(SEND_ADDRESS);
            req.setDestination(new String[]{receiverAddress});

            // 根据邮件类型设置不同的主题和模板
            String subject = "";
            Template template = new Template();
            JSONObject parameter = new JSONObject();
            switch (emailType) {
                // 新用户
                case 1:
                    subject = "Welcome to AiDA!";
                    if (country.equals("China")) {
                        template.setTemplateID(NEW_USER_PAYMENT_NOTIFICATION_CN);
                    } else {
                        template.setTemplateID(NEW_USER_PAYMENT_NOTIFICATION_EN);
                    }
                    parameter.put("userName", userName);
                    parameter.put("email", receiverAddress);
                    break;
                // 续费用户
                case 2:
                    subject = "Account renewal notification";
                    if (country.equals("China")) {
                        template.setTemplateID(RENEWAL_NOTIFICATION_FOR_OLD_USER_CN);
                    } else {
                        template.setTemplateID(RENEWAL_NOTIFICATION_FOR_OLD_USER_EN);
                    }
                    break;
                default:
                    break;
            }

            parameter.put("userName", userName);
            parameter.put("date", date);
            template.setTemplateData(parameter.toJSONString());

            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");
        }
    }


    public static Boolean designWorksRegister(String userEmail, String randomVerifyCode) {
        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[]{userEmail});
            String subject = "Tourist registration";
            req.setSubject(subject);

            req.setTemplate(contractTemplate(PORTFOLIO_REGISTER_ID, randomVerifyCode, null));

            // 返回的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");
        }
    }

    // todo 目前该定时器已取消，是否需要保留该模板？
    private final static Long NEW_USER_REGISTER_NOTIFICATION_EN = 126919L;

    public static void notificationForRegisterUser(String receiverAddress) {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 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});

            req.setSubject("Welcome to AiDa");
            Template template = new Template();
            template.setTemplateID(NEW_USER_REGISTER_NOTIFICATION_EN);
            template.setTemplateData("{\"email\":\" " + receiverAddress + "\"}");
            req.setTemplate(template);

            // 返回的resp是一个SendEmailResponse的实例，与请求对象对应
            SendEmailResponse resp = client.SendEmail(req);
            log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.info("邮件发送至{} 发送失败###{}", receiverAddress, e.toString());
            log.error(e.getMessage());
            // 这里不再抛出异常 失败就不发，保证后续正常运行
//            throw new BusinessException("failed.to.send.mail");
        }
    }

    private final static Long UPLOAD_TIMEOUT_REMINDER = 128324L;

    public static void uploadTimeoutReminder(String userName, String time) {
        String xp = "xupei3360@163.com";
        String wxd = "X1627315083@163.com";
        String pkc = "kaicpang.pang@connect.polyu.hk";
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 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[]{xp, wxd, pkc});
            Template template = new Template();
            req.setSubject("上传图片超时提醒");
            template.setTemplateID(UPLOAD_TIMEOUT_REMINDER);
            JSONObject param = new JSONObject();
            param.put("userName", userName);
            param.put("time", time);

            template.setTemplateData(param.toJSONString());
            req.setTemplate(template);

            // 返回的resp是一个SendEmailResponse的实例，与请求对象对应
            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 HALFPRICEPROMOTION_CN_ID = 128582L;
    private final static Long HALFPRICEPROMOTION_EN_ID = 128583L;

    public static void halfPricePromotion(Account account, String senderAddress, int type) {
        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();
//            if (type == 1) {
//                subject = "Upcoming System Upgrade for AiDA 3.0";
//                template.setTemplateID(UPGRADE_NOTIFICATION_ID);
//            }else {
//                subject = "即将到来的AiDA 3.0系统升级";
//                template.setTemplateID(UPGRADE_NOTIFICATION_ID_CHINESE);
//            }
            if (type == 1) {
                subject = "AiDA workshop - Win a trip to Hong Kong！";
                template.setTemplateID(HALFPRICEPROMOTION_EN_ID);
            } else {
                subject = "AiDA workshop - 赢取香港之旅";
                template.setTemplateID(HALFPRICEPROMOTION_CN_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 final static Long SYSTEM_UPGRADE_CN_ID = 131743L;
    private final static Long SYSTEM_UPGRADE_EN_ID = 131744L;
    public static void temporaryUpgrade(Account account, String senderAddress, int type) {
        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();
            if (type == 1) {
                subject = "AiDA system upgrade completed";
                template.setTemplateID(SYSTEM_UPGRADE_EN_ID);
            }else {
                subject = "AiDA系统升级完成";
                template.setTemplateID(SYSTEM_UPGRADE_CN_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 final static Long CANCEL_MERCHANT_EN = 130720L;
    //    private final static Long NEW_MERCHANT_EN = 130721L;
//    private final static Long NEW_USER_EN = 130722L;
//    private final static Long NEW_USER_CN = 130723L;
    private final static Long NEW_MERCHANT_EN = 140335L;
    //    private final static Long NEW_MERCHANT_EN = 135190L;
//    private final static Long NEW_USER_EN = 135189L;
//    private final static Long NEW_USER_CN = 135186L;
    private final static Long NEW_USER_EN = 140316L;
    private final static Long NEW_USER_CN = 140317L;
    private final static Long RENEWAL_MERCHANT_EN = 130724L;
    private final static Long RENEWAL_USER_EN = 130725L;
    private final static Long RENEWAL_USER_CN = 130726L;
    private final static Long RENEWAL_REMINDER_USER_EN = 130727L;
    private final static Long RENEWAL_REMINDER_USER_CN = 130728L;
    private final static Long PAYMENT_FAILED_NEW_MERCHANT_EN = 131230L;
    private final static Long PAYMENT_FAILED_RENEWAL_MERCHANT_EN = 131225L;
    private final static Long PAYMENT_FAILED_RENEWAL_USER_EN = 131563L;
    private final static Long PAYMENT_FAILED_RENEWAL_USER_CN = 131564L;

    public static boolean subscriptionEmailReminder(String type, SubscriptionEmailParamsDTO subscriptionEmailParamsDTO, String language, String receiverAddress) {
        try {
            String merchantEmail = "kimwong@code-create.com.hk";
            String developer = "xupei3360@163.com";
            String[] receiverEmail = {/*merchantEmail,*/ developer};
            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 user = new SendEmailRequest();
            user.setFromEmailAddress(SEND_ADDRESS);
            user.setDestination(new String[]{receiverAddress});
            SendEmailRequest merchant = new SendEmailRequest();
            merchant.setFromEmailAddress(SEND_ADDRESS);
            merchant.setDestination(receiverEmail);
            Template templateUser = new Template();
            Template templateMerchant = new Template();
            switch (type) {
                case "cancel":
                    merchant.setSubject("[Code-Create] Subscription Cancelled");
                    templateMerchant.setTemplateID(CANCEL_MERCHANT_EN);
                    break;
                case "fail_new":
                    merchant.setSubject("[Code-Create] Payment Failed : New Order (" + subscriptionEmailParamsDTO.getOrderId() + ")");
                    templateMerchant.setTemplateID(PAYMENT_FAILED_NEW_MERCHANT_EN);
                    break;
                case "fail_renewal":
                    merchant.setSubject("[Code-Create] Payment Failed : Renewal Order (" + subscriptionEmailParamsDTO.getOrderId() + ")");
                    templateMerchant.setTemplateID(PAYMENT_FAILED_RENEWAL_MERCHANT_EN);
                    // todo to user
                    if (language.equals("ENGLISH")) {
                        user.setSubject("[Code-Create] Payment Failed : Renewal Order (" + subscriptionEmailParamsDTO.getOrderId() + ")");
                        templateUser.setTemplateID(PAYMENT_FAILED_RENEWAL_USER_EN);
                    } else {
                        user.setSubject("[Code-Create] 自动续费失败 (" + subscriptionEmailParamsDTO.getOrderId() + ")");
                        templateUser.setTemplateID(PAYMENT_FAILED_RENEWAL_USER_CN);
                    }
                    break;
                case "new":
                    merchant.setSubject("[Code-Create] New Order(" + subscriptionEmailParamsDTO.getOrderId() + ")");
                    templateMerchant.setTemplateID(NEW_MERCHANT_EN);
                    if (language.equals("ENGLISH")) {
                        user.setSubject("[Code-Create] You have successfully subscribed to AiDA");
                        templateUser.setTemplateID(NEW_USER_EN);
                    } else {
                        user.setSubject("[Code-Create] 您已成功订阅AiDA");
                        templateUser.setTemplateID(NEW_USER_CN);
                    }
                    break;
                case "renewal":
                    merchant.setSubject("[Code-Create] New subscription renewal order (" + subscriptionEmailParamsDTO.getOrderId() + ")");
                    templateMerchant.setTemplateID(RENEWAL_MERCHANT_EN);
                    if (language.equals("ENGLISH")) {
                        user.setSubject("[Code-Create] AiDA Renewal Successful");
                        templateUser.setTemplateID(RENEWAL_USER_EN);
                    } else {
                        user.setSubject("[Code-Create] AiDA续订成功");
                        templateUser.setTemplateID(RENEWAL_USER_CN);
                    }
                    break;
                case "reminder_subscriber":
                    if (language.equals("ENGLISH")) {
                        user.setSubject("[Code-Create] AiDA Subscription Renewal Reminder");
                        templateUser.setTemplateID(156072L);
                    } else if (language.equals("CHINESE")){
                        user.setSubject("[Code-Create] AiDA续订提醒");
                        templateUser.setTemplateID(156073L);
                    } else {
                        user.setSubject("[Code-Create] AiDA續訂提醒");
                        templateUser.setTemplateID(156074L);
                    }
                    break;
                case "reminder_expire":
                    if (language.equals("ENGLISH")) {
                        user.setSubject("[Code-Create] AiDA account is about to expire");
                        templateUser.setTemplateID(156749L);
                    } else if (language.equals("CHINESE")){
                        user.setSubject("[Code-Create] 您的AiDA账号即将到期");
                        templateUser.setTemplateID(156750L);
                    } else {
                        user.setSubject("[Code-Create] 您的AiDA帳號即將到期");
                        templateUser.setTemplateID(156751L);
                    }
                    break;
                case "reminder_trial":
                    if (language.equals("ENGLISH")) {
                        user.setSubject("[Code-Create] AiDA — Free Trial Ending");
                        templateUser.setTemplateID(156075L);
                    } else if (language.equals("CHINESE")){
                        user.setSubject("[Code-Create] AiDA — 免费试用结束提醒");
                        templateUser.setTemplateID(156076L);
                    } else {
                        user.setSubject("[Code-Create] AiDA — 免費試用結束提醒");
                        templateUser.setTemplateID(156077L);
                    }
                    break;

                default:
                    log.error("unknown subscription email type");
                    return false;
//                    throw new BusinessException("unknown subscription email type");
            }

            templateUser.setTemplateData(JSON.toJSONString(subscriptionEmailParamsDTO));
            user.setTemplate(templateUser);

            subscriptionEmailParamsDTO.setEndDate("When cancelled");
            templateMerchant.setTemplateData(JSON.toJSONString(subscriptionEmailParamsDTO));
            merchant.setTemplate(templateMerchant);

            if (!type.equals("cancel") && !type.equals("fail_new")) {
                // 返回的resp是一个SendEmailResponse的实例，与请求对象对应
                SendEmailResponse respUser = client.SendEmail(user);
                log.info("邮件主题：{}，发送结果toUser###{}", user.getSubject(), SendEmailResponse.toJsonString(respUser));
            }
            if (!type.startsWith("reminder")) {
                SendEmailResponse respMerchant = client.SendEmail(merchant);
                log.info("邮件主题：{}，发送结果toMerchant###{}", merchant.getSubject(), SendEmailResponse.toJsonString(respMerchant));
            }
            return true;
        } catch (TencentCloudSDKException e) {
            log.info("邮件发送失败###{}", e.toString());
            return false;
//            throw new BusinessException("failed.to.send.mail");
        }
    }

    private final static Long NEW_REGISTRATION = 132123L;
    private final static Long AFFILIATE_ACCEPTED = 132124L;
    private final static Long AFFILIATE_REFUSED = 132125L;
    private final static Long AFFILIATE_MONTHLY_SUMMARY = 132126L;

    public static void affiliateEmailReminder(String[] receiverAddress, AffiliateEmailParamsDTO paramsDTO, String type) {
        try {
            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(receiverAddress);
            Template template = new Template();
            switch (type) {
                case "new":
                    req.setSubject("New Affiliate Registration");
                    template.setTemplateID(NEW_REGISTRATION);
                    break;
                case "accepted":
                    req.setSubject("Affiliate Application Accepted");
                    template.setTemplateID(AFFILIATE_ACCEPTED);
                    break;
                case "refused":
                    req.setSubject("Affiliate Application Refused");
                    template.setTemplateID(AFFILIATE_REFUSED);
                    break;
                case "summary":
                    req.setSubject("Your Monthly AffiliateWP Summary for AiDA");
                    template.setTemplateID(AFFILIATE_MONTHLY_SUMMARY);
                    break;
            }

            template.setTemplateData(JSON.toJSONString(paramsDTO));
            req.setTemplate(template);

            // 返回的resp是一个SendEmailResponse的实例，与请求对象对应
            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 CREDITS_PURCHASE_MERCHANT = 133275L;

    public static void creditsPurchaseReminder(String username, String quantity, String amount) {
        try {
            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);
            String merchantEmail = "kimwong@code-create.com.hk";
            String developerEmail = "xupei@code-create.com.hk";
            req.setDestination(new String[]{/*merchantEmail,*/ developerEmail});
            Template template = new Template();
            req.setSubject("New Credit Purchase Order");
            template.setTemplateID(CREDITS_PURCHASE_MERCHANT);
            JSONObject jsonObject = new JSONObject();
            // 设置试用订单相关数据
            jsonObject.put("username", username);
            jsonObject.put("quantity", quantity);
            jsonObject.put("totalFee", amount);

            template.setTemplateData(JSON.toJSONString(jsonObject));
            req.setTemplate(template);

            // 返回的resp是一个SendEmailResponse的实例，与请求对象对应
            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 COMMON_EXCEPTION_REMINDER = 135279L;
    public static void commonExceptionReminder(String functionName, String[] destination) {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 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(destination);
            Template template = new Template();
            req.setSubject("AiDA发生异常，请及时处理");
            template.setTemplateID(COMMON_EXCEPTION_REMINDER);
            JSONObject param = new JSONObject();
            param.put("function", functionName);

            // 邮件内容 {{function}}处理异常，请及时查看
            template.setTemplateData(param.toJSONString());
            req.setTemplate(template);

            // 返回的resp是一个SendEmailResponse的实例，与请求对象对应
            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 CN_2025_618 = 141425L;
    private final static Long EN_2025_618 = 141424L;
    public static void send618PromotionEmailTemp(String receiver, String language){
        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();
            req.setFromEmailAddress(CODE_CREATE_SEND_ADDRESS);
            req.setDestination(new String[]{receiver});

            // 根据邮件类型设置不同的主题和模板
            String subject = "";
            Template template = new Template();
//            if (type == 1) {
//                subject = "Upcoming System Upgrade for AiDA 3.0";
//                template.setTemplateID(UPGRADE_NOTIFICATION_ID);
//            }else {
//                subject = "即将到来的AiDA 3.0系统升级";
//                template.setTemplateID(UPGRADE_NOTIFICATION_ID_CHINESE);
//            }
            if (language.equals("ENGLISH")) {
                subject = "Welcome back ！Subscribe AiDA with the discount code to enjoy 50% OFF!";
                template.setTemplateID(EN_2025_618);
            }else {
                subject = "设计时速狂飙！AiDA 618半价让灵感永不限流！";
                template.setTemplateID(CN_2025_618);
            }

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

            // 发送邮件
            SendEmailResponse resp = client.SendEmail(req);
            log.info("邮件发送成功，收件人地址：{}", receiver);
            log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.info(receiver);
            log.error("邮件发送失败###{},收件人地址：{}", e.toString(), receiver);

        }

    }

}
