package com.srs.flowable.listener;

import com.srs.common.doman.vo.TeacherVo;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.WeChatUtil;
import com.srs.common.utils.spring.SpringUtils;
import com.srs.flowable.domain.NotificationManage;
import com.srs.flowable.domain.StuLeaveApplication;
import com.srs.flowable.mapper.LeaveMapper;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 二级学院书记审批或学生销假开始监听器
 * 邵政文
 */
@Component
@Slf4j
public class BoStartListener implements ExecutionListener {
    @Override
    public void notify(DelegateExecution delegateExecution) {
        LeaveMapper leaveMapper = (LeaveMapper) SpringUtils.getBean("leaveMapper");

        String deptId = delegateExecution.getVariable("deptId").toString();

        // 二级学院书记审批结果
        String approval = delegateExecution.getVariable("approval").toString();

        // 获取流程ID
        String leaveApplicationId = delegateExecution.getVariable("leaveApplicationId").toString();

        // 获取请假信息
        StuLeaveApplication stuLeaveApplication = leaveMapper.selectRtStuLeaveApplicationByLeaveApplicationId(leaveApplicationId);

        // 获取校领导信息
        String roleKey = "xldsp"; //角色key
        List<TeacherVo> lingDataInfo = leaveMapper.getShenDataInfo(roleKey);
        if (lingDataInfo == null || lingDataInfo.isEmpty()) {
            log.warn("未找到校领导(roleKey={})信息，跳过学工领导通知。", roleKey);
        }

        // 设置流程变量
        //delegateExecution.setVariable("approval", secondaryLeaderInfo.getUserId());

        // todo 企业微信推送消息（邵政文）
        log.info("请假信息：{}", stuLeaveApplication);
        try {
            log.info("二级学院书记审批或学生销假开始监听器");

            // 步骤 3: 检查是否成功获取到 userName
            //向系统发送通知
            NotificationManage notificationManage = new NotificationManage();
            if (lingDataInfo != null && !lingDataInfo.isEmpty()) {
                notificationManage.setContent("您有一条【学工领导已提交请假申请审批】需待处理"); // 消息内容
                notificationManage.setReceiver(lingDataInfo.get(0).getUserId());
            }
            NotificationManage userManage = leaveMapper.selectCphMsgListForFlowable(notificationManage);
            if (userManage != null) {
                //删除指定通知信息
                int delRes = leaveMapper.deleteCphMsgById(userManage.getId());
                log.info("删除成功{}", delRes);
                //向学工领导添加通知信息
                // 获取二级学院书记信息
                List<TeacherVo> secondaryLeaderInfo = leaveMapper.getSecondaryLeaderInfo(deptId);
                if (secondaryLeaderInfo == null || secondaryLeaderInfo.isEmpty()) {
                    log.warn("未找到二级学院书记信息，deptId={}，跳过通知。", deptId);
                } else {
                    //由于这里查到了多个数据，由于时间原因，暂时还没有研究到工作流中多用户节点的同时进行(所以取了第一条数据用于发消息)
                    notificationManage.setContent("您有一条【二级学院书记已提交请假申请审批】需待处理"); // 消息内容
                    notificationManage.setSender(secondaryLeaderInfo.get(0).getUserId()); // 发送方
                }
                notificationManage.setReceiver(Long.parseLong(approval)); // 接收方
                NotificationManage userManages = leaveMapper.selectCphMsgListForFlowable(notificationManage);
                if (userManages == null) {
                    notificationManage.setCreateTime(DateUtils.getNowDate());
                    int res = leaveMapper.insertCphMsg(notificationManage);
                    log.info("添加成功{}", res);
                    //向企业微信发消息
                    TeacherVo updateDeptId = leaveMapper.getUpdateDeptId(approval);
                    // 步骤 2: 使用updateDeptId.getUserName()获取辅导员工号
                    String userName = updateDeptId.getUserName();

                    // 获取向企业微信发通知的工具类
                    WeChatUtil weChatUtil = SpringUtils.getBean(WeChatUtil.class);

                    // 构造包含超链接的消息内容
                    String content = "您有待处理任务，<a href='https://zhxg.gxsdxy.cn/wab/#/pages/Approval/index'>请点击前往处理</a>";

                    // 步骤 4: 使用 userName 作为接收人发送消息
                    //weChatUtil.sendTextMessage(userName, content);
                    log.info("已成功向学工领导(userName:{})发送企业微信请假审批通知。", userName);
                }
                return;
            }
            // 获取请假人id
            Long stuId = (Long) delegateExecution.getVariable("stuId");

            // 查询辅导员工信息
            TeacherVo teacherInfo = leaveMapper.getCounselorInfo(stuId);

            //查询请假人用户信息
            TeacherVo shenUserInfo = leaveMapper.getShenUserInfo(stuId);

            notificationManage.setContent("您有一条【请假人已提交销假审批】需待处理"); // 消息内容
            notificationManage.setReceiver(teacherInfo.getUserId());
            NotificationManage userManages = leaveMapper.selectCphMsgListForFlowable(notificationManage);
            if (userManages != null) {
                //删除指定通知信息
                int delRes = leaveMapper.deleteCphMsgById(userManages.getId());
                log.info("删除成功{}", delRes);
                //向请假人添加通知信息
                //由于这里查到了多个数据，由于时间原因，暂时还没有研究到工作流中多用户节点的同时进行(所以取了第一条数据用于发消息)
                notificationManage.setContent("您有一条【请假申请审批已通过】需待处理"); // 消息内容
                notificationManage.setSender(teacherInfo.getUserId()); // 发送方
                notificationManage.setReceiver(shenUserInfo.getUserId()); // 接收方
                NotificationManage userMsge = leaveMapper.selectCphMsgListForFlowable(notificationManage);
                if (userMsge == null) {
                    notificationManage.setCreateTime(DateUtils.getNowDate());
                    int res = leaveMapper.insertCphMsg(notificationManage);
                    log.info("添加成功{}", res);
                    //向企业微信发消息
                    // 步骤 2: 使用shenUserInfo.getUserName()获取辅导员工号
                    String userName = shenUserInfo.getUserName();

                    // 获取向企业微信发通知的工具类
                    WeChatUtil weChatUtil = SpringUtils.getBean(WeChatUtil.class);

                    // 构造包含超链接的消息内容
                    String content = "您有待处理任务，<a href='https://zhxg.gxsdxy.cn/wab/#/pages/Approval/index'>请点击前往处理</a>";

                    // 步骤 4: 使用 userName 作为接收人发送消息
                    weChatUtil.sendTextMessage(userName, content);
                    log.info("已成功向请假人(userName:{})发送企业微信请假审批通知。", userName);
                }
            }

        } catch (Exception e) {
            // 捕获所有异常，仅记录日志，确保主流程不受影响
            log.error("发送通知或处理通知时出现异常。错误详情: {}", e.getMessage(), e);
        }
    }
}
