<?php
namespace Meibuyu\Micro\Aspect;

use Meibuyu\Micro\Handler\LogTrace\LogTraceHandler;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Meibuyu\Micro\Annotation\AsyncCoroutine;
use Hyperf\Utils\Coroutine;

/**
 * @Aspect(
 *   annotations={
 *      AsyncCoroutine::class
 *   }
 * )
 */
class AsyncCoroutineAspect extends AbstractAspect
{

    /**
     * 优先级
     * @var int
     */
    public $priority = 998;

    public function process(ProceedingJoinPoint $proceedingJoinPoint)
    {
        // 切面切入后,执行对应的方法会由此来负责
        // $proceedingJoinPoint 为连接点,通过该类的 process() 方法调用原方法并获得结果
        // 在调用前进行某些处理
        return Coroutine::create(function ()use($proceedingJoinPoint){

            try {
                LogTraceHandler::recordProcess(
                    '投递到子协程任务,id:'.Coroutine::id()
                    .' ,类:'.$proceedingJoinPoint->className
                    .' ,方法:'.$proceedingJoinPoint->methodName
                    .' ,参数:'.json_encode($proceedingJoinPoint->getArguments())
                    ,
                    true
                );
                $result = $proceedingJoinPoint->process();
                LogTraceHandler::recordProcess(
                    '子协程任务id:'.Coroutine::id().'已完成,执行结果:'.
                    json_encode($result),true
                );
            }catch (\Throwable $exception){
                LogTraceHandler::recordProcess($exception,true);
            }

        });


    }
}