package com.qqchen.deploy.backend.workflow.delegate;

import com.qqchen.deploy.backend.notification.dto.SendNotificationRequest;
import com.qqchen.deploy.backend.notification.service.INotificationService;
import com.qqchen.deploy.backend.workflow.dto.inputmapping.NotificationInputMapping;
import com.qqchen.deploy.backend.workflow.dto.outputs.NotificationOutputs;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Map;

/**
 * 通知任务委派
 *
 * @author qqchen
 * @since 2025-10-22
 */
@Slf4j
@Component("notificationDelegate")
public class NotificationNodeDelegate extends BaseNodeDelegate<NotificationInputMapping, NotificationOutputs> {

    @Resource
    private INotificationService notificationService;

    @Override
    protected void executeInternal(DelegateExecution execution, Map<String, Object> configs, NotificationInputMapping input) {
        // 1. 参数校验
        if (input.getChannelId() == null || input.getNotificationTemplateId() == null) {
            logWarn(String.format("Notification delegate parameter verification failed - channelId: %s, templateId: %s", input.getChannelId(), input.getNotificationTemplateId()));
            return;
        }

        // 2. 构建SendNotificationRequest
        SendNotificationRequest request = new SendNotificationRequest();
        request.setChannelId(input.getChannelId());
        request.setNotificationTemplateId(input.getNotificationTemplateId());
        request.setTemplateParams(execution.getVariables());

        // 3. 发送通知（NotificationService会自动根据渠道类型创建请求对象）
        notificationService.send(request);

        log.info("工作流通知发送成功 - 渠道ID: {}, 模板ID: {}", input.getChannelId(), input.getNotificationTemplateId());
    }
}
