package com.liangjian.dataplatform.member.util.dynamic;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by huangziqi on 2019/12/17
 *
 * 用于解析request带上来的参数
 */
public class DynamicParamsWorker {

    public static DynamicParams analyze(HttpServletRequest request) {
        Map<String,String[]> queryMap = request.getParameterMap();
        DynamicParams params = new DynamicParams();
        Map<String,DynamicFilter> filterMap = new HashMap<>();
        Map<String,OperateType> operateTypeMap = new HashMap<>();
        queryMap.forEach((k,v) -> {
            if(k.endsWith("Operate")) {
                //这个param是一个operate的param
                var key = k.replace("Operate","");
                OperateType type = OperateType.valueOf(v[0]);
                operateTypeMap.put(key,type);
            } else {
                if (k.equals("page")) {
                    params.page = Integer.valueOf(v[0]);
                } else if (k.equals("size")) {
                    params.size = Integer.valueOf(v[0]);
                } else if(k.equals("sortDirection")) {
                    params.sortDirection = SortDirection.valueOf(v[0]);
                } else if(k.equals("sortField")) {
                    params.sortField = v[0];
                } else {
                    DynamicFilter filter = new DynamicFilter();
                    filter.field = k;
                    filter.operate = OperateType.Equal; //默认使用Equal
                    filter.value = v[0];
                    filterMap.put(k,filter);
                }
            }
        });
        operateTypeMap.forEach((k,v) -> {
            filterMap.get(k).setOperate(v);
        });
        params.filters = new ArrayList<>(filterMap.values());
        return params;
    }
}
