package com.ag.redis;

import com.ag.base.IRedisService;
import com.ag.secp.platform.spring.SpringApplicationContext;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wb.common.KvBean;
import com.wb.util.WebUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/** @Description: 手动获取键值 keyname
* @author: fengjun
* @Date: 2023/2/15
*/
public class WbKeyNameUtil {

    /** @Description: 获取keyname 数组
    * @return: void
    * @author: fengjun
    * @Date: 2023/2/15
    */
    public static void getKeyName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String keyName = request.getParameter("keyName");
        String type = request.getParameter("type");
        IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
        List<KvBean> allByKey = service.getAllByKey(keyName);
        if ("array".equals(type)) {
            JSONArray array = new JSONArray();
            allByKey.stream().map(k->{
                JSONObject object = new JSONObject();
                object.put("label",k.getV());
                object.put("value",k.getK());
                return object;
            }).forEach(array::add);
            WebUtil.send(response,array);
            return;
        }
        JSONObject object = new JSONObject();
        allByKey.forEach(k-> object.put(k.getK(),k.getV()));
        WebUtil.send(response,object);
    }

}
