package com.docus.server.service.impl;

import com.docus.core.util.DateUtil;
import com.docus.log.annotation.TrackGroup;
import com.docus.server.common.process.ChannelProcessor;
import com.docus.server.entity.scheduling.management.SchCollectRecord;
import com.docus.server.entity.scheduling.management.SchCollectRecordRetryLog;
import com.docus.server.enums.StateEnum;
import com.docus.server.enums.SubStateEnum;
import com.docus.server.infrastructure.dao.ISchCollectRecordDao;
import com.docus.server.infrastructure.dao.ISchCollectRecordRetryLogDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class RedisKeyExpirationService {
    @Resource
    private ISchCollectRecordDao iSchCollectRecordDao;
    @Resource
    private ISchCollectRecordRetryLogDao iSchCollectRecordRetryLogDao;

    @TrackGroup(group = "RedisKeyExpirationService-expired", processor = ChannelProcessor.class)
    public void expired(String expireKey) {

        if (expireKey.startsWith("schCollectorRecord:noRetryTask:expireKey:")) {
            System.out.println("expireKey过期了===" + expireKey);

            String recordId = expireKey.substring(expireKey.lastIndexOf(":") + 1);

            SchCollectRecord collectRecord = iSchCollectRecordDao.findById(recordId);
            collectRecord.setTaskExecState(StateEnum.FAIL);
            //超时作废
            collectRecord.setSubTaskExecState(SubStateEnum.CANCEL);
            collectRecord.setUpdateTime(DateUtil.now());
            collectRecord.setLastTaskErrorMsg("任务超时，触发任务作废");
            iSchCollectRecordDao.updateById(collectRecord);

        }
        if (expireKey.startsWith("schCollectorRecord:isRetryTask:expireKey:")) {
            System.out.println("expireKey过期了===" + expireKey);

            String logRecordId = expireKey.substring(expireKey.lastIndexOf(":") + 1);

            SchCollectRecordRetryLog recordRetryLog = iSchCollectRecordRetryLogDao.findById(logRecordId);
            recordRetryLog.setTaskExecState(StateEnum.FAIL);
            recordRetryLog.setSubTaskExecState(SubStateEnum.CANCEL);
            recordRetryLog.setUpdateTime(DateUtil.now());
            recordRetryLog.setLastTaskErrorMsg("任务超时，触发任务作废");
            iSchCollectRecordRetryLogDao.updateById(recordRetryLog);

        }

    }

}
