package com.srs.flowable.listener.enlistmentReserve;

import com.srs.common.core.domain.entity.SysUser;


import com.srs.common.doman.vo.TeacherVo;
import com.srs.common.utils.SecurityUtils;
import com.srs.common.utils.spring.SpringUtils;
import com.srs.flowable.domain.EnlistmentReserve;
import com.srs.flowable.domain.EnlistmentReserveApproval;
import com.srs.flowable.mapper.EnlistmentReserveApprovalMapper;
import com.srs.flowable.mapper.EnlistmentReserveMapper;
import com.srs.system.service.ISysUserService;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowNode;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
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.Date;
import java.util.List;


/**
 * 审批流程负责人自动流转监听器
 * 用于节点审批通过时，添加审批记录
 */
@Component("approvalAssigneeListener") // Spring Bean名称，与BPMN表达式对应
public class ApprovalAssigneeListener implements ExecutionListener {

    @Autowired
    private ISysUserService sysUserService; // 用户服务（查询部门/学院负责人）

    // 用于查询流程定义中的节点信息
    @Autowired
    private RepositoryService repositoryService;

    @Override
    public void notify(DelegateExecution execution) {
        // 1. 获取当前节点ID和流程定义ID
        String currentActivityId = execution.getCurrentActivityId(); // 当前节点ID（兼容所有版本）
        String processDefinitionId = execution.getProcessDefinitionId(); // 流程定义ID

        // 2. 根据节点ID查询节点名称（核心修正：通过流程定义获取名称）
        String currentNodeName = getNodeNameByActivityId(processDefinitionId, currentActivityId);
        if (currentNodeName == null) {
            throw new RuntimeException("未找到节点ID=" + currentActivityId + "的名称");
        }

        // 3. 获取流程实例ID
        String processInstanceId = execution.getProcessInstanceId();

        // 获取申请表id
        Long enlistmentId = Long.valueOf(execution.getVariable("enlistmentId").toString());

        // 获取审核意见
        String approvalOpinion = (String) execution.getVariable("approvalOpinion");

        // 获取审核状态（兼容Integer/Long类型）
        Object approvalResultObj = execution.getVariable("approvalResult");
        Long approvalResult = null;
        if (approvalResultObj != null) {
            // 先转为数字，再获取long值
            Number num = (Number) approvalResultObj;
            approvalResult = num.longValue();
        }

        // 添加审批记录
        EnlistmentReserveMapper rtEnlistmentReserveMapper = (EnlistmentReserveMapper) SpringUtils.getBean(EnlistmentReserveMapper.class);
        // 根据Id查询入伍申请记录
        EnlistmentReserve enlistmentReserve = rtEnlistmentReserveMapper.selectRtEnlistmentReserveById(enlistmentId);
        saveApprovalRecord(enlistmentReserve.getId(), enlistmentReserve.getProcessInstanceId(),currentActivityId,currentNodeName, enlistmentReserve.getStudentName(), enlistmentReserve.getStudentNo(), approvalOpinion, approvalResult);

        // 如果到了最后一个审批人，则修改申请表审核状态
        if (currentNodeName.equals("教务处主管领导审批")){
            // 改变申请表中的审核状态（审核通过）
            enlistmentReserve.setApplyStatus(2L);
            rtEnlistmentReserveMapper.updateRtEnlistmentReserve(enlistmentReserve);
        }
    }

    /**
     * 根据节点ID和流程定义ID，查询节点名称（兼容所有版本的核心方法）
     */
    private String getNodeNameByActivityId(String processDefinitionId, String activityId) {
        // 获取流程模型
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        if (bpmnModel == null) {
            throw new RuntimeException("未找到流程定义ID=" + processDefinitionId + "的模型");
        }

        // 从模型中获取节点信息（FlowNode包含用户任务、网关等节点）
        FlowNode flowNode = (FlowNode) bpmnModel.getFlowElement(activityId);
        return flowNode != null ? flowNode.getName() : null;
    }

    /**
     * 通用审批记录保存方法
     */
    private void saveApprovalRecord(Long ApplyId,String processInstanceId, String taskId, String nodeName, String studentName, String studentNo, String approvalOpinion, Long approvalResult) {
        EnlistmentReserveApproval enlistmentReserveApproval = new EnlistmentReserveApproval();
        // 赋值
        enlistmentReserveApproval.setApplyId(ApplyId);
        enlistmentReserveApproval.setProcessInstanceId(processInstanceId);
        enlistmentReserveApproval.setTaskId(taskId);
        enlistmentReserveApproval.setNodeName(nodeName);
        enlistmentReserveApproval.setApproverId(SecurityUtils.getLoginUser().getUser().getUserId());
        // SecurityUtils.getUserName()是工号
        enlistmentReserveApproval.setApproverName(SecurityUtils.getLoginUser().getUser().getNickName());

        // 若变量未传递，直接用默认值“同意”（前端点击同意按钮的默认意见）
        enlistmentReserveApproval.setApprovalOpinion(approvalOpinion);

        // 审核状态
        enlistmentReserveApproval.setApprovalResult(approvalResult == null ? 0L : approvalResult);

        // 审批时间：当前系统时间
        enlistmentReserveApproval.setApprovalTime(new Date());
        enlistmentReserveApproval.setStudentName(studentName);
        enlistmentReserveApproval.setStudentNo(studentNo);
        System.out.println(SecurityUtils.getLoginUser().getUser());
        EnlistmentReserveApprovalMapper rtEnlistmentReserveApprovalMapper = (EnlistmentReserveApprovalMapper) SpringUtils.getBean(EnlistmentReserveApprovalMapper.class);
        // 查询审批记录是否存在
        EnlistmentReserveApproval enlistmentReserveApproval1 = rtEnlistmentReserveApprovalMapper.selectRtEnlistmentReserveApprovalByStuName(studentName, studentNo, SecurityUtils.getLoginUser().getUser().getUserId());
        if (enlistmentReserveApproval1 == null) {
            rtEnlistmentReserveApprovalMapper.insertRtEnlistmentReserveApproval(enlistmentReserveApproval);
        } else {
            enlistmentReserveApproval.setId(enlistmentReserveApproval1.getId());
            rtEnlistmentReserveApprovalMapper.updateRtEnlistmentReserveApproval(enlistmentReserveApproval);
        }
    }
}