package com.sagacloud.endpoints;

import com.sagacloud.dict.TableMap;
import com.alibaba.fastjson.*;
import com.sagacloud.utils.CommonUtil;
import com.sagacloud.utils.Const;
import com.sagacloud.utils.DpUtils;
import com.sagacloud.utils.ZillionAgentProvider;
import com.sagacloud.utils.tables.ObjectTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.util.Arrays;

@Path("dynamic_data")
public class DynamicData {
    private static final Logger log = LoggerFactory.getLogger(DynamicData.class);

    @Path("/query")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String query(@QueryParam(Const.PROJECT_ID) String projectId, String jsonStr) {
        JSONObject criteriaNode = JSONObject.parseObject(jsonStr).getJSONObject("criteria");
        if(!criteriaNode.containsKey("building")) {
            criteriaNode.put("building", projectId.substring(2));
        }
        if (criteriaNode.get("id")==null || criteriaNode.get("code")==null||criteriaNode.get("data_time")==null)
            return DpUtils.errorJsonMsg("json格式错误");

        boolean queryMax;
        if(criteriaNode.containsKey("max")&&criteriaNode.get("max")!=null) {
            queryMax = (Boolean) criteriaNode.get("max");
        }else {
            queryMax = false;
        }
        criteriaNode.remove("max");
        JSONObject idNode = new JSONObject();
        String id = (String) criteriaNode.get("id");
        String code = (String) criteriaNode.get("code");
        idNode.put("id", id);
        criteriaNode.remove("id");
        criteriaNode.remove("code");

        try {
            DpUtils.rewriteCriteria(idNode, "id", true);
            String type = idNode.get(ObjectTable.KEY_OBJ_TYPE).toString();
            if (type.startsWith("EqOTSE") && TableMap.getTableName("EqOTSE", code) != null) {
                String tableName = TableMap.getTableName("EqOTSE", code);
                if(queryMax)
                    tableName = tableName + "_max";
                return query(TableMap.getNamespace("EqOTSE", code), tableName, criteriaNode).toString();

            }else if(type.startsWith("Eq") && TableMap.getTableName("Eq", code) != null){
                String tableName = TableMap.getTableName("Eq", code);
                if(queryMax)
                    tableName = tableName + "_max";
                return query(TableMap.getNamespace("Eq", code), tableName, criteriaNode).toString();

            }else if(TableMap.getTableName(type, code) != null){
                String tableName = TableMap.getTableName(type, code);
                if(queryMax)
                    tableName = tableName + "_max";
                return query(TableMap.getNamespace(type, code), tableName, criteriaNode).toString();

            }else{
                //1.查询信息点内容
                Object info = CommonUtil.getInfoById(projectId.substring(2, 12), id,code);
                if(info == null){
                    return DpUtils.errorJsonMsg("该信息点不存在！Assigned code does not exist！");
                }
                if(info instanceof JSONObject){
                    criteriaNode.put("meter",((JSONObject) info).get("meter"));
                    criteriaNode.put("funcid",((JSONObject) info).get("func-id"));
                }else{//String
                    String meter = ((String) info).substring(0,((String) info).lastIndexOf("-"));
                    String funcId = ((String) info).substring(((String) info).lastIndexOf("-")+1);
                    criteriaNode.put("meter",meter);
                    criteriaNode.put("funcid",Long.parseLong(funcId));
                }
                criteriaNode.put("receivetime",criteriaNode.get("data_time"));
                criteriaNode.remove("data_time");
                JSONObject re = query("db_public","originaldata",criteriaNode);

                return re.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(Arrays.toString(e.getStackTrace()));
            return DpUtils.errorJsonMsg("查询出错");
        }
    }

    private static JSONObject query(String database, String table, JSONObject criteria) throws Exception {
        JSONObject json = JSONObject.parseObject("{\"QueryType\":\"select\"}");
        json.put("Database", database);
        json.put("Datatable", table);
        json.put("Criteria", criteria);
//        return json;
        return ZillionAgentProvider.GetAgent().Query(json);
    }
}
