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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.business.order.dto.ordermanage.ListOrderItemDTO;
import com.gic.business.order.dto.ordermanage.OrderOutInfoDTO;
import com.gic.business.order.qdto.ordermanage.OrderInfoQDTO;
import com.gic.business.order.service.ordermanage.OrderInfoOutApiService;
import com.gic.haoban.manage.service.pojo.bo.content.InteractRecordExtendInfoBO;
import com.gic.haoban.manage.service.pojo.bo.content.context.InteractRecordMessageContext;
import com.gic.haoban.manage.service.pojo.qo.content.InteractRecordQO;
import com.gic.haoban.manage.service.service.content.InteractRecordService;
import com.gic.member.api.dto.MemberDTO;
import com.gic.member.api.service.MemberService;
import com.gic.order.api.service.sharding.OrderApiService;
import com.gic.orderecommerce.api.constant.OrderChannelEnum;
import com.gic.orderecommerce.api.dto.MallEorderDTO;
import com.gic.orderecommerce.api.service.EcommerceOrderOutputApiService;
import com.gic.store.goods.dto.goods.GoodsSpuInfoDTO;
import com.gic.store.goods.dto.qdto.GoodsListQDTO;
import com.gic.store.goods.service.GoodsCenterApiService;
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.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author MUSI
 * @Date 2023/3/29 3:48 PM
 * @Description
 * @Version
 **/
@Slf4j
@Component
public class InteractRecordMessageBuilder {

    @Autowired
    private InteractRecordService interactRecordService;
    @Autowired
    private MemberService memberService;
    @Autowired
    OrderInfoOutApiService orderInfoOutApiService;
    @Autowired
    private GoodsCenterApiService goodsCenterApiService;
    @Autowired
    private EcommerceOrderOutputApiService ecommerceOrderOutputApiService;
    @Autowired
    private OrderApiService orderApiService;

    /**
     * 计算互动记录的访问次数
     * // 通过clerkId、memberId、materialId 查询之前存在的记录总数，本次是第几次访问 在之前的记录总数上加1
     *
     * @param context
     */
    public void calcCustomerVisitTimes(InteractRecordMessageContext context) {
        InteractRecordQO searchQo = new InteractRecordQO();
        searchQo.setClerkId(context.getInteractRecordMessageBO().getClerkId());
        searchQo.setMemberId(context.getInteractRecordMessageBO().getMemberId());
        if (StringUtils.isBlank(searchQo.getMemberId())) {
            searchQo.setUnionId(context.getInteractRecordMessageBO().getUnionId());
        }
        searchQo.setPageSize(1);
        searchQo.setBizId(context.getInteractRecordMessageBO().getMaterialId());
        Integer count = interactRecordService.countInteractRecord(searchQo);
        context.setTimes(count + 1);
    }

    /**
     * 冗余会员信息
     * @param context
     */
    public void redundantMemberInfo(InteractRecordMessageContext context) {
        String memberId = context.getInteractRecordMessageBO().getMemberId();
        if (StringUtils.isBlank(memberId)) {
            log.info("互动记录冗余会员信息 会员不存在");
            return;
        }
        MemberDTO memberDTO = memberService.queryMember(memberId);
        if (memberDTO == null) {
            log.info("查询会员信息为空 {}", memberId);
            return;
        }
        InteractRecordMessageContext.MemberInfo memberInfo = new InteractRecordMessageContext
                .MemberInfo(memberDTO.getMemberName(), memberDTO.getThirdNickname(), memberDTO.getPhoneNumber());
        context.setMemberInfo(memberInfo);
    }

    /**
     * 计算会员是否有过订单
     * @param context
     */
    public void calcHaveOrderNum(InteractRecordMessageContext context) {
        String memberId = context.getInteractRecordMessageBO().getMemberId();
        if (StringUtils.isBlank(memberId)) {
            log.info("互动记录冗余会员信息 会员id不存在");
            return;
        }
        String enterpriseId = context.getInteractRecordMessageBO().getEnterpriseId();
        context.setHasDeal(false);
        // 查询会员全渠道订单
        Integer countOfSale = orderApiService.getCountOfSale(memberId, enterpriseId);
        if (countOfSale != null && countOfSale > 0) {
            context.setHasDeal(true);
            return;
        }
        for (OrderChannelEnum value : OrderChannelEnum.values()) {
            Page<MallEorderDTO> eorderDTOPage = ecommerceOrderOutputApiService.queryEorderListByMemberId(enterpriseId, memberId, null, 1, 1, value.getChannelCode());
            if (eorderDTOPage != null && CollectionUtils.isNotEmpty(eorderDTOPage.getResult())) {
                context.setHasDeal(true);
                return;
            }
        }
    }


    /**
     * 冗余订单项信息
     * @param
     * @return
     */
    public InteractRecordExtendInfoBO.ExtendOrderInfo buildMaterialOrderItemInfo(String enterpriseId, String orderNumber) {

        OrderInfoQDTO orderInfoQDTO = new OrderInfoQDTO();
        orderInfoQDTO.setOrderNumber(orderNumber);
        orderInfoQDTO.setEnterpriseId(enterpriseId);
        ServiceResponse<OrderOutInfoDTO> serviceResponse =
                orderInfoOutApiService.queryOrderInfo(orderInfoQDTO);
        if (!serviceResponse.isSuccess()) {
            log.info("查询订单信息异常 {}", JSON.toJSONString(serviceResponse));
            return null;
        }

        List<String> goodsIds = serviceResponse.getResult()
                .getOrderItems()
                .stream()
                .map(ListOrderItemDTO::getMallProId)
                .distinct()
                .collect(Collectors.toList());
        Map<String, Integer> goodsSourceTypeMap = queryGoodsSimpleInfo(enterpriseId, goodsIds);

        OrderOutInfoDTO orderOutInfoDTO = serviceResponse.getResult();
        InteractRecordExtendInfoBO.ExtendOrderInfo extendOrderInfo = new InteractRecordExtendInfoBO.ExtendOrderInfo();
        extendOrderInfo.setOrderNumber(orderOutInfoDTO.getOrderNumber());
        extendOrderInfo.setOrderCreateTime(orderOutInfoDTO.getCreateTime());
        extendOrderInfo.setOrderTotalNum(orderOutInfoDTO.getOrderItems().size());
        extendOrderInfo.setOrderPay(orderOutInfoDTO.getReceivableAmount());
        extendOrderInfo.setRealPay(orderOutInfoDTO.getPayAmount());
        List<InteractRecordExtendInfoBO.ExtendGoodsInfo> goodsInfos = orderOutInfoDTO.getOrderItems()
                .stream()
                .map(item -> {
                    InteractRecordExtendInfoBO.ExtendGoodsInfo goodsInfo = new InteractRecordExtendInfoBO.ExtendGoodsInfo();
                    goodsInfo.setGoodsCode(item.getProCode());
                    goodsInfo.setGoodsName(item.getMallProName());
                    goodsInfo.setOrderNum(item.getMallProNumber().intValue());
                    goodsInfo.setGoodsImageUrl(item.getMallProImageUrl());
                    goodsInfo.setSalePrice(BigDecimal.valueOf(item.getMallProPrice()));
                    goodsInfo.setGoodsNorm(this.convertSkuNorm(item.getMallProSkuAttr()));
                    Integer sourceType = Optional.ofNullable(goodsSourceTypeMap.get(item.getMallProId())).orElse(2);
                    goodsInfo.setSourceType(sourceType);
                    return goodsInfo;
                })
                .collect(Collectors.toList());
        extendOrderInfo.setOrderGoodsInfos(goodsInfos);
        return extendOrderInfo;
    }

    private Map<String, Integer> queryGoodsSimpleInfo(String enterpriseId, List<String> goodsIds) {
        GoodsListQDTO goodsListQDTO = new GoodsListQDTO();
        goodsListQDTO.setEnterpriseId(enterpriseId);
        goodsListQDTO.setIncludeGoodsIds(goodsIds);
        goodsListQDTO.setPageSize(goodsIds.size() + 1);
        ServiceResponse<Page<GoodsSpuInfoDTO>> serviceResponse =
                goodsCenterApiService.queryStoreGoodsList(goodsListQDTO);
        if (!serviceResponse.isSuccess() || CollectionUtils.isEmpty(serviceResponse.getResult().getResult())) {
            return Collections.emptyMap();
        }
        return serviceResponse.getResult()
                .getResult()
                .stream()
                .collect(Collectors.toMap(GoodsSpuInfoDTO::getGoodsId, GoodsSpuInfoDTO::getSourceType, (v1, v2) -> v1));
    }

    private String convertSkuNorm(String skuAttr) {
        if (StringUtils.isBlank(skuAttr)) {
            return null;
        }
        List<JSONObject> jsonObjects = JSON.parseArray(skuAttr, JSONObject.class);
        List<String> norms = jsonObjects
                .stream()
                .map(item -> {
                    String propName = item.getString("propName");
                    String valueName = item.getString("valueName");
                    return propName + "," + valueName;
                })
                .collect(Collectors.toList());
        return StringUtils.join(norms, ",");
    }

}
