package com.gxwebsoft.common.system.util;

import cn.hutool.core.date.DateUtil;
import com.gxwebsoft.common.system.service.EmailRecordService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 邮件模板工具类
 * 统一管理邮件模板和发送逻辑
 *
 * @author WebSoft
 * @since 2024-08-28
 */
@Component
public class EmailTemplateUtil {

    @Resource
    private EmailRecordService emailRecordService;

    /**
     * 发送注册成功邮件
     *
     * @param username 用户名
     * @param phone    手机号
     * @param password 密码
     * @param email    邮箱
     * @param tenantId 租户ID
     */
    public void sendRegisterSuccessEmail(String username, String phone, String password, String email, Integer tenantId) {
        try {
            String title = "恭喜！您的账号已注册成功";
            Map<String, Object> data = new HashMap<>();
            data.put("username", username);
            data.put("phone", phone);
            data.put("password", password);
            if (email != null && !email.trim().isEmpty()) {
                data.put("email", email);
            }

            emailRecordService.sendHtmlEmail(title, "register-success.html", data, new String[]{email});
        } catch (Exception e) {
            // 如果HTML邮件发送失败，降级为文本邮件
            String content = "恭喜！您的WebSoft账号已注册成功\r\n用户名：" + username + "\r\n手机号码：" + phone + "\r\n密码：" + password;
            emailRecordService.sendEmail("恭喜！您的WebSoft账号已注册成功", content, email, tenantId);
        }
    }

    /**
     * 发送密码重置邮件
     *
     * @param username    用户名
     * @param phone       手机号
     * @param newPassword 新密码
     * @param email       邮箱
     * @param tenantId    租户ID
     */
    public void sendPasswordResetEmail(String username, String phone, String newPassword, String email, Integer tenantId) {
        try {
            String title = "WebSoft密码重置通知";
            Map<String, Object> data = new HashMap<>();
            data.put("username", username);
            data.put("phone", phone);
            data.put("resetTime", DateUtil.now());
            if (newPassword != null && !newPassword.trim().isEmpty()) {
                data.put("newPassword", newPassword);
            }

            emailRecordService.sendHtmlEmail(title, "password-reset.html", data, new String[]{email});
        } catch (Exception e) {
            // 如果HTML邮件发送失败，降级为文本邮件
            String content = "您的WebSoft账号密码已重置\r\n用户名：" + username + "\r\n手机号码：" + phone + "\r\n新密码：" + newPassword + "\r\n重置时间：" + DateUtil.now();
            emailRecordService.sendEmail("WebSoft密码重置通知", content, email, tenantId);
        }
    }

    /**
     * 发送通用通知邮件
     *
     * @param title       邮件标题
     * @param content     邮件内容
     * @param email       收件人邮箱
     * @param tenantId    租户ID
     * @param greeting    问候语（可选）
     * @param infoMessage 提示信息（可选）
     * @param actionUrl   操作链接（可选）
     * @param actionText  操作按钮文字（可选）
     */
    public void sendNotificationEmail(String title, String content, String email, Integer tenantId,
                                    String greeting, String infoMessage, String actionUrl, String actionText) {
        try {
            Map<String, Object> data = new HashMap<>();
            data.put("title", title);
            data.put("content", content);
            data.put("sendTime", DateUtil.now());

            if (greeting != null && !greeting.trim().isEmpty()) {
                data.put("greeting", greeting);
            }
            if (infoMessage != null && !infoMessage.trim().isEmpty()) {
                data.put("infoMessage", infoMessage);
            }
            if (actionUrl != null && !actionUrl.trim().isEmpty()) {
                data.put("actionUrl", actionUrl);
            }
            if (actionText != null && !actionText.trim().isEmpty()) {
                data.put("actionText", actionText);
            }

            emailRecordService.sendHtmlEmail(title, "notification.html", data, new String[]{email});
        } catch (Exception e) {
            // 如果HTML邮件发送失败，降级为文本邮件
            emailRecordService.sendEmail(title, content, email, tenantId);
        }
    }

    /**
     * 发送简单通知邮件
     *
     * @param title    邮件标题
     * @param content  邮件内容
     * @param email    收件人邮箱
     * @param tenantId 租户ID
     */
    public void sendNotificationEmail(String title, String content, String email, Integer tenantId) {
        sendNotificationEmail(title, content, email, tenantId, null, null, null, null);
    }

    /**
     * 发送带操作按钮的通知邮件
     *
     * @param title      邮件标题
     * @param content    邮件内容
     * @param email      收件人邮箱
     * @param tenantId   租户ID
     * @param actionUrl  操作链接
     * @param actionText 操作按钮文字
     */
    public void sendNotificationEmailWithAction(String title, String content, String email, Integer tenantId,
                                               String actionUrl, String actionText) {
        sendNotificationEmail(title, content, email, tenantId, null, null, actionUrl, actionText);
    }

    /**
     * 发送账户安全提醒邮件
     *
     * @param username 用户名
     * @param phone    手机号
     * @param email    邮箱
     * @param tenantId 租户ID
     * @param event    安全事件描述
     */
    public void sendSecurityAlertEmail(String username, String phone, String email, Integer tenantId, String event) {
        String title = "WebSoft账户安全提醒";
        String content = "您的账户发生了以下安全事件：" + event + "。如果这不是您本人的操作，请立即联系客服并修改密码。";
        String infoMessage = "为了保障您的账户安全，建议您定期修改密码并开启双重验证。";
        String actionUrl = "https://websoft.top/security";
        String actionText = "查看安全设置";

        sendNotificationEmail(title, content, email, tenantId, "尊敬的用户", infoMessage, actionUrl, actionText);
    }

    /**
     * 发送系统维护通知邮件
     *
     * @param email         收件人邮箱
     * @param tenantId      租户ID
     * @param maintenanceTime 维护时间
     * @param duration      维护时长
     */
    public void sendMaintenanceNotificationEmail(String email, Integer tenantId, String maintenanceTime, String duration) {
        String title = "WebSoft系统维护通知";
        String content = "为了提供更好的服务，我们将在 " + maintenanceTime + " 进行系统维护，预计维护时长：" + duration + "。维护期间可能会影响系统的正常使用，给您带来的不便敬请谅解。";
        String infoMessage = "维护完成后，系统将自动恢复正常服务。";

        sendNotificationEmail(title, content, email, tenantId, "尊敬的用户", infoMessage, null, null);
    }

    /**
     * 发送订单状态变更邮件
     *
     * @param username   用户名
     * @param orderNo    订单号
     * @param status     订单状态
     * @param email      邮箱
     * @param tenantId   租户ID
     */
    public void sendOrderStatusEmail(String username, String orderNo, String status, String email, Integer tenantId) {
        String title = "WebSoft订单状态更新";
        String content = "您的订单 " + orderNo + " 状态已更新为：" + status + "。";
        String actionUrl = "https://websoft.top/orders/" + orderNo;
        String actionText = "查看订单详情";

        sendNotificationEmailWithAction(title, content, email, tenantId, actionUrl, actionText);
    }

    /**
     * 发送邮箱验证码邮件
     *
     * @param email    收件人邮箱
     * @param code     验证码
     * @param tenantId 租户ID
     */
    public void sendCaptchaEmail(String email, String code, Integer tenantId) {
        if (email == null || email.trim().isEmpty()) {
            return;
        }
        String title = "邮箱验证码";
        String content = "您正在绑定或修改邮箱，验证码为：" + code + "，5 分钟内有效，请勿泄露给他人。如非本人操作，请忽略此邮件。";
        sendNotificationEmail(title, content, email, tenantId, "尊敬的用户", "验证码用于确认邮箱真实性，请勿转发给他人。", null, null);
    }
}
