package com.gic.haoban.manage.web.controller.content.adaptor;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.haoban.manage.web.utils.target.DataTargetHttpUtils;
import com.gic.haoban.manage.web.vo.content.statistics.MaterialIndexDataVO;
import com.gic.mall.api.dto.MallProDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author MUSI
 * @Date 2023/3/27 10:49 AM
 * @Description
 * @Version
 * 素材数据统计
 **/
@Slf4j
@Component
public class MaterialDataAdaptor {

    @Autowired
    private ClerkStoreAdaptor clerkStoreAdaptor;

    /**
     * 素材首页数据统计
     */
    private static final String MATERIAL_INDEX_DATA = "data_matl_haoban_area_stats_real";


    /**
     * 查询素材首页使用数据
     * @param enterpriseId
     * @return
     */
    public MaterialIndexDataVO queryMaterialIndexData(String enterpriseId, List<String> storeIds) {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> inlineParams = new HashMap<>();
        params.put("inFields", inlineParams);

        inlineParams.put("enterprsieId", enterpriseId);
        if (CollectionUtil.isNotEmpty(storeIds)) {
            inlineParams.put("storeId", StringUtils.join(storeIds, ","));
        }
        Map<String, Object> result =  this.doHttp(JSON.toJSONString(params), MATERIAL_INDEX_DATA);
        if (result.get("data") == null) {
            return MaterialIndexDataVO.builder()
                    .useMaterialClerkNum(0)
                    .unUseMaterialClerkNum(0)
                    .conversionAmount(BigDecimal.ZERO)
                    .build();
        }

        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.get("data")), JSONObject.class);
        return MaterialIndexDataVO.builder()
                .useMaterialClerkNum(jsonObject.getIntValue("useMatlClerkNum"))
                .unUseMaterialClerkNum(jsonObject.getIntValue("unusedMatlClerkNum"))
                .conversionAmount(jsonObject.getBigDecimal("convSalesAmt"))
                .build();
    }


    private Map<String, Object> doHttp(String jsonParam, String apolloKey){
        try {
            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();
    }

}
