package com.zbf.web.controller.section;

import com.zbf.common.core.page.TableDataInfo;
import com.zbf.generator.util.ColumnUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
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.util.List;
import java.util.Map;

import static com.zbf.common.utils.PageUtils.startPage;

@Aspect
@Component
public class DataListAspect {

    @Pointcut("@annotation(EnhanceDataList)")
    public void dataListPointcut() {}

    //分页不处理
    @Around(value = "dataListPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 先执行目标方法
        Object result = joinPoint.proceed();

        // 检查结果是否为 TableDataInfo 实例
        if (result instanceof TableDataInfo) {
            TableDataInfo dataTable = (TableDataInfo) result;
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            EnhanceDataList enhanceDataList = signature.getMethod().getAnnotation(EnhanceDataList.class);

            // 设置列信息
            dataTable.setColumns(ColumnUtils.getColumnsJson(enhanceDataList.entityType()));

            // 在这里添加其他逻辑来修改 dataTable
            // 例如重新计算 total 或修改 rows
            // dataTable.setTotal(newTotal);
            // dataTable.setRows(newRows);

            return dataTable; // 返回修改后的 dataTable
        }

        return result; // 如果结果不是 TableDataInfo 实例，直接返回原结果
    }



    //集合类
    @Pointcut("@annotation(ListColumns)")
    public void list() {}

    @Around("list()")
    public Object lists(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = joinPoint.proceed();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        ListColumns columns = signature.getMethod().getAnnotation(ListColumns.class);
        if (result instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) result;
            // 确保list也被放入map中
            if (joinPoint.getArgs().length > 0 && joinPoint.getArgs()[0] instanceof List) {
                map.put("list", joinPoint.getArgs()[0]);
            }
            map.put("columns", ColumnUtils.getColumnsJson(columns.value()));
        }
        return result;
    }

}
