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

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.haoban.manage.web.exception.TargetException;
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 2022/5/6 17:01
 */
public class StoreTargetConfigHttpUtils extends HttpClient{
    private static final Logger LOGGER = LogManager.getLogger(StoreTargetConfigHttpUtils.class);

    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("enterpriseId", "ff8080815dacd3a2015dacd3ef5c0000");
        //Map<String, Object> res = http(getParamNoPage(jsonObject).toJSONString(), "data_mbr_target_overview_targetActual");
        //System.out.println(JSON.toJSONString(responseOfOne(res, null)));
    }


    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 List<JSONObject> getDataList(Map<String, Object> res) {
        return (List<JSONObject>) res.get("data");
    }


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

    public static Page getPageData(Map<String, Object> res) {
        if (!isSuccess(res)) {
            throw new TargetException(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 RestResponse responsePage(Map<String, Object> res) {
        if (isSuccess(res)) {
            return RestResponse.successResult(getPageData(res));
        }
        return errorRes(res);
    }

    public static RestResponse responsePageOne(Map<String, Object> res) {
        return RestResponse.successResult(getPageOne(res));
    }

    public static RestResponse responsePageList(Map<String, Object> res) {
        Page page = getPageData(res);
        return RestResponse.successResult(page.getResult());
    }


    public static RestResponse responseRest(Map<String, Object> res) {
        if (isSuccess(res)) {
            return RestResponse.successResult(getDataList(res));
        }
        return errorRes(res);
    }

    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 JSONObject getDefaultMonth(JSONObject resJson) {
        if (!resJson.containsKey("1")) {
            resJson.put("1", 0D);
        }
        if (!resJson.containsKey("2")) {
            resJson.put("2", 0D);
        }
        if (!resJson.containsKey("3")) {
            resJson.put("3", 0D);
        }
        if (!resJson.containsKey("4")) {
            resJson.put("4", 0D);
        }
        if (!resJson.containsKey("5")) {
            resJson.put("5", 0D);
        }
        if (!resJson.containsKey("6")) {
            resJson.put("6", 0D);
        }
        if (!resJson.containsKey("7")) {
            resJson.put("7", 0D);
        }
        if (!resJson.containsKey("8")) {
            resJson.put("8", 0D);
        }
        if (!resJson.containsKey("9")) {
            resJson.put("9", 0D);
        }
        if (!resJson.containsKey("10")) {
            resJson.put("10", 0D);
        }
        if (!resJson.containsKey("11")) {
            resJson.put("11", 0D);
        }
        if (!resJson.containsKey("12")) {
            resJson.put("12", 0D);
        }
        return resJson;
    }

    public static JSONObject getCommonParam(String enterpriseId, String storeId, String startTime, String endTime) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("enterpriseId", enterpriseId);
        jsonObject.put("entId", enterpriseId);
        jsonObject.put("storeId", storeId);
        jsonObject.put("startTime", startTime);
        jsonObject.put("startDate", startTime);
        jsonObject.put("endTime", endTime);
        jsonObject.put("endDate", endTime);
        return jsonObject;
    }

    public static RestResponse responseOfOneForRest(Map<String, Object> res, JSONObject defaultJson) {
        if (isSuccess(res)) {
            List<JSONObject> list = getDataList(res);
            if (CollectionUtils.isNotEmpty(list)) {
                return RestResponse.successResult(list.get(0));
            }
            if (defaultJson != null) {
                return RestResponse.successResult(defaultJson);
            }
            return RestResponse.successResult();
        }
        return RestResponse.failure("-1",  res.get("errMsg").toString());
    }

    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 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 TargetException("数据接口配置有误！");
        }
        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 TargetException((String) res.get("errorInfo"));
        }
        LOGGER.info("调用接口{}，返回结果:{}", url, res);
        return res;
    }

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

    /**
     * 保留2位小数 .元转万元
     *
     * @param a
     * @param isNeedToTransfer true除以10000
     * @return by wws
     */
    public static Double transferTenThousand(Object a, boolean isNeedToTransfer) {
        if (a == null) {
            return 0.00;
        }
        BigDecimal bd = new BigDecimal(a.toString());
        if (isNeedToTransfer) {
            bd = bd.divide(new BigDecimal(10000));
        }
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }

    /**
     * 保留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("0.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 JSONObject fixLastMonthSales(JSONObject resJson, Double yearSales) {
        if (yearSales == null || yearSales <= 0) {
            return resJson;
        }
        int lastMonth = 1;
        //取出最后一个有值的月份
        for (int i = 1; i <= 12; i++) {
            if (resJson.containsKey(String.valueOf(i))) {
                //如果有值
                if (i > lastMonth) {
                    lastMonth = i;
                }
            }
        }
        Double sum = 0D;
        for (int i = 1; i < lastMonth; i++) {
            if (resJson.containsKey(String.valueOf(i))) {
                sum += resJson.getDouble(String.valueOf(i));
            }
        }
        resJson.put(String.valueOf(lastMonth), transferTenThousandNoDivide(yearSales - sum));
        return resJson;
    }
}
