package com.bonus.canteen.core.common.page;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bonus.canteen.core.common.utils.JacksonUtil;
import com.fasterxml.jackson.databind.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class QueryParseHelper {
   private static final Logger log = LoggerFactory.getLogger(QueryParseHelper.class);

   public static PageDTO getPageFromContent(String content) {
      PageDTO page = getPageOrNullFromContent(content);
      return page == null ? new PageDTO() : page;
   }

   public static PageDTO getPageOrNullFromContent(String content) {
      PageDTO page = null;
      JsonNode jsonNode = JacksonUtil.readTree(content);
      if (jsonNode != null) {
         page = (PageDTO)JacksonUtil.treeToValue(jsonNode.path("page"), PageDTO.class);
      }

      return page;
   }

   /** @deprecated */
   @Deprecated
   public static <T> Page<T> getPageFromContent(String content, Class<T> clz) {
      Page<T> page = new Page(1L, 10L);
      JsonNode jsonNode = JacksonUtil.readTree(content);
      if (jsonNode != null) {
         page.setCurrent(jsonNode.path("page").path("current").asLong(1L));
         page.setSize(jsonNode.path("page").path("size").asLong(10L));
      }

      return page;
   }

   public static <T> T getParamFromContent(String content, Class<T> clz) {
      T paramDto = null;

      try {
         JsonNode jsonNode = JacksonUtil.readTree(content);
         if (jsonNode != null) {
            JsonNode object = jsonNode.get("object");
            paramDto = JacksonUtil.treeToValue(object, clz);
         }

         if (paramDto == null) {
            paramDto = clz.newInstance();
         }
      } catch (IllegalAccessException | InstantiationException var5) {
         log.error("实例化对象失败", var5);
      }

      return paramDto;
   }

   public static <T> T getParamFromContentOrNull(String content, Class<T> clz) {
      T paramDto = null;
      JsonNode jsonNode = JacksonUtil.readTree(content);
      if (jsonNode != null) {
         JsonNode object = jsonNode.get("object");
         paramDto = JacksonUtil.treeToValue(object, clz);
      }

      return paramDto;
   }

   public static JsonNode getNodeFromContent(String content, String expression) {
      JsonNode node = JacksonUtil.readTreeOrMissing(content);
      return JacksonUtil.getByPath(node, expression);
   }

   public static <T> T getValueFromContent(String content, String expression, Class<T> clz) {
      JsonNode node = JacksonUtil.readTreeOrMissing(content);
      JsonNode nodeByPath = JacksonUtil.getByPath(node, expression);
      return JacksonUtil.treeToValue(nodeByPath, clz);
   }

   public static <T> T getValueFromContent(String content, String expression, T defaultValue) {
      return JacksonUtil.getValueByPath(content, expression, defaultValue);
   }
}
