package com.srs.flowable.listener.disciplinary;
import com.srs.common.utils.SecurityUtils;
import com.srs.common.utils.WeChatUtil;
import com.srs.comprehensive.domain.CphMsg;
import com.srs.comprehensive.service.ICphMsgService;
import com.srs.flowable.mapper.DisciplinaryMapper;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.SequenceFlow;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 在流程结果返回给发起人时， 知无涯
 * 负责发送企业微信和内部消息两种通知。
 */
@Component("initiatorNotificationListener") // 使用一个全新的、明确的Bean名称
@Slf4j
public class InitiatorNotificationListener implements ExecutionListener {

    @Autowired
    private DisciplinaryMapper disciplinaryMapper;

    @Autowired
    private ICphMsgService cphMsgService;

    @Autowired(required = false) // 允许WeChatUtil为null，增加灵活性
    private WeChatUtil weChatUtil;

    @Override
    public void notify(DelegateExecution execution) {
        log.info("流程实例 [{}]: 触发 InitiatorNotificationListener，准备向发起人发送整合通知...", execution.getProcessInstanceId());

        // --- 1. 获取核心数据：发起人ID ---
        Object initiatorObj = execution.getVariable("INITIATOR");
        if (initiatorObj == null) {
            log.error("在流程实例 [{}] 中未找到发起人(INITIATOR)变量，无法发送任何通知。", execution.getProcessInstanceId());
            return;
        }

        Long initiatorUserId;
        try {
            initiatorUserId = Long.parseLong(initiatorObj.toString());
        } catch (NumberFormatException e) {
            log.error("发起人(INITIATOR)变量 '{}' 无法转换为Long类型。", initiatorObj, e);
            return;
        }

        // --- 2. 准备通知内容 (解决taskName为空的问题) ---
        String nextTaskName = getNextTaskName(execution);
        String weChatMessage = "您提交的学生违纪处分申请已有最终处理结果，<a href='https://zhxg.gxsdxy.cn/wab/#/pages/Approval/index'>请点击前往处理</a>。";
        String internalMessageText = "您有一条新的【" + nextTaskName + "】待办任务需要处理。";
        String hiddenIdentifier = String.format("<span id='flow-identifier' data-proc-inst-id='%s' data-activity-id='%s' style='display:none;'></span>",
                execution.getProcessInstanceId(),
                ((SequenceFlow) execution.getCurrentFlowElement()).getTargetRef());
        String internalMessageContent = internalMessageText + "<a href='https://zhxg.gxsdxy.cn/wab/#/pages/Approval/index'>请点击前往处理</a>。" + hiddenIdentifier;

        // --- 3. 发送企业微信通知 ---
        sendWeChatNotification(initiatorUserId, weChatMessage);

        // --- 4. 创建内部消息 ---
        createInternalMessage(initiatorUserId, internalMessageContent, execution);
    }

    /**
     * 发送企业微信通知
     */
    private void sendWeChatNotification(Long userId, String content) {
        if (weChatUtil == null) { // 防御性编程
            log.warn("WeChatUtil未配置，跳过发送企业微信。");
            return;
        }
        try {
            String userName = disciplinaryMapper.getUserNameByUserId(userId);
            if (userName != null && !userName.isEmpty()) {
                weChatUtil.sendTextMessage(userName, content);
                log.info("已成功向流程发起人 (userId:{}) 发送企业微信通知。", userId);
            } else {
                log.warn("找到了发起人(userId:{})，但其企微账号为空，未发送企微通知。", userId);
            }
        } catch (Exception e) {
            log.error("向流程发起人发送企业微信通知时异常: {}", e.getMessage(), e);
        }
    }

    /**
     * 创建内部消息
     */
    private void createInternalMessage(Long receiverId, String content, DelegateExecution execution) {
        try {
            CphMsg cphMsg = new CphMsg();
            cphMsg.setReceiver(receiverId);
            cphMsg.setContent(content);
            // 安全地获取发送人，提供默认值
            cphMsg.setSender(SecurityUtils.getUserId() != null ? SecurityUtils.getUserId() : 1L);

            cphMsgService.insertCphMsg(cphMsg);
            log.info("已成功为流程发起人 (userId:{}) 创建内部消息。", receiverId);
        } catch (Exception e) {
            log.error("为流程发起人创建内部消息时异常: {}", e.getMessage(), e);
        }
    }

    /**
     * 安全地获取线上监听器下一个目标节点的名称
     */
    private String getNextTaskName(DelegateExecution execution) {
        try {
            SequenceFlow sequenceFlow = (SequenceFlow) execution.getCurrentFlowElement();
            FlowElement targetElement = sequenceFlow.getTargetFlowElement();
            if (targetElement != null) {
                return targetElement.getName();
            }
        } catch (Exception e) {
            log.warn("获取下一个任务名称时出错: {}", e.getMessage());
        }
        return "结果接收";
    }
}
