package com.gic.haoban.manage.web.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.gic.api.base.commons.Page;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.HttpClient;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.marketing.api.exception.ErrmsgException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据组http接口调用工具类
 * @Author guojx
 * @Date 2023/6/25 14:39
 */
public class DataApiHttpUtils {
    private static final Logger LOGGER = LogManager.getLogger(DataApiHttpUtils.class);

    public static <T> RestResponse<Page<T>> responsePage(Map<String, Object> res, Class clazz) {
        if (isSuccess(res)) {
            Page page = getPageData(res);
            if (CollectionUtils.isNotEmpty(page.getResult())) {
                Page<T> resPage = EntityUtil.changeEntityNew(Page.class, page);
                List voList = JSONObject.parseArray(JSON.toJSONString(page.getResult()), clazz);
                resPage.setResult(voList);
                return RestResponse.successResult(resPage);
            }
            return RestResponse.successResult(page);
        }
        return errorRes(res);
    }

    public static <T> RestResponse<List<T>> responsePageList(Map<String, Object> res, Class clazz) {
        return RestResponse.successResult(parsePageList(res, clazz));
    }

    public static <T> List<T> parsePageList(Map<String, Object> res, Class clazz) {
        Page page = getPageData(res);
        if (CollectionUtils.isNotEmpty(page.getResult())) {
            List voList = JSONObject.parseArray(JSON.toJSONString(page.getResult()), clazz);
            return voList;
        }
        return Collections.EMPTY_LIST;
    }

    public static boolean isSuccess(Map<String, Object> res) {
        return res.get("errCode").toString().equals("0");
    }

    public static RestResponse errorRes(Map<String, Object> res) {
        return RestResponse.failure(res.get("errCode").toString(), res.get("errMsg").toString());
    }

    public static <T> List<T> parseList(Map<String, Object> res, Class clazz) {
        List<JSONObject> list = getDataList(res);
        if (CollectionUtils.isNotEmpty(list)) {
            List voList = JSONObject.parseArray(JSON.toJSONString(list), clazz);
            return voList;
        }
        return Collections.EMPTY_LIST;
    }

    public static List<JSONObject> getDataList(Map<String, Object> res) {
        return (List<JSONObject>) res.get("data");
    }
    public static JSONObject getDataOne(Map<String, Object> res) {
        List<JSONObject> list = getDataList(res);
        return CollectionUtils.isNotEmpty(list) ? list.get(0) : null;
    }

    public static Page getPageData(Map<String, Object> res) {
        if (!isSuccess(res)) {
            throw new ErrmsgException(res.get("errMsg").toString());
        }
        JSONObject data = (JSONObject) res.get("data");
        Page page = new Page();
        page.setTotalCount(data.getIntValue("totalNum"));
        page.setPageSize(data.getIntValue("pageSize"));
        page.setCurrentPage(data.getIntValue("pageNum"));
        List<JSONObject> list = (List<JSONObject>) data.get("rows");
        page.setResult(list);
        return page;
    }

    public static JSONObject getPageOne(Map<String, Object> res) {
        Page page = getPageData(res);
        if (CollectionUtils.isNotEmpty(page.getResult())) {
            return (JSONObject) page.getResult().get(0);
        }
        return new JSONObject();
    }

    public static List<JSONObject> getPageList(Map<String, Object> res) {
        Page page = getPageData(res);
        if (CollectionUtils.isNotEmpty(page.getResult())) {
            return (List<JSONObject>) page.getResult();
        }
        return Collections.EMPTY_LIST;
    }

    public static Map<String, Object> http(String jsonParam, String apolloKey) {
        if (StringUtils.isNotBlank(jsonParam)) {
            JSONObject jsonObject = JSONObject.parseObject(jsonParam);
            dealStoreIdParam(jsonObject);
            jsonParam = jsonObject.toJSONString();
        }
        LOGGER.info("接口的key：{}", apolloKey);
        Config config = ConfigService.getConfig("COMMON.data-api-config");
        String value = config.getProperty(apolloKey, "");
        if (StringUtils.isBlank(value)) {
            throw new ErrmsgException("数据接口配置有误！");
        }
        LOGGER.info("{}：Apollo查询的配置信息：{}", apolloKey, value);
        String[] split = value.split("\\+\\+\\+\\+");
        String url = split[0];
        String token = split[1];

        Map<String, String> head = new HashMap<>();
        head.put("Content-Type", "application/json");
        head.put("Authorization", token);
        Map<String, Object> res = HttpClient.getWinxinResByJson(url, jsonParam, head);
        if (!isSuccess(res)) {
            throw new ErrmsgException(res.get("errMsg").toString());
        }
        LOGGER.info("调用接口{}，返回结果:{}", url, res);
        return res;
    }

    public static void dealStoreIdParam(JSONObject objParam) {
        if (objParam != null) {
            if (objParam.containsKey("storeId")) {
                Object storeId = objParam.get("storeId");
                if (storeId == null || StringUtils.isBlank(storeId.toString())) {
                    objParam.remove("storeId");
                }
            }
        }
    }

    public static int getOrderByType(String str) {
        if (StringUtils.isBlank(str)) {
            return 2;
        }
        if (str.contains("desc")) {
            return 2;
        }
        return 1;
    }

    public static int getOrderByFields(String str, String defaultStr, Map<String, Integer> map) {
        if (StringUtils.isBlank(str)) {
            str = defaultStr;
        }
        str = str.replace(" desc", "");
        str = str.replace(" asc", "");
        str = str.replace(" ", "");
        return map.get(str);
    }

    public static void dealParamJsonDate(JSONObject paramJson) {
        dealParamJsonClerkSelect(paramJson, "startTime", "startDate");
        dealParamJsonClerkSelect(paramJson, "endTime", "endDate");
    }

    public static void dealParamJsonClerkSelect(JSONObject paramJson, String field, String httpField) {
        if (paramJson.containsKey(field)) {
            paramJson.put(httpField, paramJson.get(field));
        }
    }

    public static void dealParamJsonOrderBy(JSONObject paramJson, String orderByStr, String defaultField, Map<String, Integer> orderByFieldMap) {
        paramJson.put("orderByType", getOrderByType(orderByStr));
        paramJson.put("orderByFields", getOrderByFields(orderByStr,
                defaultField, orderByFieldMap));
    }
}
