package com.qmth.sop.task.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.sop.business.entity.*;
import com.qmth.sop.business.service.*;
import com.qmth.sop.common.contant.SpringContextHolder;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.*;
import com.qmth.sop.common.util.ResultUtil;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @Description: job监听
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2022/9/22
 */
public class MyJobListener implements JobListener {
    private final static Logger log = LoggerFactory.getLogger(MyJobListener.class);

    @Override
    public String getName() {
        return "myJobListener";
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
        log.info("定时任务:{}-开始执行", context.getTrigger().getJobKey());
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {

    }

    @Override
    @Transactional
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        JobEnum jobEnum = JobEnum.valueOf(context.getTrigger().getJobKey().getGroup());
        switch (jobEnum) {
            case REMIND_QUARTZ_JOB_GROUP:
                try {
                    JobDataMap map = context.getJobDetail().getJobDataMap();
                    TSJobRemind tsJobRemind = (TSJobRemind) map.get(SystemConstant.JOB_DATA);
                    tsJobRemind.setEnable(false);

                    TSJobRemindService tsJobRemindService = SpringContextHolder.getBean(TSJobRemindService.class);
                    tsJobRemindService.updateById(tsJobRemind);
                    TSJobLogService tsJobLogService = SpringContextHolder.getBean(TSJobLogService.class);
                    TSJobLog tsJobLog = new TSJobLog(tsJobRemind);
                    tsJobLogService.save(tsJobLog);

                    //往延期预警表插数据
                    if (tsJobRemind.getType() == JobQuartzTypeEnum.FLOW && tsJobRemind.getRemindType() == JobTypeEnum.AFTER) {
                        TFCustomFlowEntityService tfCustomFlowEntityService = SpringContextHolder.getBean(TFCustomFlowEntityService.class);
                        TFCustomFlowEntity tfCustomFlowEntity = tfCustomFlowEntityService.getOne(new QueryWrapper<TFCustomFlowEntity>().lambda().eq(TFCustomFlowEntity::getCode, tsJobRemind.getCode()));
                        Optional.ofNullable(tfCustomFlowEntity).orElseThrow(() -> ExceptionResultEnum.FLOW_ENTITY_NO_DATA.exception());

                        if (tsJobRemind.getCode().contains(SystemConstant.SOP)) {
                            TBDelayWarnService tbDelayWarnService = SpringContextHolder.getBean(TBDelayWarnService.class);
                            SequenceService sequenceService = SpringContextHolder.getBean(SequenceService.class);

                            TBSopInfoService tbSopInfoService = SpringContextHolder.getBean(TBSopInfoService.class);
                            TBSopInfo tbSopInfo = tbSopInfoService.getById(tfCustomFlowEntity.getObjId());
                            Optional.ofNullable(tbSopInfo).orElseThrow(() -> ExceptionResultEnum.SOP_INFO_NO_DATA.exception());

                            String code = DelayWarnSeqTypeEnum.DELAY_WARN.getMark() + sequenceService.createCode(DelayWarnSeqTypeEnum.DELAY_WARN.getCode());
                            tbDelayWarnService.save(new TBDelayWarn(tbSopInfo.getCrmNo(), tbSopInfo.getSopNo(), tbSopInfo.getServiceId(), code, tsJobLog.getCreateTime(), tsJobRemind.getReceiveUserId(), tsJobRemind.getExecField()));
                        }
                    }
                } catch (Exception e) {
                    log.error(SystemConstant.LOG_ERROR, e);
                    if (e instanceof ApiException) {
                        ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
                    } else {
                        ResultUtil.error(e.getMessage());
                    }
                }
                break;
            default:
                break;
        }
        log.info("定时任务:{}-执行结束", context.getTrigger().getJobKey());
    }
}