package com.pictc.jdbc.model;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pictc.jdbc.model.Criteria.DataType;
import com.pictc.jdbc.model.Criteria.Type;
import com.pictc.utils.CollectionUtils;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

@ApiModel
@Accessors(chain = true)
@Data
public class QueryParameter implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String queryId;
	
	private Class<?> entityClass; //实体类型
	
	@ApiModelProperty(name = "实体对象，会已eq方式转为查询条件")
	private JSONObject data;
	
	@ApiModelProperty(name = "where条件")
	private List<CriteriaGroup> criterias;	
	
	@ApiModelProperty(name = "排序配置")
	private List<QueryOrder> orders;
	
	@ApiModelProperty(name = "查询指定列")
	private Set<String> froms;
	
	private int index;
	
	private int size;
	
	private boolean page;
	
	@ApiModelProperty(hidden = true)
	public List<CriteriaGroup> getAllCriterias(){
		List<CriteriaGroup> res = null;
		if(criterias!=null) {
			res = CollectionUtils.newArrayList();
			for (CriteriaGroup group : criterias) {
				res.add(group);
			}
		}
		
		if(data!=null && !data.isEmpty()) {
			if(res==null) {
				res = CollectionUtils.newArrayList();
			}
			res.add(objToCriteria(data));
		}
		return res;
	}
	
	private CriteriaGroup objToCriteria(JSONObject pojo) {
		CriteriaGroup group = new CriteriaGroup();
		for (String key : pojo.keySet()) {
			Object val = pojo.get(key);
			if(val==null || val instanceof JSONObject || val instanceof JSONArray) {
				continue;
			}else {
				JdbcType type = JdbcType.valueOf(val.getClass());
				DataType dtype = DataType.STRING;
				if(type.isDecimal()) {
					dtype = DataType.DOUBLE;
				}else if(type.isDate()) {
					dtype = DataType.DATE;
				}
				group.add(new Criteria().setType(Type.EQ).setVal(val).setDataType(dtype).setField(key));
			}
		}
		return group;
	}
}
