package com.srs.flowable.listener.disciplinary;

import com.srs.common.utils.WeChatUtil;
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;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 为“学院违纪处理委员会”多实例任务准备数据。 知无涯
 * 1. 设置 'userList' 变量供多实例节点本身消费。
 * 2. 设置 'nextTaskNameForMessage' 变量供下游消息监听器消费。
 * 3. 发送企业微信通知。
 */
@Component("xywjclwyhListener")
@Slf4j
public class XYWJCLWYHListener implements ExecutionListener {

    @Autowired
    private DisciplinaryMapper disciplinaryMapper;

    @Autowired
    private WeChatUtil weChatUtil;

    @Override
    public void notify(DelegateExecution execution) {
        log.info("流程实例 [{}]: 触发 XYWJCLWYHListener，为'委员会'节点准备数据...", execution.getProcessInstanceId());

        List<Long> userIdList = disciplinaryMapper.getApprovalByRoleKey("xywjclwyh");
        if (CollectionUtils.isEmpty(userIdList)) {
            log.error("角色 'xywjclwyh' 未配置或未找到任何有效用户，流程无法继续。");
            throw new RuntimeException("学院违纪处理委员会审批人员未设置");
        }

        // 步骤 1: 设置 'userList' 变量，供多实例UserTask节点消费
        execution.setVariable("userList", userIdList);
        log.info("已将'委员会'的 {} 位成员ID存入 'userList' 流程变量。", userIdList.size());

        // 步骤 2: 主动获取并设置下一个节点的名称，供 GenericMessageListener 消费
        FlowElement nextElement = getNextFlowElement(execution);
        if (nextElement != null) {
            execution.setVariable("nextTaskNameForMessage", nextElement.getName());
            log.info("已将下一个任务的名称 '{}' 存入流程变量 'nextTaskNameForMessage'。", nextElement.getName());
        }

        // 步骤 3: 发送企业微信通知
        sendWeChatNotification(userIdList, execution.getProcessInstanceId());
    }

    private void sendWeChatNotification(List<Long> userIdList, String processInstanceId) {
        try {
            List<String> userNameList = disciplinaryMapper.getUserNamesByUserIdList(userIdList);
            if (CollectionUtils.isEmpty(userNameList)) {
                log.warn("流程实例 [{}]: 角色'xywjclwyh'存在审批人ID，但无人配置企微账号。", processInstanceId);
                return;
            }
            String toUser = String.join("|", userNameList);
            String content = "您有一条新的学生违纪审批任务待处理，<a href='https://zhxg.gxsdxy.cn/wab/#/pages/Approval/index'>请点击前往处理</a>。";
            weChatUtil.sendTextMessage(toUser, content);
            log.info("流程实例 [{}]: 已成功向'委员会'发送企微通知。", processInstanceId);
        } catch (Exception e) {
            log.error("流程实例 [{}]: 发送企微通知时出现异常: {}", processInstanceId, e.getMessage(), e);
        }
    }

    private FlowElement getNextFlowElement(DelegateExecution execution) {
        if (execution.getCurrentFlowElement() instanceof SequenceFlow) {
            return ((SequenceFlow) execution.getCurrentFlowElement()).getTargetFlowElement();
        }
        return null;
    }
}
