package com.ibiz.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;

import lombok.Data;

@Data
public class SearchContext implements ISearchContext {

    /**
     * 自定义查询条件
     */
    @JsonProperty("customcond")
	public String customCond;
	/**
     * 自定义查询参数
     */
    @JsonProperty("customparams")
	public String customParams;
	/**
	 * 快速搜索
	 */
    @JsonProperty("query")
	public String query;

	/**
	 * 条件
	 */
	List<SearchFilter> condition = new ArrayList<SearchFilter>() ;

	/**
	 * 上下文参数
	 */
	Map<String,Object> params = new HashMap<String,Object>() ;

    @JsonIgnore
    Pageable pageable = PageRequest.of(0, 20);

    /**
    * 获取数据上下文
    * @return
    */
    public Map<String,Object> getDatacontext() {
    	return params;
    }

    /**
    * 获取网页请求上下文
    * @return
    */
    public Map<String,Object> getWebcontext() {
    	return params;
    }

    /**
	 * 用户上下文参数
	 */
	Map<String,Object> sessionparams = new HashMap<String,Object>() ;
	
    /**
    * 获取用户上下文
    * @return
    */
    public Map<String,Object> getSessioncontext() {
    	return sessionparams;
    }

    @JsonAnyGetter
    public Map<String , Object> any() {
        return params;
    }

    @JsonAnySetter
    public void set(String name, Object value) {
        params.put(name, value);
    }

    /**
     * 解析自定义参数（解析规则1，以 ; 进行词条切割，以 : 进行键值切割）<br>
     * 传入<br>
     *     customParams = "key:value,key:value,key:value;"<br>
     * 返回<br>
     *     map = {key:value,key:value,key:value}
     *
     * @param customParams 自定义参数
     * @return 参数Map
     */
    public Map<String, String> analysisCustomParams1(String customParams) {
        if (customParams == null || customParams.isEmpty()) {
            return null;
        }
        String[] params = customParams.split(",", -1);
        if (params == null || params.length == 0) {
            return null;
        }
        Map<String, String> map = new HashMap<>();
        for (String param : params) {
            if (!param.contains(":")) {
                continue;
            }
            String[] arr = param.split(":", -1);
            if (arr.length != 2) {
                continue;
            }
            map.put(arr[0], arr[1]);
        }
        return map;
    }

}
