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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class XGLDSHListener implements ExecutionListener {


    @Autowired
    private WeChatUtil weChatUtil;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        DisciplinaryMapper disciplinaryMapper = SpringUtils.getBean(DisciplinaryMapper.class);

        // 固定角色 Key
        final String TARGET_ROLE_KEY = "xgldsp";

        // 步骤 1: 查询角色下的所有审批人 userId
        List<Long> userIdList = disciplinaryMapper.getApprovalByRoleKey(TARGET_ROLE_KEY);

        if (userIdList == null || userIdList.isEmpty()) {
            throw new RuntimeException("未找到角色 '" + TARGET_ROLE_KEY + "' 的审批人员，无法发送通知。");
        }

        try {
            // 步骤 2: 查询 userName 列表
            List<String> userNameList = disciplinaryMapper.getUserNamesByUserIdList(userIdList);

            if (userNameList != null && !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>。";

                // 步骤 3: 发送企业微信通知
                weChatUtil.sendTextMessage(toUser, content);
                log.info("已成功向角色 '{}' 的成员发送企业微信审批通知。接收人: {}", TARGET_ROLE_KEY, toUser);

            } else {
                log.warn("角色 '{}' 下找到 {} 个用户，但无对应的企业微信账号，无法发送通知。", TARGET_ROLE_KEY, userIdList.size());
            }

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