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

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.enterprise.api.dto.page.EnterpriseWxaLinkDTO;
import com.gic.enterprise.api.service.EnterpriseWxaLinkService;
import com.gic.haoban.manage.api.enums.content.MaterialInteractRecordEventType;
import com.gic.haoban.manage.api.enums.content.ShareBizType;
import com.gic.haoban.manage.api.enums.content.ShareCustomerSourceType;
import com.gic.haoban.manage.api.enums.content.TriggerCustomerChannelType;
import com.gic.haoban.manage.service.entity.content.TabHaobanInteractRecord;
import com.gic.haoban.manage.service.pojo.bo.content.InteractRecordBO;
import com.gic.haoban.manage.service.pojo.bo.content.InteractRecordExtendInfoBO;
import com.gic.haoban.manage.service.pojo.bo.content.PotentialCustomerBO;
import com.gic.haoban.manage.service.pojo.bo.content.context.InteractRecordMessageContext;
import com.gic.haoban.manage.service.pojo.bo.content.message.InteractRecordMessageBO;
import com.gic.store.goods.dto.goods.GoodsInfoSimpleDTO;
import com.gic.store.goods.dto.goods.GoodsSpuInfoDTO;
import com.gic.store.goods.service.GoodsInfoOutApiService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author MUSI
 * @Date 2023/3/29 2:49 PM
 * @Description
 * @Version
 **/
@Slf4j
@Component
public class InteractRecordBuilder {

    @Autowired
    private InteractRecordMessageBuilder interactRecordMessageBuilder;
    @Autowired
    private GoodsInfoOutApiService goodsInfoOutApiService;
    @Autowired
    private GoodsInfoAdaptor goodsInfoAdaptor;
    @Autowired
    private EnterpriseWxaLinkService enterpriseWxaLinkService;

    /**
     * 互动记录描述
     *
     * @param interactRecord
     * @return
     */
    public String buildDesc(TabHaobanInteractRecord interactRecord) {
        return this.buildDesc(interactRecord.getChannelSource(), interactRecord.getShareSource(),interactRecord.getEventType(), interactRecord.getBizType());
    }

    /**
     * 基于渠道和事件类型拼接信息
     *
     * @param channelSource
     * @param eventType
     * @return
     */
    public String buildDesc(Integer channelSource, Integer shareSource,Integer eventType, Integer bizType) {
        StringBuilder stringBuilder = new StringBuilder();
        if (TriggerCustomerChannelType.showDescChannel().contains(channelSource)) {
            TriggerCustomerChannelType channelType = TriggerCustomerChannelType.getInstance(channelSource);
            if (channelType != null) {
                stringBuilder.append(String.format("通过%s", channelType.getDesc()));
            }
        }
        MaterialInteractRecordEventType instance = MaterialInteractRecordEventType.getInstance(eventType);
        if (instance != null) {
            String shareSourceMessage = shareSource != null && StringUtils.isNotBlank(ShareCustomerSourceType.getDesc(shareSource)) ?
                    "使用" + ShareCustomerSourceType.getDesc(shareSource) : "";
            String text = String.format(instance.getDesc(), shareSourceMessage, ShareBizType.getDescWithCode(bizType), ShareBizType.getGoodsTextWithCode(bizType));
            if (MaterialInteractRecordEventType.VISIT_PRODUCT.getCode().equals(eventType) && ShareBizType.GOODS.getCode().equals(bizType)) {
                text = "浏览了你分享的商品";
            }
            stringBuilder.append(text);
        }
        return stringBuilder.toString();
    }

    public Map<String,GoodsInfoSimpleDTO> buildGoodsMap(String enterprieseId,List<TabHaobanInteractRecord> list) {
        Set<String> goodsIdSet = Sets.newHashSet();
        list.forEach(item -> {
            String extendInfo = Optional.ofNullable(item.getExtendInfo()).orElse("{}");
            InteractRecordExtendInfoBO extendInfoBO = JSONObject.parseObject(extendInfo, InteractRecordExtendInfoBO.class);
            List<String> goodsIds = extendInfoBO.getGoodsIds();
            if (CollectionUtils.isNotEmpty(goodsIds)) {
                goodsIdSet.addAll(goodsIds);
            }
            List<List<String>> groupGoodsIds = extendInfoBO.getGroupGoodsIds();
            if (CollectionUtils.isNotEmpty(groupGoodsIds)) {
                goodsIdSet.addAll(groupGoodsIds.stream().flatMap(Collection::stream).collect(Collectors.toList()));
            }
        });
        if (CollectionUtils.isEmpty(goodsIdSet)) {
            return new HashMap<>();
        }
        return goodsInfoAdaptor.queryGoodsAndMinPrice(enterprieseId,Lists.newArrayList(goodsIdSet));
    }


    /**
     * 互动记录转换扩展信息
     *
     * @param interactRecord
     * @return
     */
    public InteractRecordExtendInfoBO convertExtendInfo(TabHaobanInteractRecord interactRecord,Map<String, GoodsInfoSimpleDTO> goodsMap) {
        if (interactRecord == null) {
            log.info("互动记录为空");
            return null;
        }
        if (StringUtils.isBlank(interactRecord.getExtendInfo())) {
            log.info("互动记录扩展信息为空 {}", interactRecord.getId());
            return null;
        }
        InteractRecordExtendInfoBO extendInfo = JSON.parseObject(interactRecord.getExtendInfo(), new TypeReference<InteractRecordExtendInfoBO>() {
        });
        if (MaterialInteractRecordEventType.VISIT_PRODUCT.getCode().equals(interactRecord.getEventType())
                || MaterialInteractRecordEventType.ADD_SHOPPING_CART.getCode().equals(interactRecord.getEventType())
                || MaterialInteractRecordEventType.ORDER.getCode().equals(interactRecord.getEventType())
                || MaterialInteractRecordEventType.VISIT_MATERIAL.getCode().equals(interactRecord.getEventType())) {
            convertGroupGoods(interactRecord.getEnterpriseId(), extendInfo, goodsMap);
            // 浏览商品事件
            List<String> visitGoodsIds = extendInfo.getGoodsIds();
            if (CollectionUtils.isEmpty(visitGoodsIds)) {
                log.info("组装浏览商品信息, 商品信息不存在 {}", interactRecord.getExtendInfo());
                return extendInfo;
            }
            // 拼接商品信息
            List<InteractRecordExtendInfoBO.ExtendGoodsInfo> extendGoodsInfos =
                    this.convertGoodsInfo(visitGoodsIds, interactRecord.getEnterpriseId(),goodsMap);
            extendInfo.setExtendGoodsInfos(extendGoodsInfos);
            extendInfo.setInvalidGoodsNum(visitGoodsIds.size() - extendGoodsInfos.size());
            return extendInfo;
        }
//        if (MaterialInteractRecordEventType.ORDER.getCode().equals(interactRecord.getEventType())
//                && ShareBizType.GOODS.getCode().equals(interactRecord.getBizType())) {
//            InteractRecordExtendInfoBO.ExtendGoodsInfo extendGoodsInfo = new InteractRecordExtendInfoBO.ExtendGoodsInfo();
//            extendGoodsInfo.setGoodsName();
//            extendGoodsInfo.setGoodsCode(item.getGoodsCode());
//            extendGoodsInfo.setGoodsImageUrl(item.getGoodsImageUrl());
//            extendGoodsInfo.setSalePrice(item.getSalePrice());
//            extendGoodsInfo.setSourceType(item.getSourceType());
//            GoodsSpuInfoDTO goodsSpuInfoDTO = goodsMinPriceMap.get(item.getGoodsId());
//            if (goodsSpuInfoDTO != null && goodsSpuInfoDTO.getMinPrice() != null) {
//                extendGoodsInfo.setSalePrice(goodsSpuInfoDTO.getMinPrice());
//            }
//        }
        return extendInfo;
    }

    private void convertGroupGoods(String enterpriseId, InteractRecordExtendInfoBO extendInfo,Map<String, GoodsInfoSimpleDTO> goodsMap) {
        List<List<String>> groupGoodsIds = extendInfo.getGroupGoodsIds();
        // 组装商品组数据
        if (CollectionUtils.isNotEmpty(groupGoodsIds)) {
            List<String> groupGoodsIdList = groupGoodsIds.stream().flatMap(Collection::stream).collect(Collectors.toList());
            List<InteractRecordExtendInfoBO.ExtendGoodsInfo> extendGoodsInfos =
                    this.convertGoodsInfo(groupGoodsIdList, enterpriseId,goodsMap);
            if (CollectionUtils.isNotEmpty(extendGoodsInfos)) {
                Map<String, InteractRecordExtendInfoBO.ExtendGoodsInfo> goodsInfoMap = extendGoodsInfos.stream()
                        .collect(Collectors.toMap(InteractRecordExtendInfoBO.ExtendGoodsInfo::getGoodsId, Function.identity(),(e,x)->e));
                List<List<InteractRecordExtendInfoBO.ExtendGoodsInfo>> groupExtendGoodsInfos = new ArrayList<>();
                for (List<String> groupGoodsId : groupGoodsIds) {
                    List<InteractRecordExtendInfoBO.ExtendGoodsInfo> list =
                            groupGoodsId.stream()
                            .map(goodsInfoMap::get)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(list)) {
                        groupExtendGoodsInfos.add(list);
                    }
                }
                extendInfo.setGroupExtendGoodsInfos(groupExtendGoodsInfos);
                extendInfo.setGroupInvalidGoodsNum(groupGoodsIdList.size() - groupExtendGoodsInfos.stream().mapToInt(List::size).sum());
            }
        }
    }

    private List<InteractRecordExtendInfoBO.ExtendGoodsInfo> convertGoodsInfo(List<String> visitGoodsIds, String enterpriseId,Map<String, GoodsInfoSimpleDTO> goodsMap) {
        if (CollectionUtils.isEmpty(visitGoodsIds)) {
            return Collections.emptyList();
        }
        List<GoodsInfoSimpleDTO> list = new ArrayList<>();
        Map<String, GoodsSpuInfoDTO> goodsMinPriceMap;
        // 修改为支持外部先批量查询
        if (goodsMap == null) {
            ServiceResponse<List<GoodsInfoSimpleDTO>> serviceResponse = goodsInfoOutApiService.queryGoodsSimpleInfo(visitGoodsIds);
            // 1:已上线，2:未上线，3:回收站
            if (!serviceResponse.isSuccess()) {
                log.info("查询商品异常 {}", JSON.toJSONString(serviceResponse));
                return Collections.emptyList();
            }
            if (CollectionUtils.isEmpty(serviceResponse.getResult())) {
                log.info("查询商品为空 {}", JSON.toJSONString(serviceResponse));
                return Collections.emptyList();
            }
            list = serviceResponse.getResult();
            goodsMinPriceMap = goodsInfoAdaptor.queryGoodsMinPrice(enterpriseId, visitGoodsIds);
        }else {
            goodsMinPriceMap = new HashMap<>();
            for (String goodsId : visitGoodsIds) {
                GoodsInfoSimpleDTO goodsInfoSimpleDTO = goodsMap.get(goodsId);
                if (goodsInfoSimpleDTO != null) {
                    list.add(goodsInfoSimpleDTO);
                }
            }
        }
        List<Integer> excludeStatus = Arrays.asList(0, 3);
        return list
                .stream()
                .filter(item -> !excludeStatus.contains(item.getStatus()))
                .map(item -> {
                    InteractRecordExtendInfoBO.ExtendGoodsInfo extendGoodsInfo = new InteractRecordExtendInfoBO.ExtendGoodsInfo();
                    extendGoodsInfo.setGoodsId(item.getGoodsId());
                    extendGoodsInfo.setGoodsName(item.getGoodsName());
                    extendGoodsInfo.setGoodsCode(item.getGoodsCode());
                    extendGoodsInfo.setGoodsImageUrl(item.getGoodsImageUrl());
                    extendGoodsInfo.setSalePrice(item.getSalePrice());
                    extendGoodsInfo.setSourceType(item.getSourceType());
                    GoodsSpuInfoDTO goodsSpuInfoDTO = goodsMinPriceMap.get(item.getGoodsId());
                    if (goodsSpuInfoDTO != null && goodsSpuInfoDTO.getMinPrice() != null) {
                        extendGoodsInfo.setSalePrice(goodsSpuInfoDTO.getMinPrice());
                    }
                    return extendGoodsInfo;
                })
                .collect(Collectors.toList());

    }

    /**
     * 计算商品浏览数量
     * @param interactRecordBO
     * @return
     */
    public void warpRelationGoodsNum(InteractRecordBO interactRecordBO) {
        if (interactRecordBO == null) {
            log.info("互动记录不存在");
            return;
        }
        if (interactRecordBO.getExtendInfo() == null) {
            log.info("互动记录不存在扩展信息 {}", JSON.toJSONString(interactRecordBO));
            return;
        }
        InteractRecordExtendInfoBO extendInfo = interactRecordBO.getExtendInfo();
        interactRecordBO.setVisitGoodsNum(0);
        if (CollectionUtils.isNotEmpty(extendInfo.getGoodsIds())) {
            interactRecordBO.setVisitGoodsNum(extendInfo.getGoodsIds().size());
        }
        interactRecordBO.setOrderGoodsNum(0);
        if (CollectionUtils.isNotEmpty(extendInfo.getExtendOrderInfos())) {
            Integer orderGoodsNum = extendInfo.getExtendOrderInfos()
                    .stream()
                    .map(item -> item.getOrderGoodsInfos().size())
                    .reduce(0, Integer::sum);
            interactRecordBO.setOrderGoodsNum(orderGoodsNum);
        }
    }

    public PotentialCustomerBO build(TabHaobanInteractRecord interactRecord) {
        PotentialCustomerBO temp = new PotentialCustomerBO();
        BeanUtils.copyProperties(interactRecord, temp);
        temp.setId(null);
        // 获取会员信息
        InteractRecordMessageContext.MemberInfo memberInfo = interactRecordMessageBuilder.queryMemberInfo(interactRecord.getMemberId());
        if (memberInfo != null) {
            temp.setMemberName(memberInfo.getMemberName());
            temp.setMemberNickName(memberInfo.getMemberNickName());
            temp.setMemberImageUrl(memberInfo.getMemberImgUrl());
            temp.setMemberPhone(memberInfo.getMemberPhone());
        }
        temp.setStarFlag(0);
        temp.setSeeFlag(0);
        temp.setLastAccessTime(interactRecord.getCreateTime());
        temp.setCreateTime(new Date());
        temp.setUpdateTime(new Date());
        temp.setDeleteFlag(0);
        // 查询memberId是否成交过订单
        boolean hasOrder = interactRecordMessageBuilder.queryMemberHasOrder(interactRecord.getMemberId(), interactRecord.getEnterpriseId());
        temp.setDealRecordNum(hasOrder ? 1 : 0);
        return temp;
    }

    public Map<String,List<List<String>>> getGroupGoodsIdByWxaLinkIds(List<String> wxaLinkIds) {
        if (CollectionUtils.isEmpty(wxaLinkIds)) {
            return null;
        }
        List<EnterpriseWxaLinkDTO> linkList = enterpriseWxaLinkService.listLinkInfo(wxaLinkIds);
        if (CollectionUtils.isEmpty(linkList)) {
            return null;
        }
        Map<String, List<List<String>>> map = new HashMap<>();
        for (EnterpriseWxaLinkDTO linkInfo : linkList) {
            String pageLink = linkInfo.getPageLink();
            String id = linkInfo.getId();
            if (StringUtils.isBlank(pageLink)) {
                return null;
            }
            String params = JSONObject.parseObject(pageLink).getString("params");
            if (StringUtils.isBlank(params)) {
                return null;
            }
            String proIdJSON = JSONObject.parseObject(params).getString("proIdJSON");
            if (StringUtils.isBlank(proIdJSON)) {
                return null;
            }
            map.put(id,JSON.parseObject(proIdJSON, new cn.hutool.core.lang.TypeReference<List<List<String>>>() {}));
        }
        return map;
    }

    public Integer getGoodsCount(InteractRecordMessageBO interactRecordMessageBO, Map<String, List<List<String>>> multipleMap) {
        Integer goodsCount = 1;
        if (StringUtils.isBlank(interactRecordMessageBO.getWxaLinkId())) {
            return goodsCount;
        }
        if (MapUtil.isEmpty(multipleMap)) {
            return goodsCount;
        }
        List<List<String>> groupGoodsIds = multipleMap.get(interactRecordMessageBO.getWxaLinkId());
        if (CollectionUtils.isNotEmpty(groupGoodsIds)) {
            goodsCount = groupGoodsIds.stream().mapToInt(List::size).sum();
            log.info("多商品分享页面goodsCount:{}", goodsCount);
        }
        return goodsCount;
    }

    public Map<String,InteractRecordExtendInfoBO> buildGroupGoodsByWxaLinkId(String enterpriseId,List<String> wxaLinkIds) {
        Map<String, InteractRecordExtendInfoBO> extendInfoBOMap = new HashMap<>();
        Map<String, List<List<String>>> map = getGroupGoodsIdByWxaLinkIds(wxaLinkIds);
        if (MapUtil.isEmpty(map)) {
            return extendInfoBOMap;
        }
        map.forEach((wxaLinkId, groupIds) -> {
            InteractRecordExtendInfoBO extendInfoBO = new InteractRecordExtendInfoBO();
            extendInfoBO.setGroupGoodsIds(groupIds);
            convertGroupGoods(enterpriseId, extendInfoBO,null);
            extendInfoBOMap.put(wxaLinkId, extendInfoBO);
        });
        return extendInfoBOMap;
    }
}
