package com.srs.flowable.listener.relieve;

import com.srs.common.utils.WeChatUtil;
import com.srs.common.utils.spring.SpringUtils;
import com.srs.flowable.mapper.LeaveMapper;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 根据学生userId获取辅导员id
 */
@Component
@Slf4j
public class StuCounselorListener implements ExecutionListener {

    @Autowired
    private WeChatUtil weChatUtil;

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

        // 获取辅导员的sys_user表id
        Map<String ,Long> map = relieveMapper.getCounselorInfo(Long.valueOf(delegateExecution.getVariable("stuUserId").toString()));

        if (map != null){
            // 辅导员的信息
            delegateExecution.setVariable("approval",map.get("userId"));
            // 辅导员的部门id
            delegateExecution.setVariable("deptId",map.get("deptId"));

            // todo 企业微信推送消息
            /**
             * 庞世斌
             */
            try {
                Long userId = map.get("userId");

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

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

                    // 构造包含超链接的消息内容
                    String content = "您有一条新的学生违纪审批任务待处理，" +
                            "<a href='https://zhxg.gxsdxy.cn/wab/#/pages/Approval/index'>点此查看</a>";

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

                } else {
                    // 如果找不到 userName，记录警告日志，但流程继续
                    log.warn("⚠ 找到了审批人(userId:{}), 但其对应的企业微信账号(userName)为空，无法发送通知。", userId);
                }
            } catch (Exception e) {
                Long userId = map.get("userId"); // 确保日志里带上 userId
                log.error("❌ 向学务干事(userId:{})发送企业微信通知时出现异常，但流程将继续。错误详情:", userId, e);
            }



        }else {
            throw new RuntimeException("获取辅导员信息失败");
        }

    }
}
