package common.interceptor.empty;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import common.utils.http.MyController;
import common.utils.http.MyRet;

public class EmptyInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation inv) {
        EmptyInterface annotation = inv.getMethod().getAnnotation(EmptyInterface.class);

        if (annotation == null) {
            inv.invoke();
        } else {
            String[] keyArray = annotation.value();
            Controller controller = inv.getController();
            JSONObject paramsModel = MyController.getJsonModelByRequestAndType(controller.getRequest(), JSONObject.class);

            if (isNotEmpty(paramsModel, keyArray)) {
                inv.invoke();
            } else {
                String errorMsgBuilder = "参数必须包含: " +
                        EmptyInterceptor.formatParams(keyArray) +
                        ", 返回值的 'data' 是你发过来的参数.";

                controller.renderJson(MyRet.fail(errorMsgBuilder).setData(paramsModel));
            }
        }
    }

    private boolean isNotEmpty(JSONObject paramsModel, String[] keyArray) {
        if (paramsModel == null) {
            return false;
        }
        
        for (String key : keyArray) {
            if (StrKit.isBlank(paramsModel.getString(key))) {
                return false;
            }
        }

        return true;
    }

    public static String formatParams(String[] keyArray) {
        StringBuilder builder = new StringBuilder();

        builder.append('[');
        for (int i = 0; i < keyArray.length; i++) {
            String key = keyArray[i];

            builder.append(key);

            if (i < keyArray.length - 1) builder.append(',');
        }
        builder.append(']');

        return builder.toString();
    }
}
