package com.wb.common;

import cn.hutool.core.convert.Convert;
import com.ag.base.IRedisService;
import com.ag.secp.platform.spring.SpringApplicationContext;
import com.ag.util.StrUtil;
import com.ag.util.WbStoreJson;
import com.wb.util.WebUtil;

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

/**
 * Created by Administrator on 2017/4/17.
 */
public class CodeBuffer {

    /**
     * redis筛选
     * 实现待重写(21/03/30完成重写)
     */
    public static void filter(HttpServletRequest request, HttpServletResponse response) {


        IRedisService service = (IRedisService) SpringApplicationContext.getBean("redisServiceImpl");
        String fldId = request.getParameter("fldId");
        String start = request.getParameter("start");
        String limit = request.getParameter("limit");
        String filterName =  request.getParameter("query");
        String tenancyId = WebUtil.fetch(request, "sys.tenancyId");
        List<KvBean> kvBeanList = null;
        if (StrUtil.isEmpty(start) || StrUtil.isEmpty(limit)) {
            kvBeanList = service.likeByKey(fldId, filterName, tenancyId, 0, 1000);
        } else {
            kvBeanList = service.likeByKey(fldId, filterName, tenancyId, Convert.toInt(start), Convert.toInt(limit));
        }
        if (kvBeanList == null){
            kvBeanList = new ArrayList<>();
        }
        try {
            response.setContentType("text/xml;charset=UTF-8");
            PrintWriter pw = response.getWriter();
            //System.out.println(getJson( kvBeanList));
            pw.print(getJson( kvBeanList));
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getJson(List<KvBean> list) {
        List<WbStoreJson.RedisJsonStr> redisJsonStrs = new ArrayList<>(list.size());
        for (KvBean kvBean : list) {
            WbStoreJson.RedisJsonStr jsonStr = new WbStoreJson.RedisJsonStr();
            jsonStr.setId(kvBean.getK());
            jsonStr.setCname(kvBean.getV());
            jsonStr.setEname(kvBean.getComv());
            jsonStr.setWname(kvBean.getComv2());
            jsonStr.setTenancyId(kvBean.getTenancyId());
            jsonStr.setKeyName(kvBean.getKeyName());
            redisJsonStrs.add(jsonStr);
        }
        WbStoreJson wb = new WbStoreJson();
        wb.generate(redisJsonStrs, WbStoreJson.RedisJsonStr.class);
        return wb.getJsonStr(wb);
    }
}
