package com.kym.common.aspect;

import com.kym.common.annotation.ConnectorID;
import com.kym.common.annotation.PlatformName;
import com.kym.common.exception.BusinessException;
import com.kym.common.utils.PlatformConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;


/**
 * APP日志，切面处理类
 *
 * @author skyline
 */
@Aspect
@Component
@Slf4j
public class PlatformConvertAspect {


    /**
     * 切点
     */
    @Pointcut("@annotation(com.kym.common.annotation.PlatformConvert)")
    public void platformConvertPointCut() {
    }

    @Around("platformConvertPointCut()")
    Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        return convert(joinPoint);
    }


    private Object convert(ProceedingJoinPoint joinPoint) throws Throwable {
        if (joinPoint == null) {
            throw new IllegalArgumentException("joinPoint cannot be null");
        }

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        if (method == null) {
            throw new IllegalArgumentException("method cannot be null");
        }

        Parameter[] parameters = method.getParameters();
        Object[] args = joinPoint.getArgs();
        Platform platformName = Platform.EN_PLUS;

        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            if (parameter.isAnnotationPresent(PlatformName.class)) {
                if (args[i] != null) {
                    platformName = Platform.valueOf(args[i].toString());
                }
            } else if (parameter.isAnnotationPresent(ConnectorID.class)) {
                if (args[i] != null) {
                    switch (platformName) {
                        case EN_PLUS:
                            args[i] = PlatformConvertUtil.parse2LocalConnectorId(args[i].toString());
                            break;
                        case LONGSHINE:
                            args[i] = PlatformConvertUtil.convert2LongshineConnectorId(args[i].toString());
                            break;
                        default:
                            throw new BusinessException("不支持的平台：" + platformName);
                    }
                }
            }
        }

        return joinPoint.proceed(args);
    }

    // 枚举类定义
    enum Platform {
        EN_PLUS, LONGSHINE
    }
}
