package com.srs.flowable.listener;

import com.srs.common.doman.vo.TeacherVo;
import com.srs.common.enums.ApplicationStatus;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.SecurityUtils;
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.apache.poi.hpsf.Decimal;
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.math.BigDecimal;
import java.util.List;

/**
 * 领导审核
 * 当请假天数大于等于4天以上，由最后一个节点的领导审核通过后，请假单才能流转状态
 */
@Component
@Slf4j
public class LeadAuditListener implements ExecutionListener {


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

        log.info("任务流相关数据", delegateExecution);

        // 辅导员审批结果
        String approval = delegateExecution.getVariable("approval").toString();

        // 拿到流程所有参数
        String approved = delegateExecution.getVariable("approved").toString();

        // 获取请假天数
        BigDecimal leaveDays = (BigDecimal) delegateExecution.getVariable("leaveDays");

        // 获取请假人id
        Long stuId = (Long) delegateExecution.getVariable("stuId");

        // 请假单id
        // 报错信息
        String leaveApplicationId = delegateExecution.getVariable("leaveApplicationId").toString();

        log.info("审批结果为：", approval);

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

        StuLeaveApplication stuLeaveApplication = leaveMapper.selectRtStuLeaveApplicationByLeaveApplicationId(leaveApplicationId);

        if (stuLeaveApplication != null) {
            // 同意
            if ("true".equals(approved)) {
                stuLeaveApplication.setStatus(ApplicationStatus.APPROVED.getCode());
            }
        }

        stuLeaveApplication.setUpdateBy(SecurityUtils.getUsername());

        stuLeaveApplication.setUpdateTime(DateUtils.getNowDate());

        leaveMapper.updateRtStuLeaveApplication(stuLeaveApplication);

        log.info("审核成功");

        //企业微信推送消息（邵政文）
        try {
            log.info("请假人");
            log.info("请假人数据为：{}", stuLeaveApplication);
            log.info("审批结果为：{}", approval);
            // 步骤 2: 发送消息的接收人stuLeaveApplication.getCreateBy()
            String userName = stuLeaveApplication.getCreateBy();

            // 步骤 3: 检查是否成功获取到 userName
            if (userName != null && !userName.isEmpty()) {
                //构建通知信息
                NotificationManage notificationManage = new NotificationManage();

                // 判断请假天数
                int leaveDay = leaveDays.intValue();
                // 向系统发送通知
                if(leaveDay >= 4 && leaveDay <= 7) {
                    //查询指定用户的通知信息
                    notificationManage.setContent("您有一条【辅导员已提交请假审批】需待处理"); // 消息内容
                    notificationManage.setReceiver(Long.parseLong(approval)); //接收人
                    NotificationManage userManage = leaveMapper.selectCphMsgListForFlowable(notificationManage);
                    if(userManage != null) {
                        //删除指定通知信息
                        int delRes = leaveMapper.deleteCphMsgById(userManage.getId());
                        log.info("删除成功{}", delRes);
                    }

                    //构建通知信息内容
                    notificationManage.setContent("您有一条【二级学院书记已提交请假申请审批】需待处理"); // 消息内容
                    notificationManage.setSender(Long.parseLong(approval)); // 发送方
                }
                if(leaveDay >= 8 && leaveDay <= 14) {
                    //获取学工领导信息
                    String roleKey = "xgldsp"; //角色key
                    List<TeacherVo> xueDataInfo = leaveMapper.getShenDataInfo(roleKey);
                    if (xueDataInfo == null || xueDataInfo.isEmpty()) {
                        log.warn("未找到学工领导(roleKey={})信息，跳过该环节通知。", roleKey);
                    } else {
                    //查询指定用户的通知信息
                    notificationManage.setContent("您有一条【二级学院书记已提交请假申请审批】需待处理"); // 消息内容
                    notificationManage.setReceiver(Long.parseLong(xueDataInfo.get(0).getUserId().toString())); //接收人需添加appvoval//185043
                    NotificationManage userManage = leaveMapper.selectCphMsgListForFlowable(notificationManage);
                    if(userManage != null) {
                        //删除指定通知信息
                        int delRes = leaveMapper.deleteCphMsgById(userManage.getId());
                        log.info("删除成功{}", delRes);
                    }

                    //构建通知信息内容
                    notificationManage.setContent("您有一条【学工领导已提交请假申请审批】需待处理"); // 消息内容
                    notificationManage.setSender(Long.parseLong(approval)); // 发送方
                    }
                }
                if(leaveDay >= 15 && leaveDay <= 30) {
                    //获取校领导信息
                    String roleKey = "xldsp"; //角色key
                    List<TeacherVo> lingDataInfo = leaveMapper.getShenDataInfo(roleKey);
                    if (lingDataInfo == null || lingDataInfo.isEmpty()) {
                        log.warn("未找到校领导(roleKey={})信息，跳过该环节通知。", roleKey);
                    } else {
                        notificationManage.setContent("您有一条【学工领导已提交请假申请审批】需待处理"); // 消息内容
                        notificationManage.setReceiver(lingDataInfo.get(0).getUserId()); //接收人185362
                        NotificationManage userManage = leaveMapper.selectCphMsgListForFlowable(notificationManage);
                        if(userManage != null) {
                            //删除指定通知信息
                            int delRes = leaveMapper.deleteCphMsgById(userManage.getId());
                            log.info("删除成功{}", delRes);
                        }

                        //构建通知信息内容
                        notificationManage.setContent("您有一条【学院领导已提交请假申请审批】待处理"); // 消息内容
                        notificationManage.setSender(lingDataInfo.get(0).getUserId()); // 发送方185362
                    }
                }
                notificationManage.setReceiver(shenUserInfo.getUserId());
                notificationManage.setCreateTime(DateUtils.getNowDate());
                int res = leaveMapper.insertCphMsg(notificationManage);
                log.info("添加成功{}", res);

                //获取向企业微信发通知的工具类
                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);
                log.info("已成功向送企业微信销假通知。{}", stuLeaveApplication.getStuId());

            } else {
                // 如果找不到userName，记录警告日志，但流程继续
                log.warn("没有找到对应审批人，无法发送通知。");
            }

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