package cn.ibizlab.core.util.job;

import cn.ibizlab.core.analysis.filter.DABuildSearchContext;
import com.baomidou.jobs.api.JobsResponse;
import com.baomidou.jobs.exception.JobsException;
import com.baomidou.jobs.handler.IJobsHandler;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

@Slf4j
@Component("AnalysisBuildJobHandler")
public class AnalysisBuildJobHandler implements IJobsHandler {

    @Autowired
    @Lazy
    protected cn.ibizlab.core.analysis.service.IDABuildService dabuildService;

    @Override
    public JobsResponse execute(String tenantId, String param) throws JobsException {
        cn.ibizlab.core.analysis.domain.DABuild entity = cn.ibizlab.util.helper.Setting.getEntity(param, new cn.ibizlab.core.analysis.domain.DABuild());
        entity.set("tenantid", tenantId);
        if(!StringUtils.isEmpty(entity.getBuildId()))
        {
            dabuildService.run(entity);
        }
        else
        {
            DABuildSearchContext context=new DABuildSearchContext();

            if(!StringUtils.isEmpty(entity.getModelId()))
                context.setN_modelid_eq(entity.getModelId());
            if(!StringUtils.isEmpty(entity.getModelName()))
                context.setN_modelname_eq(entity.getModelName());
            if(!StringUtils.isEmpty(entity.getSystemId()))
                context.setN_systemid_eq(entity.getSystemId());
            context.setSize(Short.MAX_VALUE);
            dabuildService.searchDefault(context).getContent().forEach(item->{
                dabuildService.run(item);
            });
        }
        log.info("执行 DemoJobHandler tenantId=" + tenantId + ",param=" + param);
        return JobsResponse.ok();
    }
}
