package com.srs.flowable.listener.relieve;

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

/**庞世斌
 *
 * 根据审批结果给学生发送企业微信通知
 */
@Component
@Slf4j
public class StuReceiveListener implements ExecutionListener {

    @Override
    public void notify(DelegateExecution delegateExecution) {
        RelieveMapper relieveMapper = (RelieveMapper) SpringUtils.getBean("relieveMapper");

        try {
            // 从流程变量中获取学生 userId（之前在发给辅导员时已经存入）
            Long stuUserId = Long.valueOf(delegateExecution.getVariable("stuUserId").toString());

            // 使用 userId 查询对应的企业微信账号
            String stuUserName = relieveMapper.getUserNameByUserId(stuUserId);

            if (stuUserName != null && !stuUserName.isEmpty()) {
                WeChatUtil weChatUtil = SpringUtils.getBean(WeChatUtil.class);

                // 根据流程结果拼接不同的提示信息
                String approveResult = delegateExecution.getVariable("approveResult") != null
                        ? delegateExecution.getVariable("approveResult").toString()
                        : "审批已完成";

                String content = "您的违纪处理流程有新的进展：" +
                        approveResult + "，" +
                        "<a href='https://zhxg.gxsdxy.cn/wab/#/pages/Approval/index'>点此查看详情</a>";

                // 发送企业微信消息
                weChatUtil.sendTextMessage(stuUserName, content);
                log.info("✅ 已成功向学生(userName:{})发送企业微信审批通知。", stuUserName);

            } else {
                log.warn("⚠ 找到了学生(stuUserId:{}), 但其对应的企业微信账号为空，无法发送通知。", stuUserId);
            }
        } catch (Exception e) {
            Long stuUserId = Long.valueOf(delegateExecution.getVariable("stuUserId").toString());
            log.error("❌ 向学生(stuUserId:{})发送企业微信通知时出现异常，但流程将继续。错误详情:", stuUserId, e);
        }
    }
}
