package com.srs.flowable.listener.disciplinary;

import com.srs.common.utils.SecurityUtils;
import com.srs.common.utils.WeChatUtil;
import com.srs.comprehensive.domain.CphMsg;
import com.srs.comprehensive.service.ICphMsgService;
import com.srs.flowable.mapper.DisciplinaryMapper;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.SequenceFlow;
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.Assert;

import javax.annotation.PostConstruct;

/**
 * 为“学生接收”节点做准备并发送所有通知。 知无涯
 * <p>
 * 它的核心职责是：
 * 1. 从流程变量 'stuId' 中获取学生ID。
 * 2. 将学生ID设置到 'approval' 流程变量中，供下一个UserTask分配办理人。
 * 3. 向该学生发送企业微信通知。
 * 4. 为该学生创建内部消息，并确保任务名正确。
 * </p>
 */
@Component("stuInfoListener") // 保持Bean名称不变
@Slf4j
public class StuInfoListener implements ExecutionListener {

    @Autowired
    private DisciplinaryMapper disciplinaryMapper;

    @Autowired
    private ICphMsgService cphMsgService;

    @Autowired(required = false)
    private WeChatUtil weChatUtil;

    @PostConstruct
    public void checkDependencies() {
        Assert.notNull(disciplinaryMapper, "DisciplinaryMapper in StuInfoListener is not injected!");
        Assert.notNull(cphMsgService, "ICphMsgService in StuInfoListener is not injected!");
    }

    @Override
    public void notify(DelegateExecution execution) {
        log.info("流程实例 [{}]: 触发 StuInfoListener (一体化版)，为'学生接收'节点准备数据并发送通知...", execution.getProcessInstanceId());

        // --- 步骤 1: 安全地获取学生ID ---
        Object stuIdObj = execution.getVariable("stuId");
        if (stuIdObj == null) {
            throw new IllegalStateException("核心流程变量 'stuId' 未找到。");
        }

        Long stuId;
        try {
            stuId = Long.parseLong(stuIdObj.toString());
        } catch (NumberFormatException e) {
            throw new IllegalStateException("流程变量 'stuId' 类型错误。");
        }

        // --- 步骤 2: (核心) 设置下一个任务的办理人 ---
        execution.setVariable("approval", stuId);
        log.info("已成功将下一个任务的办理人('approval')设置为学生ID: {}", stuId);

        // --- 步骤 3: (可选) 发送企业微信通知 ---
        sendWeChatNotification(stuId);

        // --- 步骤 4: (关键新增) 创建内部消息，并确保任务名正确 ---
        createInternalMessage(stuId, execution);
    }

    /**
     * 发送企业微信通知的私有方法
     */
    private void sendWeChatNotification(Long stuId) {
        if (weChatUtil != null) {
            try {
                String studentUserName = disciplinaryMapper.getUserNameByUserId(stuId);
                if (studentUserName != null && !studentUserName.isEmpty()) {
                    String content = "同学你好，关于你的一项违纪处分申请已有最终结果，请登录系统在'我的待办'中查看并确认。";
                    weChatUtil.sendTextMessage(studentUserName, content);
                    log.info("已成功向学生 (ID:{}) 发送企业微信通知。", stuId);
                } else {
                    log.warn("未找到学生 (ID:{}) 对应的企业微信账号，未发送通知。", stuId);
                }
            } catch (Exception e) {
                log.error("向学生 (ID:{}) 发送企业微信时发生异常: {}", stuId, e.getMessage(), e);
            }
        }
    }

    /**
     * 创建内部消息的私有方法
     */
    private void createInternalMessage(Long receiverId, DelegateExecution execution) {
        try {
            FlowElement nextElement = getNextFlowElement(execution);
//            String taskName = (nextElement != null && nextElement.getName() != null) ? nextElement.getName() : "结果确认";
//            String activityId = (nextElement != null) ? nextElement.getId() : "Activity_0iy3ij6"; // 备用ID
            String taskName = "学生接收";
            String activityId = "Activity_0iy3ij6"; // 备用ID


            String messageText = "您有一条新的【" + taskName + "】待办任务需要处理。";
            String link = "<a href='https://zhxg.gxsdxy.cn/wab/#/pages/Approval/index'>请点击前往处理</a>。";
            String hiddenIdentifier = String.format("<span id='flow-identifier' data-proc-inst-id='%s' data-activity-id='%s' style='display:none;'></span>",
                    execution.getProcessInstanceId(), activityId);
            String internalMessageContent = messageText + link + hiddenIdentifier;

            Long senderId = SecurityUtils.getUserId() != null ? SecurityUtils.getUserId() : 1L;

            CphMsg cphMsg = new CphMsg();
            cphMsg.setReceiver(receiverId);
            cphMsg.setSender(senderId);
            cphMsg.setContent(internalMessageContent);

            cphMsgService.insertCphMsg(cphMsg);
            log.info("已成功为学生 (ID:{}) 创建内部消息。", receiverId);
        } catch (Exception e) {
            log.error("为学生 (ID:{}) 创建内部消息时发生异常: {}", receiverId, e.getMessage(), e);
        }
    }

    /**
     * 安全地获取线上监听器的下一个目标节点
     */
    private FlowElement getNextFlowElement(DelegateExecution execution) {
        if (execution.getCurrentFlowElement() instanceof SequenceFlow) {
            return ((SequenceFlow) execution.getCurrentFlowElement()).getTargetFlowElement();
        }
        return null;
    }
}
