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

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.DataApiUtils;
import com.gic.commons.util.DateUtil;
import com.gic.content.api.dto.material.ContentMaterialBaseDTO;
import com.gic.content.api.enums.MaterialPurposeEnum;
import com.gic.content.api.service.ContentMaterialApiService;
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.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.Date;
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";
    @Autowired
    private ContentMaterialApiService contentMaterialApiService;

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

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

    }

    @Data
    @AllArgsConstructor
    public static class MaterialBizInfo {
        private String clerkId;
        private String bizId;
        private String storeId;
    }

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

        String apolloKey = CLERK_WEEK_DATA;
        if (MaterialReportType.MONTH.getCode().equals(reportType)) {
            apolloKey = CLERK_MONTH_DATA;
        }
        Map<String, Object> inlineParams = new HashMap<>();
        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("orderByFields", 2);
        inlineParams.put("orderByType", 1);
        Map<String, Object> result = DataApiUtils.http(JSON.toJSONString(inlineParams), apolloKey);
        if (result.get("data") == null) {
            return null;
        }
        JSONObject jsonObject = DataApiUtils.getPageOne(result);
        if (jsonObject.isEmpty()) {
            return null;
        }
        int useMatlNum = jsonObject.getIntValue("useMatlNum");
        BigDecimal convSalesAmt = Optional.ofNullable(jsonObject.getBigDecimal("omniConvSalesAmt")).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, String bizDate) {

        String apolloKey = AREA_WEEK_DATA;
        if (MaterialReportType.MONTH.getCode().equals(reportType)) {
            apolloKey = AREA_MONTH_DATA;
        }
        Map<String, Object> inlineParams = new HashMap<>();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(clerkId)) {
            inlineParams.put("clerkId", clerkId);
        }
        inlineParams.put("enterpriseId", enterpriseId);
        inlineParams.put("bizDate", bizDate);
        if (CollectionUtils.isNotEmpty(storeIds)) {
            inlineParams.put("storeId", StringUtils.join(storeIds, ","));
        }
        Map<String, Object> result = DataApiUtils.http(JSON.toJSONString(inlineParams), apolloKey);
        if (result.get("data") == null) {
            return null;
        }
        List<JSONObject> dataList = DataApiUtils.getDataList(result);
        if (CollectionUtils.isEmpty(dataList)) {
            return null;
        }
        JSONObject jsonObject = dataList.get(0);
        if (jsonObject.isEmpty()) {
            return null;
        }
        BigDecimal dayAvgUseMatlNum = jsonObject.getBigDecimal("dayAvgUseMatlNum");
        BigDecimal convSalesAmt = Optional.ofNullable(jsonObject.getBigDecimal("convSalesAmt")).orElse(BigDecimal.ZERO);
        convSalesAmt = convSalesAmt.add(Optional.ofNullable(jsonObject.getBigDecimal("offlineConvSalesAmt")).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();
    }


    /**
     * 查询素材信息
     * @param enterpriseId
     * @param memberId
     * @param orderTime
     * @param goodsCode
     * @return
     */
    public MaterialBizInfo queryMaterialBizInfo(String enterpriseId, String memberId, Date orderTime, String goodsCode) {
        JSONObject params = new JSONObject();
        params.put("enterpriseId", enterpriseId);
        params.put("memberId", memberId);
        params.put("conv_flag", 1);
        try {
            params.put("orderCreateTime", DateUtil.formatString(orderTime, DateUtil.FORMAT_DATETIME_19));
            if (StringUtils.isNotBlank(goodsCode)) {
                params.put("conv_flag", 2);
                params.put("goodsCode", goodsCode);
            }
            Map<String, Object> res = DataApiUtils.http(params.toJSONString(), "data_cms_matl_conv_rel");
            List<JSONObject> dataList = DataApiUtils.getDataList(res);
            if (CollectionUtils.isEmpty(dataList)) {
                return null;
            }
            JSONObject jsonObject = dataList.get(0);
            return new MaterialBizInfo(jsonObject.getString("clerkId"), jsonObject.getString("contentMaterialId"), jsonObject.getString("storeId"));
        }catch (Exception ex) {
            log.info("查询会员素材信息异常 {}", params.toJSONString(), ex);
        }
        return null;
    }

    /**
     * 查询素材的审核素材id
     *
     * @param enterpriseId
     * @param materialId
     * @return
     */
    public Long queryMaterialBaseId(String enterpriseId, Long materialId) {
        if (StringUtils.isBlank(enterpriseId) || materialId == null) {
            return null;
        }
        ServiceResponse<ContentMaterialBaseDTO> serviceResponse = contentMaterialApiService.getFromMaterialById(enterpriseId,
                materialId, MaterialPurposeEnum.AUDIT.code);
        log.info("查询审核素材结果:{}", JSON.toJSONString(serviceResponse));
        if (serviceResponse.isSuccess() && serviceResponse.getResult() != null) {
            return serviceResponse.getResult().getContentMaterialId();
        }
        return null;
    }

}
