package cn.axzo.workflow.core.engine.job.service;

import cn.axzo.workflow.common.constant.LogFieldConstants;
import cn.axzo.workflow.core.engine.job.utils.AsyncJobUtils;
import cn.azxo.framework.common.constatns.Constants;
import lombok.extern.slf4j.Slf4j;
import org.flowable.job.service.JobProcessor;
import org.flowable.job.service.JobProcessorContext;
import org.flowable.job.service.impl.persistence.entity.AbstractJobEntity;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class JobLogProcessor implements JobProcessor {

    @Override
    public void process(JobProcessorContext jobProcessorContext) {
        if (jobProcessorContext.getPhase() == JobProcessorContext.Phase.BEFORE_EXECUTE) {
            AbstractJobEntity jobEntity = jobProcessorContext.getJobEntity();
            String customValues = jobEntity.getCustomValues();
            if (AsyncJobUtils.isWrappedCustomValues(customValues)) {
                AsyncJobUtils.WrappedJobCustomValuesInfo bean = AsyncJobUtils.convert2WrappedCustomValuesInfo(customValues);
                if (bean != null) {
                    //原始的值重新设置回去
                    String originalCustomValues = bean.getCustomValues();
                    jobEntity.setCustomValues(originalCustomValues);
                    MDC.put(LogFieldConstants.X_REQUEST_ID, bean.getXRequestId());
                    MDC.put(Constants.CTX_LOG_ID_MDC, bean.getCtxLogId());
                    return;
                }
            }
            //不是包装的customValues,MDC删除log的两个字段
            MDC.remove(LogFieldConstants.X_REQUEST_ID);
            MDC.remove(Constants.CTX_LOG_ID_MDC);
        } else if (jobProcessorContext.getPhase() == JobProcessorContext.Phase.BEFORE_CREATE) {//持久化之前做处理
            AbstractJobEntity jobEntity = jobProcessorContext.getJobEntity();
            String customValues = jobEntity.getCustomValues();
            jobEntity.setCustomValues(AsyncJobUtils.getWrappedCustomValues(customValues));
        }
    }


}
