package com.dgtly.common.core.domain;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dgtly.common.config.BodyReaderHttpServletRequestWrapper;
import com.dgtly.common.exception.api.LessParamException;
import com.dgtly.common.utils.ServletUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

public class ParameterObject {

    private JSONObject jsonObject;

    public ParameterObject(HttpServletRequest request){
        BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
        String data = requestWrapper.getJson();
        if(data!=null&&!data.trim().equals("")){
            jsonObject =  JSONObject.parseObject(data);
        }
    }

    public <T> T parseBean(Class<T> clazz){
        if(jsonObject!=null){
            return JSON.parseObject(jsonObject.toJSONString(), clazz);
        }else{
            return null;
        }
    }



    public JSONObject getJSONObject(String key){
        if(jsonObject!=null){
            return jsonObject.getJSONObject(key);
        }else{
            return null;
        }
    }
    public JSONObject getJSONObject(){
        if(jsonObject!=null){
            return jsonObject;
        }else{
            return null;
        }
    }



    public String getString(String key){
        if(jsonObject!=null){
            return jsonObject.getString(key);
        }else{
            return null;
        }
    }

    public Long getLong(String key){
        if(jsonObject!=null){
            return jsonObject.getLong(key);
        }else{
            return null;
        }
    }

    public Object getObject(String key){
        if(jsonObject!=null){
            return jsonObject.get(key);
        }else{
            return null;
        }
    }

    public Boolean getBoolean(String Key){
        if (jsonObject!=null){
            return jsonObject.getBoolean(Key);
        }else {
            return null;
        }
    }

    public void checkParameterNotNull(String fieldNames){
        if(jsonObject!=null){
            String[] fieldList = fieldNames.split(",");
            List<String> list = Arrays.asList(fieldList);
            for(String field:list){
                if(!jsonObject.containsKey(field)){
                    throw new LessParamException("缺少字段:"+field);
                }
            }
        }
    }

    public <T> List<T> getList(String key,Class<T> clazz){
        if(jsonObject!=null){
            return jsonObject.getJSONArray(key).toJavaList(clazz);
        }else{
            return null;
        }
    }


    public Boolean contaonsKey(Object key){
        return jsonObject.containsKey(key);
    }

}
