package cn.ibizlab.core.aspect;

import cn.ibizlab.core.rule.domain.RuleEngine;
import cn.ibizlab.core.util.job.TopicListenter;
import cn.ibizlab.util.domain.EntityBase;
import lombok.SneakyThrows;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * @author 无名小卒
 * @data 2022/8/22
 */
//@Aspect
//@Component
//@ConditionalOnExpression("${rocketmq.consumer.enabled:false}")
public class TopicListenerApsect {
  @Autowired
  private TopicListenter topicListenter;

    @Pointcut("execution( * cn.ibizlab.core.rule.service.IRuleEngineService.create(..))")
    public void create() {
    }

    @Pointcut("execution( * cn.ibizlab.core.rule.service.IRuleEngineService.update(..))")
    public void update() {
    }

    /**
     * 规则引擎创建切面
     *
     * @param point
     */
    @AfterReturning(value = "create()|| update()")
    @SneakyThrows
    public void create(JoinPoint point) {
        Object[] args = point.getArgs();
        if (ObjectUtils.isEmpty(args) || args.length == 0) {
            return;
        }
        Object serviceParam = args[0];
        if (serviceParam instanceof EntityBase) {
            EntityBase entity = (EntityBase) serviceParam;
            String extparams = (String) entity.get("extparams");
            if (extparams.contains("isAuto") && extparams.contains("topic")) {
               topicListenter.updruleEngine((RuleEngine) entity);
            }
        }
    }
    /**
     * 实体数据更新切面，在成功更新数据后将新增数据内容记录审计日志内（审计明细【AuditInfo】中只记录审计属性变化情况，审计属性在平台属性中配置）
     * 使用环切【@Around】获取要删除的完整数据，并将审计属性相关信息记录到审计日志中
     *
     * @param point
     * @return
     * @throws Throwable
     */
    @AfterReturning("execution(* cn.ibizlab.core.rule.service.IRuleEngineService.remove(..))")
    public void remove(JoinPoint point) throws Throwable {
        Object args[] = point.getArgs();
        if (ObjectUtils.isEmpty(args) || args.length == 0) {
            return;
        }
        Object idValue = args[0];
        topicListenter.delEngine((String) idValue);
    }


}
