package com.wb.common;

import com.wb.util.DbUtil;
import com.wb.util.StringUtil;
import com.wb.util.WebUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Administrator on 2017/4/17.
 */
public class CodeBuffer {
    private static ArrayList<String> str = new ArrayList<String>();
    private static ArrayList<String> Sql = new ArrayList<String>();

    /**
     * 键值数据缓存。
     */
    public static ConcurrentHashMap<String, List<Code>> buffer;


    public static void getkeyvalue(HttpServletRequest request, HttpServletResponse response) {

        String key = request.getParameter("key");
        String value = request.getParameter("value");

        String result = "";

        ConcurrentHashMap<Object, String> map = KVBuffer.buffer.get(key);
        Set<Map.Entry<Object, String>> es = map.entrySet();
        for (Map.Entry<Object, String> e : es) {
            Object K=e.getKey();
            String keytemp="";
            if (K instanceof Integer){
                keytemp=Integer.toString((Integer) K);
            }else{
                keytemp=StringUtil.quote((String) K);
            }

            if (keytemp.equals(value)) {

                result = e.getValue();
                break;
            }
        }
        try {
            WebUtil.send(response, result);//将修改数据同步返回表格
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * ??????
     *
     * @param request
     * @param response
     */
    public static void filter(HttpServletRequest request, HttpServletResponse response) {
        String fldId = request.getParameter("fldId");
        String name = request.getParameter("name");
        String start = request.getParameter("start");
        String limit = request.getParameter("limit");
        String tenancyId = request.getParameter("TENANCY_ID");//租户
        tenancyId = StringUtil.isEmpty(tenancyId) ? "@@@" : tenancyId;
        String PARID = request.getParameter("parId");//父节点过滤
        PARID = StringUtil.isEmpty(PARID) ? "@@@" : PARID;
        Map m = request.getParameterMap();
        String filterName = null;
        // if(name!=null&&!name.equals(""))
        filterName = request.getParameter("query");// ????
        List<Code> list2 = buffer.get(fldId);// ????
        List<Code> listNew = new ArrayList<Code>();
        int size = 0;
        if (list2 != null) {
            size = list2.size();
            if (start == null && filterName == null) {// ???????
                listNew = list2;
            } else if (start != null) {// ?????
                int j = 0;
                for (int i = 0; i < size; i++) {
                    if (compareCode(list2.get(i), PARID, filterName, tenancyId)) {
                        if (Integer.parseInt(start) <= j
                                && Integer.parseInt(start)
                                + Integer.parseInt(limit) > j)
                            listNew.add(list2.get(i));
                        j++;
                    }
                }
                size = j;
            } else if (start == null && filterName != null) {// ??????
                for (int i = 0; i < size; i++) {
                    if (list2.get(i).getcName().contains(filterName) || list2.get(i).geteName().contains(filterName) || list2.get(i).getSysCod().contains(filterName)) {
                        listNew.add(list2.get(i));
                    }
                }
                size = listNew.size();
            }
        } else {
            listNew = null;
        }
        try {
            response.setContentType("text/xml;charset=UTF-8");
            PrintWriter pw = response.getWriter();
            pw.print(getJson(size, listNew, "EN"));
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getJson(int s, List<Code> list, Object language) {
        List<Code> listnew = list;
        int size = 0;
        if (list != null)
            size = list.size();
        String styr = "{total:2,metaData:{totalProperty:\"total\",root:\"row\",fields:[{name:\"ID\",type:\"string\"},"
                + "{name:\"NAME\",type:\"string\"}]},"
                + "row:[{\"ID\":\"ATSTA\",\"NAME\":\"STAINACH\"},{\"ID\":\"ATSTC\",\"NAME\":\"STOCKERAU\"}]} ";
        StringBuffer str = new StringBuffer(
                "{total:"
                        + s
                        + ","
                        + "metaData:{"
                        + "totalProperty:\"total\",root:\"row\","
                        + "fields:["
                        + "{name:\"ID\",type:\"string\"},"
                        + "{name:\"CNAME\",type:\"string\"},{name:\"ENAME\",type:\"string\"},{name:\"TENANCY_ID\",type:\"string\"}]},"
                        + "row:[");
        for (int i = 0; i < size; i++) {
            if (i != size - 1)
                str.append("{\"ID\":\"" + listnew.get(i).getSysCod()
                        + "\",\"CNAME\":\"" + listnew.get(i).getcName()
                        + "\",\"ENAME\":\"" + listnew.get(i).geteName()
                        + "\",\"TENANCY_ID\":\"" + listnew.get(i).getTentantId() + "\"},"
                );
            else
                str.append("{\"ID\":\"" + listnew.get(i).getSysCod()
                        + "\",\"CNAME\":\"" + listnew.get(i).getcName()
                        + "\",\"ENAME\":\"" + listnew.get(i).geteName()
                        + "\",\"TENANCY_ID\":\"" + listnew.get(i).getTentantId() + "\"}"
                );
        }
        str.append("]} ");
        //System.out.println(str.toString());
        return str.toString();
    }

    /**
     * 加载和初始化。
     */
    public static synchronized void load() {
        buffer = new ConcurrentHashMap<String, List<Code>>();
        for (int i = 0; i < str.size(); i++) {
            loadWbKey(str.get(i), Sql.get(i));
        }
    }

    /**
     * 加载和初始化
     *
     * @param l1
     * @param l2
     */
    public static synchronized void load(List<String> l1, List<String> l2) {
        buffer = new ConcurrentHashMap<String, List<Code>>();
        for (int i = 0; i < l1.size(); i++) {
            loadWbKey(l1.get(i), l2.get(i));
        }
    }

    //不同数据源 加载对应CODE 放入wbKey中
    public static void loadWbKey(String Jndi, String sql) {
        try {
            Connection conn = null;
            Statement st = null;
            ResultSet rs = null;
            String K, keyName = null, preKeyName = null;
            List<Code> list = new ArrayList<Code>();
            try {
                conn = DbUtil.getConnection(Jndi);
                st = conn.createStatement();
                rs = st.executeQuery(sql);
                while (rs.next()) {
                    keyName = rs.getString("KEY_NAME");
                    if (preKeyName != null && !preKeyName.equals(keyName)) {
                        buffer.put(preKeyName, list);
                        list = new ArrayList<Code>();
                    }
                    Code code = new Code();
                    code.setFldId(keyName);
                    code.setFldNam(rs.getString("KEY_NAME"));
                    code.setSysCod(rs.getString("K"));// 代码主键
                    code.setcName(rs.getString("V"));// 代码中文名
                    code.seteName(rs.getString("V"));// 代码英文名
                    code.setComNam1(rs.getString("COMV"));// comName
                    code.setComNam2(rs.getString("COMV2"));// comName
                    //code.setTentantId( rs.getString("TENANCY_ID"));// ??????????
                    //code.setParId( rs.getString("PARID"));// ??????????
                    list.add(code);
                    preKeyName = keyName;
                }
                if (preKeyName != null)
                    buffer.put(preKeyName, list);
            } finally {
                DbUtil.close(rs);
                DbUtil.close(st);
                DbUtil.close(conn);
            }
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 获取指定键对应的值。
     *
     * @param map     键值对照map。
     * @param request 请求对象，用于多国语言支持。
     * @param key     键。
     * @return 键对应的字符串值。
     */
    private static String getValue(ConcurrentHashMap<?, ?> map,
                                   HttpServletRequest request, Object key) {
        Object value;
        String str;

        if (key instanceof Number)
            value = map.get(((Number) key).intValue());
        else
            value = map.get(key.toString());
        if (value == null)
            return key.toString();
        str = value.toString();
        if (str.startsWith("@Str."))
            return Str.format(request, str.substring(5));
        else
            return str;
    }

    /**
     * 获取指定键对应的值。
     *
     * @param parId      父节点。
     * @param filterName 模糊查询。
     * @return boolean。
     */
    private static boolean compareCode(Code code, String parId, String filterName, String tentantId) {
        boolean parBool = true, tentBool = true, filterBool = true;
        if (!parId.equals("@@@"))//???????????
            parBool = code.getComNam2().equals(parId);
        if (!tentantId.equals("@@@"))//?????????
            tentBool = code.getTentantId().equals(tentantId);
        if (!StringUtil.isEmpty(filterName))//???????
        {
            filterBool = code.getcName().contains(filterName) || code.geteName().contains(filterName) || code.getSysCod().contains(filterName);
        }
        return filterBool && parBool && tentBool;


    }

}
