package com.gic.haoban.manage.service.util;

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.HttpClient;
import com.gic.commons.web.qo.PageQo;
import com.gic.commons.webapi.reponse.RestResponse;
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.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 目标配置调用数据组http接口工具类
 * @Author guojx
 * @Date 2023/1/17 9:51
 */
public class DataTargetHttpUtils {
    private static final Logger LOGGER = LogManager.getLogger(DataTargetHttpUtils.class);

    public static JSONObject getCommonParam(String enterpriseId, String storeId, String startTime, String endTime) {
        JSONObject resJson = new JSONObject();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("enterpriseId", enterpriseId);
        jsonObject.put("storeId", storeId);
        jsonObject.put("startTime", startTime);
        jsonObject.put("endTime", endTime);
        return resJson;
    }

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

    public static RestResponse responsePageData(Map<String, Object> res) {
        if (res.get("errorCode").toString().equals("1")) {
            //成功
            Page page = new Page();
            List<JSONObject> dataList = (List<JSONObject>) res.get("data");

            JSONObject pageJson = (JSONObject) res.get("page");
            page.setPageSize(pageJson.getIntValue("pageSize"));
            page.setTotalCount(pageJson.getIntValue("totalCount"));
            page.setCurrentPage(pageJson.getIntValue("currentPage"));
            page.setTotalPage(pageJson.getIntValue("totalPage"));

            page.setResult(dataList);
            return RestResponse.successResult(page);
        }
        return RestResponse.failure((String) res.get("errorCode"), (String) res.get("errorInfo"));
    }

    public static RestResponse response(Map<String, Object> res) {
        if (res.get("errorCode").toString().equals("1")) {
            //成功
            List<JSONObject> dataList = (List<JSONObject>) res.get("data");
            return RestResponse.successResult(dataList);
        }
        return RestResponse.failure((String) res.get("errorCode"), (String) res.get("errorInfo"));
    }

    public static RestResponse responseOfOne(Map<String, Object> res, JSONObject defaultJson) {
        if (res.get("errorCode").toString().equals("1")) {
            //成功
            List<JSONObject> dataList = (List<JSONObject>) res.get("data");
            if (CollectionUtils.isNotEmpty(dataList)) {
                return RestResponse.successResult(dataList.get(0));
            }
            if (defaultJson != null) {
                return RestResponse.successResult(defaultJson);
            }
            return RestResponse.successResult(null);
        }
        return RestResponse.failure((String) res.get("errorCode"), (String) res.get("errorInfo"));
    }

    public static List<JSONObject> getDataList(Map<String, Object> res) {
        if (res.get("errorCode").toString().equals("1")) {
            //成功
            List<JSONObject> dataList = (List<JSONObject>) res.get("data");
            return dataList;
        }
        return Collections.EMPTY_LIST;
    }

    public static JSONObject getData(Map<String, Object> res) {
        if (res.get("errorCode").toString().equals("1")) {
            //成功
            List<JSONObject> dataList = (List<JSONObject>) res.get("data");
            if (CollectionUtils.isNotEmpty(dataList)) {
                return dataList.get(0);
            }
            return null;
        }
        return null;
    }

    public static Map<String, Object> http(String jsonParam, String apolloKey) {
        LOGGER.info("接口的key：{}", apolloKey);
        Config config = ConfigService.getConfig("COMMON.data-api-config");
        String value = config.getProperty(apolloKey, "");
        if (StringUtils.isBlank(value)) {
            throw new RuntimeException("数据接口配置有误！");
        }
        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("API-TOKEN", token);
        Map<String, Object> res = HttpClient.getWinxinResByJson(url, jsonParam, head);
        if (!isSuccess(res)) {
            throw new RuntimeException((String) res.get("errorInfo"));
        }
        LOGGER.info("调用接口{}，返回结果:{}", url, res);
        return res;
    }

    public static JSONObject getParam(PageQo pageQo, JSONObject objParam) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageNo", pageQo.getPageNum());
        jsonObject.put("pageSize", pageQo.getPageSize());

        if (objParam != null) {
            if (objParam.containsKey("storeId")) {
                Object storeId = objParam.get("storeId");
                if (storeId == null || StringUtils.isBlank(storeId.toString())) {
                    objParam.remove("storeId");
                }
            }
        }
        jsonObject.put("inFields", objParam);
        return jsonObject;
    }

    public static JSONObject getParamNoPage(JSONObject objParam) {
        JSONObject jsonObject = new JSONObject();
        if (objParam != null) {
            if (objParam.containsKey("storeId")) {
                Object storeId = objParam.get("storeId");
                if (storeId == null || StringUtils.isBlank(storeId.toString())) {
                    objParam.remove("storeId");
                }
            }
        }
        jsonObject.put("inFields", objParam);
        return jsonObject;
    }

    /**
     * 保留2位小数 .元转万元
     *
     * @param a
     * @return by wws
     */
    public static Double transferTenThousand(Double a) {
        BigDecimal bd = new BigDecimal(a / 10000);
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }

    public static Double transferTenThousand(String a) {
        BigDecimal bd = new BigDecimal(a);
        bd = bd.divide(new BigDecimal("10000")).setScale(2, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }

    public static Double transferTenThousand(Object a) {
        if (a == null) {
            return 0.00;
        }
        BigDecimal bd = new BigDecimal(a.toString());
        bd = bd.divide(new BigDecimal("10000")).setScale(2, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }

    public static Double parseDouble(Object a) {
        if (a == null) {
            return 0.00;
        }
        return Double.parseDouble(a.toString());
    }

    public static Double transferTenThousandNoDivide(Double a) {
        if (a == null) {
            return 0.00;
        }
        BigDecimal bd = new BigDecimal(a.toString());
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }

    public static String formatToSepara(Double data) {
        DecimalFormat df = new DecimalFormat("#,###.00");
        return df.format(data);
    }

    public static String formatToSepara(Integer data) {
        DecimalFormat df = new DecimalFormat("#,###");
        return df.format(data);
    }

    public static String getContrast(String data) {
        if ("--".equals(data)) {
            return data;
        }
        Double dataDouble = Double.parseDouble(data);
        if (dataDouble > 0) {
            return "+" + data + "%";
        } else {
            return data + "%";
        }
    }

    public static String getJsonOrDefault(Object a, Object object) {
        if (a == null) {
            return object.toString();
        }
        return a.toString();
    }

    public static Object getObjectOrDefault(Object a, Object object) {
        if (a == null) {
            return object;
        }
        return a;
    }

    public static String getContrastOrDefault(Object a, Object object) {
        return getContrast(getJsonOrDefault(a, object));
    }

    public static String getRateOrDefault(Object a, Object object) {
        String data = getJsonOrDefault(a, object);
        if ("--".equals(data)) {
            return data;
        }
        return data + "%";
    }

    public static Page getPage(Map<String, Object> detailRes) {
        Page page = new Page();
        List<JSONObject> dataList = (List<JSONObject>) detailRes.get("data");

        JSONObject pageJson = (JSONObject) detailRes.get("page");
        page.setPageSize(pageJson.getIntValue("pageSize"));
        page.setTotalCount(pageJson.getIntValue("totalCount"));
        page.setCurrentPage(pageJson.getIntValue("currentPage"));
        page.setTotalPage(pageJson.getIntValue("totalPage"));

        page.setResult(dataList);
        return page;
    }
}
