package com.sagacloud.endpoints;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sagacloud.dict.EqStaticInfo;
import com.sagacloud.endpoints.item.PhysicalObject;
import com.sagacloud.utils.Const;
import com.sagacloud.utils.DpUtils;
import com.sagacloud.utils.InfoCodeUtil;
import com.sagacloud.utils.OssUtils;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Path("infocode")
public class InfoCode {
    @Context
    private ResourceContext resourceContext;
    //	public static Hashtable<String, JSONArray> infoCodeMap = new Hashtable<>();
    public static String returnJson = "{\"Result\": \"success\", \"Content\": [],\"ResultMsg\": \"\" }";

    @Path("/query/project")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String queryProject(@QueryParam("enrich") Boolean enrich) {
        try {
            JSONArray content = InfoCodeUtil.getInfosForProperty(null, "project");
            JSONObject json = JSONObject.parseObject(returnJson);
            json.put("Content", content);
            if (enrich != null && enrich) {
                return enrich(json.toString());
            }
            return json.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(Arrays.toString(ex.getStackTrace()));
        }
    }

    @Path("/query/building")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String queryBuilding(@QueryParam("enrich") Boolean enrich) {
        try {
            JSONArray content = InfoCodeUtil.getInfosForProperty(null, "building");
            JSONObject json = JSONObject.parseObject(returnJson);
            json.put("Content", content);
            if (enrich != null && enrich) {
                return enrich(json.toString());
            }
            return json.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(Arrays.toString(ex.getStackTrace()));
        }
    }

    @Path("/query/floor")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String queryFloor(@QueryParam("enrich") Boolean enrich) {
        try {
            JSONArray content = InfoCodeUtil.getInfosForProperty(null, "floor");
            JSONObject json = JSONObject.parseObject(returnJson);
            json.put("Content", content);
            if (enrich != null && enrich) {
                return enrich(json.toString());
            }
            return json.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(Arrays.toString(ex.getStackTrace()));
        }
    }

    @Path("/query/space")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String querySpace(@QueryParam("enrich") Boolean enrich) {
        try {
            JSONArray content = InfoCodeUtil.getInfosForProperty(null, "space");
            JSONObject json = JSONObject.parseObject(returnJson);
            json.put("Content", content);
            if (enrich != null && enrich) {
                return enrich(json.toString());
            }
            return json.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(Arrays.toString(ex.getStackTrace()));
        }
    }

    @Path("/query/system-general")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String querySystemGeneral(@QueryParam("enrich") Boolean enrich) {
        try {
            JSONArray content = InfoCodeUtil.getInfosForProperty(null, "sy-gen");
            JSONObject json = JSONObject.parseObject(returnJson);
            json.put("Content", content);
            if (enrich != null && enrich) {
                return enrich(json.toString());
            }
            return json.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(Arrays.toString(ex.getStackTrace()));
        }
    }

    @Path("/query/equipment-general")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String queryEquipmentGeneral(@QueryParam("enrich") Boolean enrich) {
        try {
            JSONArray content = InfoCodeUtil.getInfosForProperty(null, "eq-gen");
            JSONObject json = JSONObject.parseObject(returnJson);
            json.put("Content", content);
            if (enrich != null && enrich) {
                return enrich(json.toString());
            }
            return json.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(Arrays.toString(ex.getStackTrace()));
        }
    }

    @Path("/query/component-general")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String queryComponentGeneral(@QueryParam("enrich") Boolean enrich) {
        try {
            JSONArray content = InfoCodeUtil.getInfosForProperty(null, "ec-gen");
            JSONObject json = JSONObject.parseObject(returnJson);
            json.put("Content", content);
            if (enrich != null && enrich) {
                return enrich(json.toString());
            }
            return json.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(Arrays.toString(ex.getStackTrace()));
        }
    }

    @Path("/query")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String queryEquipment(@QueryParam(Const.PROJECT_ID) String projectId, @QueryParam("ID") String ID, @QueryParam("enrich") Boolean enrich) {
        if(projectId == null && OssUtils.getProperty("default.project.id") != null){
            projectId = OssUtils.getProperty("default.project.id");
        }
        try {
            JSONArray content = InfoCodeUtil.getInfosForProperty(projectId, ID);
            JSONObject json = JSONObject.parseObject(returnJson);
            json.put("Content", content);
            if (enrich != null && enrich) {
                return enrich(json.toString());
            }
            return json.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(Arrays.toString(ex.getStackTrace()));
        }
    }

    @Path("/query_whole")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String queryWhole(@QueryParam(Const.PROJECT_ID) String projectId, @QueryParam("ID") String ID, @QueryParam("enrich") Boolean enrich) {
        if(projectId == null && OssUtils.getProperty("default.project.id") != null){
            projectId = OssUtils.getProperty("default.project.id");
        }
        try {
            JSONArray content = InfoCodeUtil.getInfosForProperty(projectId, ID);
            JSONObject json = JSONObject.parseObject(returnJson);
            json.put("Content", content);
            if (enrich != null && enrich) {
                return enrich(json.toString());
            }
            return json.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(Arrays.toString(ex.getStackTrace()));
        }
    }

    @Path("/query_all")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String queryAll(@QueryParam(Const.PROJECT_ID) String projectId) {
        if(projectId == null && OssUtils.getProperty("default.project.id") != null){
            projectId = OssUtils.getProperty("default.project.id");
        }
        try {
            //加入了种族信息点
            JSONObject result = new JSONObject();
//            result.put("project", InfoCodeUtil.getInfosForProperty("project"));
//            result.put("building", InfoCodeUtil.getInfosForProperty("building"));
//            result.put("floor", InfoCodeUtil.getInfosForProperty("floor"));
//            result.put("space", InfoCodeUtil.getInfosForProperty("space"));
//            result.put("sy-gen", InfoCodeUtil.getInfosForProperty("sy-gen"));
//            result.put("eq-gen", InfoCodeUtil.getInfosForProperty("eq-gen"));
//            result.put("ec-gen", InfoCodeUtil.getInfosForProperty("ec-gen"));
//
//            for (String cate : EqStaticInfo.eqSet) {
//                result.put(cate, InfoCodeUtil.getInfosForProperty(cate));
//            }
//            for (String cate : EqStaticInfo.sysSet) {
//                result.put(cate, InfoCodeUtil.getInfosForProperty(cate));
//            }
//            for (String cate : EqStaticInfo.ecSet) {
//                result.put(cate, InfoCodeUtil.getInfosForProperty(cate));
//            }
//            for (String cate : EqStaticInfo.familySet) {
//                result.put(cate, InfoCodeUtil.getInfosForProperty(cate));
//            }
            Set<String> tmpSet = new HashSet<>(InfoCodeUtil.objTypeSet);
            EqStaticInfo eqStaticInfo = new EqStaticInfo(projectId);
            tmpSet.addAll(eqStaticInfo.getEcSet());
            tmpSet.addAll(eqStaticInfo.getEqSet());
            tmpSet.addAll(eqStaticInfo.getSysSet());
            
            String ctmDictId = InfoCodeUtil.queryDictId(projectId);
            for (String key : tmpSet) {
                result.put(key, InfoCodeUtil.getInfosForProperty(projectId, key, ctmDictId));
            }
            return result.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return new JSONObject().toString();
        }

    }

    @Path("/complex_query")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String complexQuery(@QueryParam("projectId") String projectId, @QueryParam("type") String type,
                               @QueryParam("combine") Boolean combine, @QueryParam("enrich") Boolean enrich) {
        if ("space".equals(type)) {
            type = "GeneralZone";
        }

        try {
            JSONArray content;
            if (projectId == null) {
                content = InfoCodeUtil.getInfosForProperty(projectId, type);
            } else {
                projectId = projectId.substring(2);
                if (combine == null || combine) {
                    content = InfoCodeUtil.queryWholeInfosWithCustom(projectId, type);
                } else {
                    content = InfoCodeUtil.queryCustomInfos(projectId, type);
                }
            }
            JSONObject json = JSONObject.parseObject(returnJson);
            json.put("Content", content);
            if (enrich != null && enrich) {
                return enrich(json.toString());
            }
            return json.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(Arrays.toString(ex.getStackTrace()));
        }
    }

    @Path("/business_space_type/query")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String queryBusinessSpaceType() {
        try {
            JSONArray arr = new JSONArray();
            int i = 0;
            JSONObject lastPointer = null;
            for (String code : PhysicalObject.bussinessSpaceTypeMap.keySet()) {
                lastPointer = new JSONObject();
                lastPointer.put("name", PhysicalObject.bussinessSpaceTypeMap.get(code));
                lastPointer.put("code", code);
                lastPointer.put("rel_type", ++i + "");
                arr.add(lastPointer);
            }
            lastPointer.put("rel_type", "99");
            return DpUtils.returnJSONArray(arr, "");
        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(Arrays.toString(ex.getStackTrace()));
        }
    }

    @Path("/query_property")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String queryProperty(@QueryParam("projectId") String projectId, @QueryParam("type") String type, @QueryParam("enrich") Boolean enrich) {
        if(projectId == null && OssUtils.getProperty("default.project.id") != null){
            projectId = OssUtils.getProperty("default.project.id");
        }
        if ("space".equals(type)) {
            type = "GeneralZone";
        }

        try {
            JSONArray content = InfoCodeUtil.getInfosForProperty(projectId, type);

//            InfoCodeUtil.sortByTag(content);
            JSONObject json = JSONObject.parseObject(returnJson);
            json.put("Content", content);
            if (enrich != null && enrich) {
                return enrich(json.toString());
            }
            return json.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(Arrays.toString(ex.getStackTrace()));
        }
    }

    private String enrich(String jsonStr) {
        org.json.JSONObject reJson = new org.json.JSONObject(jsonStr);
        org.json.JSONArray items = reJson.getJSONArray("Content");
        for (int i = 0; i < items.length(); i++) {
            org.json.JSONObject item = items.getJSONObject(i);
            if (!(item.opt("dataSource") instanceof String)) {
                continue;
            }
            String dataSource = item.getString("dataSource");
            org.json.JSONObject json = null;
            if (dataSource.contains("省市区代码")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).queryGeography());
            } else if (dataSource.contains("气候区代码")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).queryClimate());
            } else if (dataSource.contains("天气状态")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).queryWeatherCondition());
            } else if (dataSource.contains("空气风力等级")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).queryWind());
            } else if (dataSource.contains("方向代码")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).queryDirection());
            } else if (dataSource.contains("建筑功能类型")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).queryBuildingFunction());
            } else if (dataSource.contains("空间功能类型")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).querySpaceFunction());
            } else if (dataSource.contains("租赁业态类型")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).queryRental());
            } else if (dataSource.contains("防尘等级")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).queryDustproof());
            } else if (dataSource.contains("防水等级")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).queryWaterproof());
            } else if (dataSource.contains("防爆设备类型")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).queryExplosionproofEquipment());
            } else if (dataSource.contains("防爆型式")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).queryExplosionType());
            } else if (dataSource.contains("危险区域等级")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).queryDanger());
            } else if (dataSource.contains("气体类型") || dataSource.contains("温度类型")) {
                json = new org.json.JSONObject(resourceContext.getResource(Dictionary.class).queryExplosionproofGasAndTemperature());
            }
            item.put("dataSourceStr", dataSource);
            item.remove("dataSource");
            if (json != null) {
                item.put("dataSource", json.get("Content"));
            }
        }
        return reJson.toString();

    }

//    @Path("/test")
//    @GET
//    @Produces(MediaType.APPLICATION_JSON)
//    public static String test(@QueryParam("type") String type){
//
//        HashMap<String, HashMap<String, InfoPoint>> map2 = InfoCodeUtil.getAllCustomInfosByType(type);
//        System.out.println("finish");
//        return "finish";
//    }

    @Path("/query/project")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String queryProjectPost(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Boolean enrich = jsonObject.getBoolean("enrich");
        return queryProject(enrich);
    }

    @Path("/query/building")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String queryBuildingPost(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Boolean enrich = jsonObject.getBoolean("enrich");
        return queryBuilding(enrich);
    }

    @Path("/query/floor")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String queryFloorPost(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Boolean enrich = jsonObject.getBoolean("enrich");
        return queryFloor(enrich);
    }

    @Path("/query/space")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String querySpacePost(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Boolean enrich = jsonObject.getBoolean("enrich");
        return querySpace(enrich);
    }

    @Path("/query/system-general")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String querySystemGeneralPost(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Boolean enrich = jsonObject.getBoolean("enrich");
        return querySystemGeneral(enrich);
    }

    @Path("/query/equipment-general")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String queryEquipmentGeneralPost(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Boolean enrich = jsonObject.getBoolean("enrich");
        return queryEquipmentGeneral(enrich);
    }

    @Path("/query/component-general")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String queryComponentGeneralPost(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Boolean enrich = jsonObject.getBoolean("enrich");
        return queryComponentGeneral(enrich);
    }

    @Path("/query")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String queryEquipmentPost(@QueryParam(Const.PROJECT_ID) String projectId, String jsonStr) {
        if(projectId == null && OssUtils.getProperty("default.project.id") != null){
            projectId = OssUtils.getProperty("default.project.id");
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String ID = jsonObject.getString("ID");
        Boolean enrich = jsonObject.getBoolean("enrich");
        return queryEquipment(projectId, ID, enrich);
    }

    @Path("/query_whole")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String queryWholePost(@QueryParam(Const.PROJECT_ID) String projectId, String jsonStr) {
        if(projectId == null && OssUtils.getProperty("default.project.id") != null){
            projectId = OssUtils.getProperty("default.project.id");
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String ID = jsonObject.getString("ID");
        Boolean enrich = jsonObject.getBoolean("enrich");
        return queryWhole(projectId, ID, enrich);
    }

    @Path("/query_all")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String queryAllPost(@QueryParam(Const.PROJECT_ID) String projectId) {
        if(projectId == null && OssUtils.getProperty("default.project.id") != null){
            projectId = OssUtils.getProperty("default.project.id");
        }
        return queryAll(projectId);
    }

    @Path("/complex_query")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String complexQueryPost(@QueryParam("projectId") String projectId, String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String type = jsonObject.getString("type");
        Boolean combine = jsonObject.getBoolean("combine");
        Boolean enrich = jsonObject.getBoolean("enrich");
        return complexQuery(projectId, type, combine, enrich);
    }

    @Path("/business_space_type/query")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String queryBusinessSpaceTypePost() {
        return queryBusinessSpaceType();
    }

    @Path("/query_property")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String queryPropertyPost(@QueryParam("projectId") String projectId, String jsonStr) {
        if(projectId == null && OssUtils.getProperty("default.project.id") != null){
            projectId = OssUtils.getProperty("default.project.id");
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String type = jsonObject.getString("type");
        Boolean enrich = jsonObject.getBoolean("enrich");
        return queryProperty(projectId, type, enrich);
    }
}
