package cn.ibizlab.core.util.job;

import cn.ibizlab.core.rule.filter.RuleEngineSearchContext;
import cn.ibizlab.util.helper.Setting;
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("RuleExecJobHandler")
public class RuleExecJobHandler implements IJobsHandler {

    @Autowired
    @Lazy
    protected cn.ibizlab.core.rule.service.IRuleEngineService ruleengineService;

    @Override
    public JobsResponse execute(String tenantId, String param) throws JobsException {
        cn.ibizlab.core.rule.domain.RuleEngine entity= Setting.getEntity(param,new cn.ibizlab.core.rule.domain.RuleEngine());
        entity.set("tenantid",tenantId);

        if(!StringUtils.isEmpty(entity.getEngineId()))
        {
            ruleengineService.run(entity);
        }
        else
        {
            RuleEngineSearchContext context=new RuleEngineSearchContext();
            if(!StringUtils.isEmpty(entity.getGroup()))
                context.getSearchCond().like("rulegroup",entity.getGroup());
            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);
            ruleengineService.searchDefault(context).getContent().forEach(item->{
                ruleengineService.run(item);
            });
        }

        log.info("执行 DemoJobHandler tenantId=" + tenantId + ",param=" + param);
        return JobsResponse.ok();
    }
}
