package com.srs.flowable.listener.disciplinary;

import com.srs.common.utils.WeChatUtil;
import com.srs.common.utils.spring.SpringUtils;
import com.srs.flowable.mapper.DisciplinaryMapper;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;
import java.util.List;

/**
 * 执行监听器：在“校领导审批”节点开始时，向校领导发送企业微信通知。 知无涯
 * (简化版：因为流程能到达此节点，即表示前序节点已全票通过)
 */
@Component
@Slf4j
public class SchoolLeaderApprovalListener implements ExecutionListener {

    @Override
    public void notify(DelegateExecution delegateExecution) {
        log.info("流程实例 [{}]: 已进入校领导审批节点，准备发送通知。", delegateExecution.getProcessInstanceId());

        try {
            DisciplinaryMapper disciplinaryMapper = SpringUtils.getBean(DisciplinaryMapper.class);

            // 1. 【核心】定义“校领导”这个角色的 role_key
            final String LEADER_ROLE_KEY = "xldsp";

            // 2. 根据角色Key查询用户ID列表
            List<Long> userIdList = disciplinaryMapper.getApprovalByRoleKey(LEADER_ROLE_KEY);

            if (userIdList == null || userIdList.isEmpty()) {
                log.warn("根据角色Key '{}' 未找到任何校领导用户，无法发送通知。", LEADER_ROLE_KEY);
                return;
            }

            // 3. 批量查询 userName 并发送通知
            List<String> userNameList = disciplinaryMapper.getUserNamesByUserIdList(userIdList);
            if (!userNameList.isEmpty()) {
                String toUser = String.join("|", userNameList);
                WeChatUtil weChatUtil = SpringUtils.getBean(WeChatUtil.class);
                String content = "校领导您有一条新的学生违纪审批任务待处理，<a href='http://zhxg.gxsdxy.cn/web/#/pages/Approval/index'>请点击前往处理</a>。";

                weChatUtil.sendTextMessage(toUser, content);
                log.info("已成功向校领导 (角色: {}) 发送通知。接收人: {}", LEADER_ROLE_KEY, toUser);
            } else {
                log.warn("角色 '{}' 中找到了 {} 个用户，但无人配置企业微信账号，未发送任何通知。", LEADER_ROLE_KEY, userIdList.size());
            }

        } catch (Exception e) {
            log.error("向校领导发送企业微信通知时出现异常。流程将继续。错误详情: {}", e.getMessage(), e);
        }
    }
}