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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gic.api.base.commons.ServiceResponse;
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.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.store.goods.dto.goods.GoodsInfoSimpleDTO;
import com.gic.store.goods.dto.goods.GoodsSpuInfoDTO;
import com.gic.store.goods.service.GoodsInfoOutApiService;
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.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
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;

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

    /**
     * 基于渠道和事件类型拼接信息
     *
     * @param channelSource
     * @param eventType
     * @return
     */
    public String buildDesc(Integer channelSource, 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 text = String.format(instance.getDesc(), ShareBizType.getDescWithCode(bizType));
            if (MaterialInteractRecordEventType.VISIT_PRODUCT.getCode().equals(eventType) && ShareBizType.GOODS.getCode().equals(bizType)) {
                text = "浏览了你分享的商品";
            }
            stringBuilder.append(text);
        }
        return stringBuilder.toString();
    }


    /**
     * 互动记录转换扩展信息
     *
     * @param interactRecord
     * @return
     */
    public InteractRecordExtendInfoBO convertExtendInfo(TabHaobanInteractRecord interactRecord) {
        if (interactRecord == null) {
            log.info("互动记录为空");
            return null;
        }
        if (StringUtils.isBlank(interactRecord.getExtendInfo())) {
            log.info("互动记录扩展信息为空 {}", interactRecord.getId());
            return null;
        }
        if (MaterialInteractRecordEventType.VISIT_MATERIAL.getCode().equals(interactRecord.getEventType())) {
            // 浏览素材事件无扩展信息
            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())) {
            // 浏览商品事件
            List<String> visitGoodsIds = extendInfo.getGoodsIds();
            if (CollectionUtils.isEmpty(visitGoodsIds)) {
                log.info("组装浏览商品信息, 商品信息不存在 {}", interactRecord.getExtendInfo());
                return extendInfo;
            }
            // 拼接商品信息
            List<InteractRecordExtendInfoBO.ExtendGoodsInfo> extendGoodsInfos =
                    this.convertGoodsInfo(visitGoodsIds, interactRecord.getEnterpriseId());
            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 List<InteractRecordExtendInfoBO.ExtendGoodsInfo> convertGoodsInfo(List<String> visitGoodsIds, String enterpriseId) {
        if (CollectionUtils.isEmpty(visitGoodsIds)) {
            return Collections.emptyList();
        }
        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();
        }
        Map<String, GoodsSpuInfoDTO> goodsMinPriceMap = goodsInfoAdaptor.queryGoodsMinPrice(enterpriseId, visitGoodsIds);
        List<Integer> excludeStatus = Arrays.asList(0, 3);
        return serviceResponse.getResult()
                .stream()
                .filter(item -> !excludeStatus.contains(item.getStatus()))
                .map(item -> {
                    InteractRecordExtendInfoBO.ExtendGoodsInfo extendGoodsInfo = new InteractRecordExtendInfoBO.ExtendGoodsInfo();
                    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;
    }
}
