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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.haoban.manage.api.enums.content.MaterialReportType;
import com.gic.haoban.manage.web.qo.content.statistics.MaterialReportQO;
import com.gic.haoban.manage.web.utils.target.DataTargetHttpUtils;
import com.gic.haoban.manage.web.vo.content.statistics.MaterialAreaUsedDataVO;
import com.gic.haoban.manage.web.vo.content.statistics.MaterialClerkUsedDataVO;
import com.gic.haoban.manage.web.vo.content.statistics.MaterialDataOverviewVO;
import com.gic.haoban.manage.web.vo.content.statistics.MaterialStoreUsedDataVO;
import com.gic.haoban.manage.web.vo.content.statistics.bo.MaterialTodayDataBO;
import com.gic.haoban.manage.web.vo.content.statistics.bo.MemberVisitMaterialBO;
import com.gic.haoban.manage.web.vo.content.statistics.report.MaterialPersonalUsedDataVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

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


    /**
     * 素材首页数据统计
     */
    private static final String MATERIAL_INDEX_DATA = "data_matl_haoban_area_stats_real";
    private static final String MATERIAL_OVERVIEW_DATA = "data_matl_haoban_area_stats";
    /**
     * 导购纬度数据统计
     */
    private static final String MATERIAL_CLERK_DATA = "data_matl_haoban_clerk_stats";

    /**
     * 门店纬度数据统计
     */
    private static final String MATERIAL_STORE_DATA = "data_matl_haoban_store_stats";

    /**
     * 素材导购周报数据
     */
    private static final String MATERIAL_CLERK_WEEK_DATA = "data_cms_clerk_week_report_list";

    /**
     * 素材导购月报数据
     */
    private static final String MATERIAL_CLERK_MONTH_DATA = "data_cms_clerk_month_report_list";
    /**
     * 素材门店周报数据
     */
    private static final String MATERIAL_STORE_WEEK_DATA = "data_cms_store_week_report_list";
    /**
     * 素材门店月报数据
     */
    private static final String MATERIAL_STORE_MONTH_DATA = "data_cms_store_month_report_list";

    /**
     * 区经周报数据
     */
    private static final String MATERIAL_AREA_WEEK_DATA = "data_cms_store_week_report_total";

    /**
     * 区经月报数据
     */
    private static final String MATERIAL_AREA_MONTH_DATA = "data_cms_store_month_report_total";

    /**
     * 会员最近30天访问素材总数
     */
    private static final String MEMBER_RECENTLY_30_DAY_VISIT = "data_matl_haoban_user_30day_stats_real";


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

        inlineParams.put("enterpriseId", 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 MaterialTodayDataBO.empty();
        }
        List<MaterialTodayDataBO> datas = JSON.parseArray(JSON.toJSONString(result.get("data")), MaterialTodayDataBO.class);
        if (CollectionUtils.isEmpty(datas)) {
            return MaterialTodayDataBO.empty();
        }
        return datas.get(0);
    }


    /**
     * 店长/区经
     * 查询数据概览
     *
     * @param enterpriseId
     * @param storeIds
     * @param fixedDateDiff
     * @return
     */
    public MaterialDataOverviewVO queryMaterialDataOverview(String enterpriseId, List<String> storeIds, Integer fixedDateDiff) {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> inlineParams = new HashMap<>();
        params.put("inFields", inlineParams);

        inlineParams.put("enterpriseId", enterpriseId);
        inlineParams.put("fixedDateDiff", fixedDateDiff);
        if (CollectionUtil.isNotEmpty(storeIds)) {
            inlineParams.put("storeId", StringUtils.join(storeIds, ","));
        }
        Map<String, Object> result = this.doHttp(JSON.toJSONString(params), MATERIAL_OVERVIEW_DATA);
        if (result.get("data") == null) {
            return new MaterialDataOverviewVO();
        }
        List<MaterialDataOverviewVO> datas = JSON.parseArray(JSON.toJSONString(result.get("data")), MaterialDataOverviewVO.class);
        if (CollectionUtils.isEmpty(datas)) {
            return new MaterialDataOverviewVO();
        }
        return datas.get(0);
    }


    /**
     * 导购纬度数据统计
     *
     * @param enterpriseId
     * @param storeIds
     * @param fixedDateDiff
     * @param orderStr
     * @return
     */
    public Page<MaterialClerkUsedDataVO> queryMaterialClerkUsedData(String enterpriseId, List<String> storeIds, Integer fixedDateDiff,
                                                                    String orderField, String orderStr, Integer pageNo, Integer pageSize) {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> inlineParams = new HashMap<>();
        params.put("pageNo", pageNo);
        params.put("pageSize", pageSize);
        params.put("inFields", inlineParams);
        inlineParams.put("enterpriseId", enterpriseId);
        inlineParams.put("fixedDateDiff", fixedDateDiff);
        if (StringUtils.isNotBlank(orderField)) {
            inlineParams.put("orderByField", orderField + " " +orderStr);
        }else {
            inlineParams.put("orderByField", "enterpriseId asc ");
        }
        if (CollectionUtil.isNotEmpty(storeIds)) {
            inlineParams.put("storeId", StringUtils.join(storeIds, ","));
        }
        Map<String, Object> result = this.doHttp(JSON.toJSONString(params), MATERIAL_CLERK_DATA);
        if (result.get("data") == null) {
            return new Page<>();
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.get("page")), JSONObject.class);
        int totalCount = jsonObject.getIntValue("totalCount");
        int totalPage = jsonObject.getIntValue("totalPage");
        List<MaterialClerkUsedDataVO> dataVOS = JSON.parseArray(JSON.toJSONString(result.get("data")), MaterialClerkUsedDataVO.class);
        Page<MaterialClerkUsedDataVO> pageResult = new Page<>();
        pageResult.setTotalCount(totalCount);
        pageResult.setTotalPage(totalPage);
        pageResult.setResult(dataVOS);
        return pageResult;
    }

    /**
     * 门店纬度数据统计
     *
     * @param enterpriseId
     * @param storeIds
     * @param fixedDateDiff
     * @param orderStr
     * @return
     */
    public Page<MaterialStoreUsedDataVO> queryMaterialStoreUsedData(String enterpriseId, List<String> storeIds, Integer fixedDateDiff,
                                                                    String orderField, String orderStr, Integer pageNo, Integer pageSize) {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> inlineParams = new HashMap<>();
        params.put("pageNo", pageNo);
        params.put("pageSize", pageSize);
        params.put("inFields", inlineParams);

        inlineParams.put("enterpriseId", enterpriseId);
        inlineParams.put("fixedDateDiff", fixedDateDiff);
        if (StringUtils.isNotBlank(orderField)) {
            inlineParams.put("orderByField", orderField + " " + orderStr);
        }else {
            inlineParams.put("orderByField", "enterpriseId asc ");
        }
        if (CollectionUtil.isNotEmpty(storeIds)) {
            inlineParams.put("storeId", StringUtils.join(storeIds, ","));
        }
        Map<String, Object> result = this.doHttp(JSON.toJSONString(params), MATERIAL_STORE_DATA);
        if (result.get("data") == null) {
            return new Page<>();
        }

        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.get("page")), JSONObject.class);
        int totalCount = jsonObject.getIntValue("totalCount");
        int totalPage = jsonObject.getIntValue("totalPage");
        List<MaterialStoreUsedDataVO> dataVOS = JSON.parseArray(JSON.toJSONString(result.get("data")), MaterialStoreUsedDataVO.class);
        Page<MaterialStoreUsedDataVO> pageResult = new Page<>();
        pageResult.setTotalCount(totalCount);
        pageResult.setTotalPage(totalPage);
        pageResult.setResult(dataVOS);
        return pageResult;
    }


    // --------------- 周报/月报 ---------------

    /**
     * 查询导购素材使用情况
     *
     * @param storeIds
     * @return
     */
    public Page<MaterialPersonalUsedDataVO> queryMaterialClerkUsedReport(MaterialReportQO materialReportQO, List<String> storeIds) {
        Integer reportType = materialReportQO.getReportType();
        Integer pageNo = materialReportQO.getPageNum();
        Integer pageSize = materialReportQO.getPageSize();
        String clerkId = materialReportQO.getClerkId();
        String enterpriseId = materialReportQO.getEnterpriseId();
        String orderField = materialReportQO.getOrderByField();
        String orderStr = materialReportQO.getOrder();
        // 获取当前时间周期
        DateTime startTime = null;
        DateTime endTime = null;
        String bizDate = materialReportQO.getBizDate();
        String apolloKey = MATERIAL_CLERK_WEEK_DATA;
        if (MaterialReportType.WEEK.getCode().equals(reportType)) {
            // 周报
            startTime = DateUtil.beginOfWeek(DateUtil.lastWeek());
            endTime = DateUtil.endOfWeek(DateUtil.lastWeek());
        } else {
            startTime = DateUtil.beginOfMonth(DateUtil.lastWeek());
            endTime = DateUtil.endOfMonth(DateUtil.lastWeek());
            apolloKey = MATERIAL_CLERK_MONTH_DATA;
        }
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> inlineParams = new HashMap<>();
        params.put("pageNo", pageNo);
        params.put("pageSize", pageSize);
        params.put("inFields", inlineParams);
        if (StringUtils.isNotBlank(clerkId)) {
            inlineParams.put("clerkId", clerkId);
        }
        inlineParams.put("enterpriseId", enterpriseId);
        inlineParams.put("bizDate", bizDate);
        if (CollectionUtil.isNotEmpty(storeIds)) {
            inlineParams.put("storeId", StringUtils.join(storeIds, ","));
        }
        if (StringUtils.isNotBlank(orderField)) {
            inlineParams.put("orderByField", orderField + " " + orderStr);
        }else {
            inlineParams.put("orderByField", "enterpriseId asc ");
        }
        Map<String, Object> result = this.doHttp(JSON.toJSONString(params), apolloKey);
        if (result.get("data") == null) {
            return new Page<>();
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.get("page")), JSONObject.class);
        int totalCount = jsonObject.getIntValue("totalCount");
        int totalPage = jsonObject.getIntValue("totalPage");
        Page<MaterialPersonalUsedDataVO> pageResult = new Page<>();
        pageResult.setTotalCount(totalCount);
        pageResult.setTotalPage(totalPage);
        List<MaterialPersonalUsedDataVO> materialPersonalUsedDataVos = JSON.parseArray(JSON.toJSONString(result.get("data")), MaterialPersonalUsedDataVO.class);
        if (CollectionUtils.isEmpty(materialPersonalUsedDataVos)) {
            return new Page<>();
        }
        for (MaterialPersonalUsedDataVO materialPersonalUsedDataVo : materialPersonalUsedDataVos) {
            materialPersonalUsedDataVo.setStartTime(startTime);
            materialPersonalUsedDataVo.setEndTime(endTime);
        }
        pageResult.setResult(materialPersonalUsedDataVos);
        return pageResult;
    }

    /**
     * 查询门店/区经使用数据
     *
     * @param storeIds
     * @return
     */
    public Page<MaterialStoreUsedDataVO> queryMaterialStoreUseReport(MaterialReportQO materialReportQO, List<String> storeIds) {

        Integer reportType = materialReportQO.getReportType();
        Integer pageNo = materialReportQO.getPageNum();
        Integer pageSize = materialReportQO.getPageSize();
        String clerkId = materialReportQO.getClerkId();
        String enterpriseId = materialReportQO.getEnterpriseId();
        String orderField = materialReportQO.getOrderByField();
        String order = materialReportQO.getOrder();
        // 获取当前时间周期
        DateTime startTime = null;
        DateTime endTime = null;
        String bizDate = materialReportQO.getBizDate();
        String apolloKey = MATERIAL_STORE_WEEK_DATA;
        if (MaterialReportType.WEEK.getCode().equals(reportType)) {
            // 周报
            startTime = DateUtil.beginOfWeek(DateUtil.lastWeek());
            endTime = DateUtil.endOfWeek(DateUtil.lastWeek());
        } else {
            startTime = DateUtil.beginOfMonth(DateUtil.lastWeek());
            endTime = DateUtil.endOfMonth(DateUtil.lastWeek());
            apolloKey = MATERIAL_STORE_MONTH_DATA;
        }
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> inlineParams = new HashMap<>();
        params.put("pageNo", pageNo);
        params.put("pageSize", pageSize);
        params.put("inFields", inlineParams);
        if (StringUtils.isNotBlank(clerkId)) {
            inlineParams.put("clerkId", clerkId);
        }
        inlineParams.put("enterpriseId", enterpriseId);
        inlineParams.put("bizDate", bizDate);
        if (CollectionUtil.isNotEmpty(storeIds)) {
            inlineParams.put("storeId", StringUtils.join(storeIds, ","));
        }
        if (StringUtils.isNotBlank(orderField)) {
            String orderStr = " " + order;
            inlineParams.put("orderByField", orderField + orderStr);
        }else {
            inlineParams.put("orderByField", "enterpriseId asc ");
        }
        Map<String, Object> result = this.doHttp(JSON.toJSONString(params), apolloKey);
        if (result.get("data") == null) {
            return new Page<>();
        }
        Page<MaterialStoreUsedDataVO> pageResult = new Page<>();
        List<JSONObject> jsonObjects = JSON.parseArray(JSON.toJSONString(result.get("data")), JSONObject.class);
        if (CollectionUtils.isEmpty(jsonObjects)) {
            return new Page<>();
        }
        List<MaterialStoreUsedDataVO> materialStoreUsedDataVOS = jsonObjects.stream()
                .map(item -> {
                    MaterialStoreUsedDataVO temp = JSONObject.parseObject(item.toJSONString(), MaterialStoreUsedDataVO.class);
                    temp.setDayAvgUseRate(item.getBigDecimal("dayAvgUseBindProportion"));
                    temp.setClickUserNum(item.getInteger("userClickNum"));
                    temp.setConvSalesNmt(item.getBigDecimal("convSalesAmt"));
                    return temp;
                })
                .collect(Collectors.toList());
        for (MaterialStoreUsedDataVO materialStoreUsedDataVO : materialStoreUsedDataVOS) {
            materialStoreUsedDataVO.setStartTime(startTime);
            materialStoreUsedDataVO.setEndTime(endTime);
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.get("page")), JSONObject.class);
        int totalCount = jsonObject.getIntValue("totalCount");
        int totalPage = jsonObject.getIntValue("totalPage");
        pageResult.setTotalCount(totalCount);
        pageResult.setTotalPage(totalPage);
        pageResult.setResult(materialStoreUsedDataVOS);
        return pageResult;
    }

    /**
     * 取经数据概览数据
     *
     * @return
     */
    public MaterialAreaUsedDataVO queryMaterialAreaOverviewData(String enterpriseId, String clerkId,
                                                                Integer reportType, List<String> storeIds, String bizDate) {

        // 获取当前时间周期
        DateTime startTime = null;
        DateTime endTime = null;
        String apolloKey = MATERIAL_AREA_WEEK_DATA;
        if (MaterialReportType.WEEK.getCode().equals(reportType)) {
            // 周报
            startTime = DateUtil.beginOfWeek(DateUtil.lastWeek());
            endTime = DateUtil.endOfWeek(DateUtil.lastWeek());
        } else {
            startTime = DateUtil.beginOfMonth(DateUtil.lastWeek());
            endTime = DateUtil.endOfMonth(DateUtil.lastWeek());
            apolloKey = MATERIAL_AREA_MONTH_DATA;
        }
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> inlineParams = new HashMap<>();
        params.put("inFields", inlineParams);
        if (StringUtils.isNotBlank(clerkId)) {
            inlineParams.put("clerkId", clerkId);
        }
        inlineParams.put("enterpriseId", enterpriseId);
        inlineParams.put("bizDate", bizDate);
        if (CollectionUtil.isNotEmpty(storeIds)) {
            inlineParams.put("storeId", StringUtils.join(storeIds, ","));
        }
        Map<String, Object> result = this.doHttp(JSON.toJSONString(params), apolloKey);
        if (result.get("data") == null) {
            return new MaterialAreaUsedDataVO();
        }
        List<MaterialAreaUsedDataVO> areaUsedDataVOS = JSON.parseArray(JSON.toJSONString(result.get("data")), MaterialAreaUsedDataVO.class);
        if (CollectionUtils.isEmpty(areaUsedDataVOS)) {
            return new MaterialAreaUsedDataVO();
        }
        MaterialAreaUsedDataVO materialAreaUsedDataVO = areaUsedDataVOS.get(0);
        materialAreaUsedDataVO.setStartTime(startTime);
        materialAreaUsedDataVO.setEndTime(endTime);
        return materialAreaUsedDataVO;
    }


    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();
    }

    /**
     * 会员最近30天的浏览素材数量
     *
     * @param enterpriseId
     * @param storeId
     * @param clerkId
     * @param memberIds
     * @return
     */
    public Map<String, Integer> queryMemberVisitMap(String enterpriseId, String storeId, String clerkId, List<String> memberIds) {

        Map<String, Object> params = new HashMap<>();
        Map<String, Object> inlineParams = new HashMap<>();
        params.put("inFields", inlineParams);
        if (StringUtils.isNotBlank(clerkId)) {
            inlineParams.put("clerkId", clerkId);
        }
        inlineParams.put("enterpriseId", enterpriseId);
        inlineParams.put("customerId", StringUtils.join(memberIds, ","));
        Map<String, Object> result = this.doHttp(JSON.toJSONString(params), MEMBER_RECENTLY_30_DAY_VISIT);
        if (result.get("data") == null) {
            return Collections.emptyMap();
        }
        List<MemberVisitMaterialBO> memberVisitMaterialBos = JSON.parseArray(JSON.toJSONString(result.get("data")), MemberVisitMaterialBO.class);
        if (CollectionUtils.isEmpty(memberVisitMaterialBos)) {
            return Collections.emptyMap();
        }
        return memberVisitMaterialBos
                .stream()
                .collect(Collectors.toMap(MemberVisitMaterialBO::getCustomerId, item -> Optional.ofNullable(item.getMatlNum30Day())
                        .map(Integer::new).orElse(0), (v1, v2) -> v1));
    }
}
