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.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;

/**
 * 学工领导审批监听器
 * 使用 @Component + @Autowired，兼容 Flowable Delegate Expression
 */
@Component("xgldshListener")
@Slf4j
public class XGLDSHListener implements ExecutionListener {

    @Autowired
    private DisciplinaryMapper disciplinaryMapper;

    @Autowired
    private WeChatUtil weChatUtil;

    @Override
    public void notify(DelegateExecution execution) {

        final String TARGET_ROLE_KEY = "xgldsp";
        String processInstanceId = execution.getProcessInstanceId();

        log.info("流程实例 [{}]: 触发 XGLDSHListener，为角色 '{}' 节点准备数据...", processInstanceId, TARGET_ROLE_KEY);

        // 查询角色下审批人
        List<Long> userIdList = disciplinaryMapper.getApprovalByRoleKey(TARGET_ROLE_KEY);
        if (CollectionUtils.isEmpty(userIdList)) {
            log.error("流程实例 [{}]: 角色 '{}' 未配置审批人员", processInstanceId, TARGET_ROLE_KEY);
            throw new RuntimeException("学工领导审批人员未设置");
        }

        // 发送企微通知
        sendWeChatNotification(userIdList, processInstanceId, TARGET_ROLE_KEY);
    }

    private void sendWeChatNotification(List<Long> userIdList, String processInstanceId, String roleKey) {
        try {
            List<String> userNameList = disciplinaryMapper.getUserNamesByUserIdList(userIdList);
            if (CollectionUtils.isEmpty(userNameList)) {
                log.warn("流程实例 [{}]: 角色 '{}' 审批人存在但无人配置企微账号", processInstanceId, roleKey);
                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, roleKey, toUser);
        } catch (Exception e) {
            log.error("流程实例 [{}]: 向角色 '{}' 发送企微通知异常", processInstanceId, roleKey, e);
        }
    }
}
