package cn.stylefeng.workflow.instance.modular.message.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.roses.kernel.email.api.MailSenderApi;
import cn.stylefeng.roses.kernel.email.api.pojo.SendMailParam;
import cn.stylefeng.roses.kernel.sys.api.SysUserServiceApi;
import cn.stylefeng.roses.kernel.sys.api.pojo.user.UserInfoDetailDTO;
import cn.stylefeng.workflow.api.entity.task.RuTask;
import cn.stylefeng.workflow.api.pojo.InstanceContext;
import cn.stylefeng.workflow.api.pojo.config.node.notice.NodeNotice;
import cn.stylefeng.workflow.instance.modular.message.TaskMessageApi;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class EmailMessageImpl implements TaskMessageApi {

    @Resource
    private SysUserServiceApi sysUserServiceApi;

    @Resource
    private MailSenderApi mailSenderApi;

    @Override
    public boolean validateSendFlag(NodeNotice nodeNotice) {
        if (nodeNotice == null) {
            return false;
        }
        return nodeNotice.getEmailMessage();
    }

    @Override
    public void sendMessage(Long userId, RuTask ruTask, NodeNotice nodeNotice, InstanceContext instanceContext) {

        UserInfoDetailDTO userDetail = sysUserServiceApi.getUserDetail(userId);
        String email = userDetail.getEmail();

        if (ObjectUtil.isEmpty(email)) {
            return;
        }

        String title = "待办任务提醒：" + instanceContext.getRuntimeInstance().getInstanceTitle();
        String content = title + "，请尽快处理！\n" + "流程发起时间：" + DateUtil.formatDateTime(instanceContext.getRuntimeInstance().getCreateTime()) + "\n";

        try {
            SendMailParam sendMailParam = new SendMailParam();
            sendMailParam.setTitle(title);
            sendMailParam.setContent(content);
            sendMailParam.setTos(ListUtil.toList(email));
            mailSenderApi.sendMail(sendMailParam);
        } catch (Exception e) {
            log.error("发送邮件失败！", e);
        }
    }

}
