package com.gic.haoban.manage.service.service.content.adaptor;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.haoban.manage.api.enums.content.MaterialReportType;
import com.gic.haoban.manage.service.util.DataTargetHttpUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Author MUSI
 * @Date 2023/4/5 3:04 PM
 * @Description
 * @Version 素材数据
 **/
@Slf4j
@Component
public class MaterialDataAdaptor {

    /**
     * 导购/店长 周报
     */
    private static final String CLERK_WEEK_DATA = "data_cms_clerk_week_report_list";
    /**
     * 导购/店长 月报
     */
    private static final String CLERK_MONTH_DATA = "data_cms_clerk_month_report_list";

    /**
     * 区经 月报
     */
    private static final String AREA_WEEK_DATA = "data_cms_store_week_report_total";

    /**
     * 区经 月报
     */
    private static final String AREA_MONTH_DATA = "data_cms_store_month_report_total";

    @Data
    @AllArgsConstructor
    public static class MaterialDataResult {
        private String firstValue;
        private String secondValue;

        public static MaterialDataResult buildEmpty() {
            return new MaterialDataResult("0", "0");
        }

    }

    /**
     * 查询导购/店长的数据
     * @param enterpriseId
     * @param clerkId
     * @param storeId
     * @param reportType
     * @return
     */
    public MaterialDataResult queryClerkReportData(String enterpriseId, String clerkId, String storeId, Integer reportType) {

        int bizDate;
        String apolloKey = CLERK_WEEK_DATA;
        if (MaterialReportType.WEEK.getCode().equals(reportType)) {
            // 周报
            bizDate = DateUtil.weekOfYear(DateUtil.lastWeek());
        } else {
            bizDate = DateUtil.month(DateUtil.lastMonth());
            apolloKey = CLERK_MONTH_DATA;
        }
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> inlineParams = new HashMap<>();
        params.put("inFields", inlineParams);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(clerkId)) {
            inlineParams.put("clerkId", clerkId);
        }
        inlineParams.put("enterpriseId", enterpriseId);
        inlineParams.put("bizDate", bizDate);
        inlineParams.put("storeId", storeId);
        inlineParams.put("orderByField", "storeId asc");
        Map<String, Object> result = this.doHttp(JSON.toJSONString(params), apolloKey);
        if (result.get("data") == null) {
            return null;
        }

        List<JSONObject> jsonObjects = JSON.parseArray(JSON.toJSONString(result.get("data")), JSONObject.class);
        if (CollectionUtils.isEmpty(jsonObjects)) {
            return null;
        }
        JSONObject jsonObject = jsonObjects.get(0);
        int useMatlNum = jsonObject.getIntValue("useMatlNum");
        BigDecimal convSalesAmt = Optional.ofNullable(jsonObject.getBigDecimal("convSalesAmt")).orElse(BigDecimal.ZERO);
        String amountUnit = "";
        if (convSalesAmt.compareTo(new BigDecimal(10000)) >= 0) {
            convSalesAmt = convSalesAmt.divide(BigDecimal.valueOf(10000), 2, RoundingMode.HALF_UP);
            amountUnit = "万";
        }
        DecimalFormat decimalFormat = new DecimalFormat("#,###,###.##");
        String formatAmount = decimalFormat.format(convSalesAmt);
        String numFormat = decimalFormat.format(useMatlNum);
        return new MaterialDataResult(numFormat, (formatAmount + amountUnit));
    }


    /**
     * 区经
     * @param enterpriseId
     * @param clerkId
     * @param storeIds
     * @param reportType
     * @return
     */
    public MaterialDataResult queryAreaReportData(String enterpriseId, String clerkId, List<String> storeIds, Integer reportType) {

        int bizDate = 0;
        String apolloKey = AREA_WEEK_DATA;
        if (MaterialReportType.WEEK.getCode().equals(reportType)) {
            // 周报
            bizDate = DateUtil.weekOfYear(DateUtil.lastWeek());
        } else {
            bizDate = DateUtil.month(DateUtil.lastMonth());
            apolloKey = AREA_MONTH_DATA;
        }
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> inlineParams = new HashMap<>();
        params.put("inFields", inlineParams);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(clerkId)) {
            inlineParams.put("clerkId", clerkId);
        }
        inlineParams.put("enterpriseId", enterpriseId);
        inlineParams.put("bizDate", bizDate);
        inlineParams.put("orderByField", "clerkId asc");
        if (CollectionUtils.isNotEmpty(storeIds)) {
            inlineParams.put("storeId", StringUtils.join(storeIds, ","));
        }
        Map<String, Object> result = this.doHttp(JSON.toJSONString(params), apolloKey);
        if (result.get("data") == null) {
            return null;
        }
        List<JSONObject> jsonObjects = JSON.parseArray(JSON.toJSONString(result.get("data")), JSONObject.class);
        if (CollectionUtils.isEmpty(jsonObjects)) {
            return null;
        }
        JSONObject jsonObject = jsonObjects.get(0);
        int dayAvgUseMatlNum = jsonObject.getIntValue("dayAvgUseMatlNum");
        BigDecimal convSalesAmt = Optional.ofNullable(jsonObject.getBigDecimal("convSalesAmt")).orElse(BigDecimal.ZERO);
        String amountUnit = "";
        if (convSalesAmt.compareTo(new BigDecimal(10000)) >= 0) {
            convSalesAmt = convSalesAmt.divide(BigDecimal.valueOf(10000), 2, RoundingMode.HALF_UP);
            amountUnit = "万";
        }
        DecimalFormat decimalFormat = new DecimalFormat("#,###,###.##");
        String formatAmount = decimalFormat.format(convSalesAmt);
        String numFormat = decimalFormat.format(dayAvgUseMatlNum);
        return new MaterialDataResult(numFormat, (formatAmount + amountUnit));
    }

    private Map<String, Object> doHttp(String jsonParam, String apolloKey) {
        try {
            log.info("调用接口 apolloKey：{}, 参数:{}", apolloKey, jsonParam);
            Map<String, Object> result = DataTargetHttpUtils.http(jsonParam, apolloKey);
            if (result == null) {
                return Collections.emptyMap();
            }
            return result;
        } catch (Exception ex) {
            log.info("请求接口失败 apolloKey:{}", apolloKey, ex);
        }
        return Collections.emptyMap();
    }
}
