package com.srs.flowable.listener;

import com.srs.common.utils.DateUtils;
import com.srs.common.utils.SecurityUtils;
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;

/**
 * 销假核实监听
 */
@Slf4j
@Component
public class CancellationListener 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();

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

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

        StuLeaveApplication stuLeaveApplication = leaveMapper.selectRtStuLeaveApplicationByLeaveApplicationId(leaveApplicationId);

        if (stuLeaveApplication != null) {
            stuLeaveApplication.setCancellation(2);
        }
        stuLeaveApplication.setUpdateBy(SecurityUtils.getUsername());

        stuLeaveApplication.setUpdateTime(DateUtils.getNowDate());

        leaveMapper.updateRtStuLeaveApplication(stuLeaveApplication);

        // 推送消息（邵政文）
        //查询指定用户的通知信息并且删除
        log.info("辅导员处理销假审批");
        log.info("接收人为{}",approval);
        NotificationManage notificationManage = new NotificationManage();
        notificationManage.setContent("您有一条【请假人已提交销假审批】需待处理"); // 消息内容
        notificationManage.setReceiver(Long.parseLong(approval)); // 接收人
        NotificationManage userManage = leaveMapper.selectCphMsgListForFlowable(notificationManage);
        int delRes;
        if(userManage != null) {
            //删除指定通知信息
            delRes = leaveMapper.deleteCphMsgById(userManage.getId());
            if(delRes > 0) {
                log.info("删除成功{}", delRes);
            } else {
                log.info("删除失败成功，没有要删除的消息");
            }
        }
        else {
            log.info("没有查到通知消息，请核实是否发起了请假申请");
        }
    }
}
