package com.yushu.web.controller.system;

import com.yushu.common.annotation.Log;
import com.yushu.common.core.controller.BaseController;
import com.yushu.common.core.domain.AjaxResult;
import com.yushu.common.enums.BusinessType;
import com.yushu.system.service.ISysMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 邮件发送Controller
 * 
 * @author yushu
 * @date 2024-12-13
 */
@RestController
@RequestMapping("/system/mail/send")
public class SysMailSendController extends BaseController {

    @Autowired
    private ISysMailService sysMailService;

    /**
     * 发送简单邮件
     */
    @PreAuthorize("@ss.hasPermi('system:mail:config:test')")
    @Log(title = "邮件发送", businessType = BusinessType.OTHER)
    @PostMapping
    public AjaxResult send(@RequestBody Map<String, Object> params) {
        Long configId = params.get("configId") != null ? Long.valueOf(params.get("configId").toString()) : null;
        String to = (String) params.get("to");
        String cc = (String) params.get("cc");
        String bcc = (String) params.get("bcc");
        String subject = (String) params.get("subject");
        String content = (String) params.get("content");
        Boolean isHtml = params.get("isHtml") != null ? (Boolean) params.get("isHtml") : true;

        if (to == null || to.isEmpty()) {
            return error("收件人不能为空");
        }
        if (subject == null || subject.isEmpty()) {
            return error("邮件主题不能为空");
        }

        boolean result = sysMailService.sendMail(configId, to, cc, bcc, subject, content, isHtml);
        return result ? success("邮件发送成功") : error("邮件发送失败");
    }

    /**
     * 使用模板发送邮件
     */
    @PreAuthorize("@ss.hasPermi('system:mail:config:test')")
    @Log(title = "邮件发送", businessType = BusinessType.OTHER)
    @PostMapping("/template")
    public AjaxResult sendByTemplate(@RequestBody Map<String, Object> params) {
        Long configId = params.get("configId") != null ? Long.valueOf(params.get("configId").toString()) : null;
        String templateCode = (String) params.get("templateCode");
        String to = (String) params.get("to");
        @SuppressWarnings("unchecked")
        Map<String, Object> variables = (Map<String, Object>) params.get("variables");

        if (templateCode == null || templateCode.isEmpty()) {
            return error("模板代码不能为空");
        }
        if (to == null || to.isEmpty()) {
            return error("收件人不能为空");
        }

        boolean result = sysMailService.sendMailByTemplate(configId, templateCode, to, variables);
        return result ? success("邮件发送成功") : error("邮件发送失败");
    }
}
