package com.inspect.aspect;

import com.inspect.annotation.TaskStatusChange;
import com.inspect.task.service.IPatrolTaskService;
import com.inspect.taskstatus.domain.PatrolTaskStatus;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class TaskStatusChangeAspect {

    @Autowired
    private IPatrolTaskService patrolTaskService;


    /**
     * 拦截带有 @TaskStatusChange 注解的方法
     */
    @AfterReturning(pointcut = "@annotation(taskStatusChange)", returning = "result")
    public void afterTaskStatusChange(JoinPoint joinPoint, TaskStatusChange taskStatusChange, Object result) {
        try {
            log.info("任务状态变更切面执行，方法: {}", joinPoint.getSignature());
            // 获取方法参数
            Object[] args = joinPoint.getArgs();
            if (args == null || args.length == 0) {
                return;
            }

            // 查找 PatrolTaskStatus 参数
            PatrolTaskStatus taskStatus = findTaskStatusParam(args, taskStatusChange.stateField());
            if (taskStatus == null) {
                log.warn("未找到任务状态参数");
                return;
            }

            // 检查状态是否符合目标状态
            if (!isTargetState(taskStatus, taskStatusChange.targetState())) {
                return;
            }

            // 执行切面逻辑
            if (taskStatusChange.async()) {
                log.info("异步执行区域任务合并报告，任务执行id: {}", taskStatus.getTaskPatrolledId());
                patrolTaskService.executeAsync(taskStatus);
            } else {
                executeSync(taskStatus);
            }

        } catch (Exception e) {
            log.error("任务状态变更切面处理异常", e);
        }
    }

    /**
     * 从方法参数中查找任务状态对象
     */
    private PatrolTaskStatus findTaskStatusParam(Object[] args, String stateField) {
        for (Object arg : args) {
            if (arg instanceof PatrolTaskStatus) {
                return (PatrolTaskStatus) arg;
            }
        }
        return null;
    }

    /**
     * 检查是否为目标状态
     */
    private boolean isTargetState(PatrolTaskStatus taskStatus, String targetState) {
        if (targetState == null || targetState.isEmpty()) {
            return true; // 如果没有指定目标状态，则所有状态变更都触发
        }
        return targetState.equals(taskStatus.getTaskState());
    }

    /**
     * 同步执行
     */
    private void executeSync(PatrolTaskStatus taskStatus) {
        log.info("同步执行任务状态变更处理，任务: {}", taskStatus);
    }


}
