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

import cn.hutool.core.date.DateTime;
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.enterprise.api.constant.EnterpriseServiceEnum;
import com.gic.haoban.manage.api.enums.content.MaterialReportType;
import com.gic.haoban.manage.service.pojo.bo.content.context.MaterialReportContext;
import com.gic.haoban.manage.service.util.DataTargetHttpUtils;
import com.gic.haoban.manage.service.util.DrawImageUtils;
import com.google.common.collect.Lists;
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.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 WeekMonthDataAdaptor {


    /**
     * 导购/店长 周报
     */
    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";


    /**
     * 潜客雷达 周报/月报
     */
    private static final String POTENTIAL_WEEK_MONTH_DATA = "data_mkt_pos_cut_haoban_overview";

    @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;
    }

    public MaterialDataResult queryClerkReportData(MaterialReportContext context,String storeId,String bizDate) {
        String enterpriseId = context.getEnterpriseId();
        String clerkId = context.getClerkId();
        Integer reportType = context.getReportType();
        List<String> rightMenuCodeList = context.getRightMenuCodeList();
        if (CollectionUtils.isEmpty(rightMenuCodeList)) {
            return MaterialDataResult.buildEmpty();
        }
        if (rightMenuCodeList.size() > 1) {
            MaterialDataResult contentResult = queryClerkReportDataContent(enterpriseId, clerkId, storeId, reportType, bizDate);
            MaterialDataResult potentialResult = queryReportDataPotential(enterpriseId, clerkId, Lists.newArrayList(storeId), reportType, bizDate);
            return new MaterialDataResult(potentialResult.getFirstValue(),contentResult.getSecondValue());
        } else if (rightMenuCodeList.contains(EnterpriseServiceEnum.POTENTIAL.getRightMenuCode())) {
            return queryReportDataPotential(enterpriseId, clerkId, Lists.newArrayList(storeId), reportType, bizDate);
        } else if (rightMenuCodeList.contains(EnterpriseServiceEnum.CONTENT.getRightMenuCode())) {
            return queryClerkReportDataContent(enterpriseId, clerkId, storeId, reportType, bizDate);
        }
        return MaterialDataResult.buildEmpty();
    }

    public MaterialDataResult queryAreaReportData(MaterialReportContext context,List<String> storeIds,String bizDate) {
        String enterpriseId = context.getEnterpriseId();
        String clerkId = context.getClerkId();
        Integer reportType = context.getReportType();
        List<String> rightMenuCodeList = context.getRightMenuCodeList();
        if (CollectionUtils.isEmpty(rightMenuCodeList)) {
            return MaterialDataResult.buildEmpty();
        }
        if (rightMenuCodeList.size() > 1) {
            MaterialDataResult contentResult = queryAreaReportDataContent(enterpriseId, clerkId, storeIds, reportType, bizDate);
            MaterialDataResult potentialResult = queryReportDataPotential(enterpriseId, clerkId, storeIds, reportType, bizDate);
            return new MaterialDataResult(potentialResult.getFirstValue(),contentResult.getSecondValue());
        } else if (rightMenuCodeList.contains(EnterpriseServiceEnum.POTENTIAL.getRightMenuCode())) {
            return queryReportDataPotential(enterpriseId, clerkId, storeIds, reportType, bizDate);
        } else if (rightMenuCodeList.contains(EnterpriseServiceEnum.CONTENT.getRightMenuCode())) {
            return queryAreaReportDataContent(enterpriseId, clerkId, storeIds, reportType, bizDate);
        }
        return MaterialDataResult.buildEmpty();
    }

    /**
     * 查询导购/店长的数据 素材
     * @param enterpriseId
     * @param clerkId
     * @param storeId
     * @param reportType
     * @return
     */
    public MaterialDataResult queryClerkReportDataContent(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;
        }
        BigDecimal useMatlNum = jsonObject.getBigDecimal("useMatlNum");
        BigDecimal convSalesAmt = Optional.ofNullable(jsonObject.getBigDecimal("omniConvSalesAmt")).orElse(BigDecimal.ZERO);
        return formatDecimal(useMatlNum,convSalesAmt);
    }


    /**
     * 区经 素材
     * @param enterpriseId
     * @param clerkId
     * @param storeIds
     * @param reportType
     * @return
     */
    public MaterialDataResult queryAreaReportDataContent(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));
        return formatDecimal(dayAvgUseMatlNum, convSalesAmt);
    }


    /**
     * 查询数据 潜客雷达 todo 对接数据
     * @param enterpriseId
     * @param clerkId
     * @param storeIds
     * @param reportType
     * @return
     */
    public MaterialDataResult queryReportDataPotential(String enterpriseId, String clerkId, List<String> storeIds, Integer reportType, String bizDate) {

        String apolloKey = POTENTIAL_WEEK_MONTH_DATA;
        String endDate = bizDate;
        String beginDate = bizDate;
        if (MaterialReportType.MONTH.getCode().equals(reportType)) {
            DateTime date = cn.hutool.core.date.DateUtil.parse("yyyy-MM");
            beginDate = cn.hutool.core.date.DateUtil.format(cn.hutool.core.date.DateUtil.beginOfMonth(date), "yyyy-MM-dd");
            endDate = cn.hutool.core.date.DateUtil.format(cn.hutool.core.date.DateUtil.endOfMonth(date), "yyyy-MM-dd");
        }else {
            DateTime date = cn.hutool.core.date.DateUtil.parse("yyyy-MM-dd");
            endDate = cn.hutool.core.date.DateUtil.format(cn.hutool.core.date.DateUtil.endOfWeek(date), "yyyy-MM-dd");
        }
        Map<String, Object> inlineParams = new HashMap<>();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(clerkId)) {
            inlineParams.put("clerkId", clerkId);
        }
        if (CollectionUtils.isNotEmpty(storeIds)) {
            inlineParams.put("storeId", StringUtils.join(storeIds, ","));
        }
        inlineParams.put("enterpriseId", enterpriseId);
        inlineParams.put("startDate", beginDate);
        inlineParams.put("endDate", endDate);
        // 1 门店维度 2 导购维度 3 合计
        inlineParams.put("potGroup", 3);
        inlineParams.put("reportType", reportType);
        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;
        }
        List<JSONObject> dataList = DataApiUtils.getDataList(result);
        if (CollectionUtils.isEmpty(dataList)) {
            return null;
        }
        JSONObject jsonObject = dataList.get(0);
        BigDecimal potCusConnRate = Optional.ofNullable(jsonObject.getBigDecimal("potCusConnRate")).orElse(BigDecimal.ZERO);
        BigDecimal convSalesAmt = Optional.ofNullable(jsonObject.getBigDecimal("connConvsAmt")).orElse(BigDecimal.ZERO);
        return formatDecimal(potCusConnRate, convSalesAmt);
    }

    private MaterialDataResult formatDecimal(BigDecimal potCusConnRate, BigDecimal convSalesAmt) {
        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 potCusConnRateStr = decimalFormat.format(potCusConnRate);
        return new MaterialDataResult(potCusConnRateStr, (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;
    }

}
