
package com.lideeyunji.core.framework.config.aspect.enhance;

import com.lideeyunji.core.framework.config.aspect.enhance.annotation.LideeyunJiEnhance;
import com.lideeyunji.core.framework.config.aspect.enhance.model.BuildSqlEnhanceContext;
import com.lideeyunji.core.framework.config.aspect.enhance.model.EnhanceContext;
import com.lideeyunji.core.framework.config.aspect.enhance.model.EnhanceResult;
import com.lideeyunji.core.framework.config.aspect.enhance.strategy.enums.SqlEnhanceButtonEnums;
import com.lideeyunji.core.framework.config.aspect.enhance.strategy.sql.EnhanceSqlStrategy;
import com.lideeyunji.core.framework.entity.EnhanceSqlEntity;
import com.lideeyunji.core.framework.service.IEnhanceSqlService;
import com.lideeyunji.core.framework.utils.Func;
import com.lideeyunji.tool.framework.yunji.model.ResultDataModel;
import com.lideeyunji.tool.framework.yunji.utils.FuncBase;
import com.lideeyunji.tool.framework.yunji.utils.lideeYunJiUtils;
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;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @author JX
 * @create 2024-08-19 13:46
 * @dedescription:
 */
@Aspect
@Component
public class LideeYunJiSqlEnhance extends LideeYunJiBaseEnhance {

    private static Map<String, List<EnhanceSqlEntity>> enhanceMaps = new HashMap<>();


    @Autowired
    private IEnhanceSqlService enhanceSqlService;

    @PostConstruct
    //初始化SQL增强
    public void initSqlEnhanceMaps() {
        //SQL插件--那个表单_功能 有sql增强
        List<EnhanceSqlEntity> allSqlEntityList = enhanceSqlService.getAllSqlEnhance();
        allSqlEntityList.forEach(sqlEntity -> {
            Long dbformId = sqlEntity.getDbformId();
            String buttonCode = sqlEntity.getButtonCode();
            String key = dbformId + "_" + buttonCode;
            enhanceMaps.merge(key, new ArrayList<>(Collections.singletonList(sqlEntity)), (oldValue, newValue) -> {
                oldValue.addAll(newValue);
                return oldValue;
            });
        });
    }

    @AfterReturning(pointcut = "@annotation(lideeyunJiEnhance)" ,returning = "returnVal")
    public Object afterReturingAdvice(JoinPoint joinPoint, Object returnVal, LideeyunJiEnhance lideeyunJiEnhance) {
        BuildSqlEnhanceContext sqlEnhanceContext = getEnhanceContext(lideeyunJiEnhance,joinPoint);
        if (FuncBase.isEmpty(sqlEnhanceContext)) {
            return returnVal;
        }
        List<EnhanceSqlEntity> sqlEntityList = sqlEnhanceContext.getEntitys();
        if(Func.isEmpty(sqlEntityList)){//没有增强
            return returnVal;
        }

        EnhanceContext context = sqlEnhanceContext.getContext();
        Object result = super.getResult(joinPoint, context);
        for (EnhanceSqlEntity enhanceSqlEntity : sqlEntityList) {
            SqlEnhanceButtonEnums enhanceButtonEnums = SqlEnhanceButtonEnums.getByCode(enhanceSqlEntity.getButtonCode());
            if(Func.isEmpty(enhanceButtonEnums)){
                continue;
            }
            EnhanceSqlStrategy strategy = enhanceButtonEnums.getStrategy();
            strategy.execute(context, enhanceSqlEntity);

            if(!(result instanceof ResultDataModel)){//不是查询类的
                continue;
            }
            EnhanceResult enhanceResult = context.getResult();
            if(Func.isEmpty(enhanceResult)){
                continue;
            }

            ResultDataModel listModel = (ResultDataModel)returnVal;
            listModel.setTotal(context.getResult().getTotal());
            listModel.setRecords(context.getResult().getRecords());
            return listModel;
        }

        return returnVal;
    }

    private BuildSqlEnhanceContext getEnhanceContext(LideeyunJiEnhance lideeyunJiEnhance,JoinPoint joinPoint) {
        Map<String, Object> paramMap = super.getJoinPointParam(joinPoint);
        String buttonCode = lideeyunJiEnhance.buttonCode();
        //表单id
        Long dbFormId = (Long) paramMap.get("dbFormId");
        Long dataId = (Long) paramMap.get("id");

        String key = dbFormId + "_" + buttonCode;
        List<EnhanceSqlEntity> sqlEntityList = enhanceMaps.getOrDefault(key, null);
        if (Func.isEmpty(sqlEntityList)) {
            return null;
        }

        Map<String, Object> params = lideeYunJiUtils.getMap2Map(paramMap, "params");

        EnhanceContext context = new EnhanceContext();
        context.setParamMore(dbFormId, params,dataId);
        context.setResult(new EnhanceResult());
        return new BuildSqlEnhanceContext(context, sqlEntityList);
    }

    // 新增增强
    public static void addEnhance(EnhanceSqlEntity sqlEntity) {
        String key = getPluginKey(sqlEntity);
        enhanceMaps.merge(key, new ArrayList<>(Collections.singletonList(sqlEntity)), (oldValue, newValue) -> {
            oldValue.addAll(newValue);
            return oldValue;
        });
    }

    // 修改增强
    public static void updateEnhance(EnhanceSqlEntity sqlEntity) {
        String key = getPluginKey(sqlEntity);
        enhanceMaps.merge(key, new ArrayList<>(Collections.singletonList(sqlEntity)), (oldValue, newValue) -> {
            // 先删除再新增
            oldValue.removeIf(enhanceSql -> FuncBase.equals(enhanceSql.getId(), sqlEntity.getId()));
            oldValue.add(sqlEntity);
            return oldValue;
        });
    }

    // 删除增强
    public static void removeEnhance(EnhanceSqlEntity sqlEntity) {
        String key = getPluginKey(sqlEntity);
        List<EnhanceSqlEntity> sqlEntityList = enhanceMaps.getOrDefault(key, new ArrayList<>());
        // id相同则删除
        sqlEntityList.removeIf(enhanceSqlEntity -> sqlEntity.getId().equals(enhanceSqlEntity.getId()));
        if (FuncBase.isEmpty(sqlEntityList)) {
            enhanceMaps.remove(key);
        }
    }

    private static String getPluginKey(EnhanceSqlEntity sqlEntity){
        String key = sqlEntity.getDbformId() + "_" + sqlEntity.getButtonCode();
        return key;
    }
}
