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.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.haoban.manage.api.enums.content.MaterialInteractRecordEventType;
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.GoodsSpuInfoDTO;
import com.gic.store.goods.dto.qdto.GoodsListQDTO;
import com.gic.store.goods.service.GoodsCenterApiService;
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.stream.Collectors;

/**
 * @Author MUSI
 * @Date 2023/3/29 2:49 PM
 * @Description
 * @Version
 **/
@Slf4j
@Component
public class InteractRecordBuilder {
    @Autowired
    private GoodsCenterApiService goodsCenterApiService;
    @Autowired
    private InteractRecordMessageBuilder interactRecordMessageBuilder;

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

    /**
     * 基于渠道和事件类型拼接信息
     *
     * @param channelSource
     * @param eventType
     * @return
     */
    public String buildDesc(Integer channelSource, Integer eventType) {
        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) {
            stringBuilder.append(instance.getDesc());
        }
        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())) {
            // 浏览商品事件
            List<String> visitGoodsIds = extendInfo.getGoodsIds();
            if (CollectionUtils.isEmpty(visitGoodsIds)) {
                log.info("组装浏览商品信息, 商品信息不存在 {}", interactRecord.getExtendInfo());
                return null;
            }
            // 拼接商品信息
            List<InteractRecordExtendInfoBO.ExtendGoodsInfo> extendGoodsInfos =
                    this.convertGoodsInfo(visitGoodsIds, interactRecord.getEnterpriseId());
            extendInfo.setExtendGoodsInfos(extendGoodsInfos);
            extendInfo.setInvalidGoodsNum(visitGoodsIds.size() - extendGoodsInfos.size());
            return extendInfo;
        }
        return extendInfo;
    }

    private List<InteractRecordExtendInfoBO.ExtendGoodsInfo> convertGoodsInfo(List<String> visitGoodsIds, String enterpriseId) {
        if (CollectionUtils.isEmpty(visitGoodsIds)) {
            return Collections.emptyList();
        }
        GoodsListQDTO goodsListQDTO = new GoodsListQDTO();
        goodsListQDTO.setEnterpriseId(enterpriseId);
        goodsListQDTO.setIncludeGoodsIds(visitGoodsIds);
        goodsListQDTO.setPageSize(visitGoodsIds.size() + 1);
        ServiceResponse<Page<GoodsSpuInfoDTO>> serviceResponse =
                goodsCenterApiService.queryStoreGoodsList(goodsListQDTO);
        // 1:已上线，2:未上线，3:回收站
        if (!serviceResponse.isSuccess()) {
            log.info("查询商品异常 {}", JSON.toJSONString(serviceResponse));
            return Collections.emptyList();
        }
        if (CollectionUtils.isEmpty(serviceResponse.getResult().getResult())) {
            log.info("查询商品为空 {}", JSON.toJSONString(serviceResponse));
            return Collections.emptyList();
        }
        List<Integer> excludeStatus = Arrays.asList(0, 3);
        return serviceResponse.getResult()
                .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.getImageUrl());
                    extendGoodsInfo.setSalePrice(item.getSalePrice());
                    extendGoodsInfo.setSourceType(item.getSourceType());
                    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;
    }
}
