

package com.tmerclub.cloud.product.service.impl;

import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.distribution.feign.DistributionFeignClient;
import com.tmerclub.cloud.api.distribution.vo.DistributionSpuVO;
import com.tmerclub.cloud.api.group.feign.GroupFeignClient;
import com.tmerclub.cloud.api.seckill.feign.SeckillFeignClient;
import com.tmerclub.cloud.api.seckill.vo.SeckillApiVO;
import com.tmerclub.cloud.api.supplier.bo.SupplierDetailBO;
import com.tmerclub.cloud.api.supplier.feign.SupplierDetailFeignClient;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.constant.StatusEnum;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.i18n.LanguageEnum;
import com.tmerclub.cloud.common.product.bo.*;
import com.tmerclub.cloud.common.product.constant.CommissionSpuStatus;
import com.tmerclub.cloud.common.product.constant.SpuType;
import com.tmerclub.cloud.common.product.constant.SupplierDeliveryType;
import com.tmerclub.cloud.common.product.constant.SupplierSpuType;
import com.tmerclub.cloud.common.product.vo.*;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.product.mapper.SpuMapper;
import com.tmerclub.cloud.product.model.SpuExtension;
import com.tmerclub.cloud.product.service.*;
import com.tmerclub.cloud.product.service.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 商品es信息处理
 *
 * @author tmerclub
 * @date 2020-10-28 15:27:24
 */
@Service
public class SpuEsSearchServiceImpl implements SpuEsSearchService {

    private static final Logger LOG = LoggerFactory.getLogger(SpuEsSearchServiceImpl.class);

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuExtensionService spuExtensionService;
    @Autowired
    private SpuCommService spuCommService;
    @Autowired
    private SpuAttrValueService spuAttrValueService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @DubboReference
    private SupplierDetailFeignClient supplierDetailFeignClient;
    @DubboReference
    private GroupFeignClient groupFeignClient;
    @DubboReference
    private SeckillFeignClient seckillFeignClient;
    @DubboReference
    private DistributionFeignClient distributionFeignClient;

    @Override
    public EsProductBO loadEsProductBO(Long spuId) {
        // 获取商品
        EsProductBO esProductBO = spuMapper.loadEsProductBO(spuId);
        // 插入模糊搜索的商品名称
        esProductBO.setSpuNameLikeZh(esProductBO.getSpuNameZh());
        esProductBO.setSpuNameLikeEn(esProductBO.getSpuNameEn());
        // 获取sku的销量和库存
        boolean supplierDelivery = Objects.equals(esProductBO.getSupplierSpuType(), SupplierSpuType.CONSIGNMENT.value()) &&
                Objects.equals(esProductBO.getSupplierDeliveryType(), SupplierDeliveryType.SUPPLIER_DELIVERY.value());
        List<SkuVO> skuList;
        if (supplierDelivery) {
            // 代销商品且是供应商发货, 查询供应商商品的sku列表
            skuList = skuService.listSkuWithAttrBySpuId(esProductBO.getSupplierSpuId());
        } else {
            skuList = skuService.listSkuWithAttrBySpuId(esProductBO.getSpuId());
        }

        //获取sku信息
        skuService.setEsSkuStock(skuList);
        // 商品编码、商品条形码列表信息
        Set<String> partyCodes = new HashSet<>(Constant.INITIAL_CAPACITY);
        Set<String> modelIds = new HashSet<>(Constant.INITIAL_CAPACITY);
        int stockWarning = 0;
        int stock = 0;
        int saleNum = 0;
        for (SkuVO skuVO : skuList) {
            stockWarning += Objects.isNull(skuVO.getStockWarning()) ? 0 : skuVO.getStockWarning();
            stock += Objects.isNull(skuVO.getStock()) ? 0: skuVO.getStock();
            saleNum += Objects.isNull(skuVO.getSaleNum()) ? 0: skuVO.getSaleNum();
            if (StrUtil.isNotBlank(skuVO.getPartyCode())) {
                partyCodes.add(skuVO.getPartyCode());
            }
            if (StrUtil.isNotBlank(skuVO.getModelId())) {
                modelIds.add(skuVO.getModelId());
            }
        }
        // 配送方式
        esProductBO.setDeliveryMode(Json.parseObject(esProductBO.getDeliveryModeVO(), EsDeliveryModeBO.class));
        // 商品库存
        esProductBO.setStock(stock);
        // 商品销量
        esProductBO.setActualSoldNum(saleNum);
        esProductBO.setHasStock(stock > 0);
        esProductBO.setStockWarning(stockWarning);
        // 编码和条形码
        esProductBO.setPartyCodes(partyCodes);
        esProductBO.setModelIds(modelIds);
        //代销商品
        if (Objects.equals(esProductBO.getSupplierSpuType(), SupplierSpuType.CONSIGNMENT.value())) {
            //如果是代销商品获取供应商名称
            ServerResponseEntity<SupplierDetailBO> supplier = supplierDetailFeignClient.getSupplierBySupplierId(esProductBO.getSupplierId());
            if (!Objects.isNull(supplier.getData())) {
                //防止空指针异常
                esProductBO.setSupplierName(supplier.getData().getSupplierName());
            }
            //设置设置代销商品状态
            if (esProductBO.getSpuStatus() == 1) {
                //1：上架 2: 部分上架
                //判断skuChoiceStatus是否 == 1：全选
                esProductBO.setCommissionSpuStatus(esProductBO.getSkuChoiceStatus() == 1 ? CommissionSpuStatus.PUT_SHELF.value() : CommissionSpuStatus.PART_PUT_SHELF.value());
            }
            if (esProductBO.getSpuStatus() == 0) {
                //3: 下架 4: 部分下架
                //判断skuChoiceStatus是否 == 1：全选
                esProductBO.setCommissionSpuStatus(esProductBO.getSkuChoiceStatus() == 1 ? CommissionSpuStatus.OFF_SHELF.value() : CommissionSpuStatus.PART_OFF_SHELF.value());
            }
        }
        if (Objects.equals(esProductBO.getSpuStatus(), StatusEnum.ENABLE.value())) {
            esProductBO.setAppDisplay(Boolean.TRUE);
        } else {
            esProductBO.setAppDisplay(Boolean.FALSE);
        }
        // 获取分类、品牌、评论、库存、属性信息
        this.setEsProductInfo(esProductBO);
        // 团购活动商品，添加活动时间
        if (Objects.equals(esProductBO.getSpuType(), SpuType.GROUP.value())) {
            ServerResponseEntity<Date> responseEntity = groupFeignClient.getActivityStartTime(esProductBO.getActivityId());
            if (Objects.nonNull(responseEntity.getData())) {
                esProductBO.setActivityStartTime(responseEntity.getData().getTime());
            }
        }
        // 秒杀活动商品，添加活动时间,秒杀分类,并添加批次信息
        if (Objects.equals(esProductBO.getSpuType(), SpuType.SECKILL.value())) {
            ServerResponseEntity<SeckillApiVO> responseEntity = seckillFeignClient.getSeckillInfoById(esProductBO.getActivityId());
            SeckillApiVO seckillApiVO = responseEntity.getData();
            esProductBO.setActivityStartTime(seckillApiVO.getStartTime().getTime());
            esProductBO.setSelectedLot(seckillApiVO.getSelectedLot());
            esProductBO.setSeckillCategoryId(seckillApiVO.getCategoryId());
        }
        // 分销信息，添加是否属于分销商品，添加分销参数
        try {
            ServerResponseEntity<DistributionSpuVO> distributionRes = distributionFeignClient.getBySpuId(spuId);
            if (!distributionRes.isSuccess()) {
                esProductBO.setDistributionSpu(Boolean.FALSE);
                return esProductBO;
            }
            DistributionSpuVO distributionProdVO = distributionRes.getData();
            if (Objects.isNull(distributionProdVO)) {
                esProductBO.setDistributionSpu(Boolean.FALSE);
            } else {
                esProductBO.setDistributionSpu(Boolean.TRUE);
                EsDistributionInfoBO esDistributionInfoBO = new EsDistributionInfoBO();
                esDistributionInfoBO.setDistributionSpuId(distributionProdVO.getDistributionSpuId());
                esDistributionInfoBO.setAwardMode(distributionProdVO.getAwardMode());
                esDistributionInfoBO.setState(distributionProdVO.getState());
                esDistributionInfoBO.setParentAwardSet(distributionProdVO.getParentAwardSet());
                esDistributionInfoBO.setAwardNumbers(distributionProdVO.getAwardNumbers());
                esDistributionInfoBO.setParentAwardNumbers(distributionProdVO.getParentAwardNumbers());
                esProductBO.setDistributionInfo(esDistributionInfoBO);
            }
        } catch (Exception e) {
            return esProductBO;
        }
        return esProductBO;
    }


    /**
     * 获取分类、品牌、评论、库存、属性信息
     *
     * @param esProductBO 商品信息
     */
    private void setEsProductInfo(EsProductBO esProductBO) {

        // 获取品牌
        EsBrandBO brand = brandService.getEsBrandBO(esProductBO);
        esProductBO.setBrand(brand);
        // 分类数据
        this.setCategory(esProductBO);
        // 好评数量
        esProductBO.setGoodReviewNum(spuCommService.countGoodReview(esProductBO.getSpuId()));
        SpuExtension spuExtension = getSpuExtension(esProductBO);

        esProductBO.setWaterSoldNum(spuExtension.getWaterSoldNum());
        esProductBO.setSaleNum(esProductBO.getWaterSoldNum() + esProductBO.getActualSoldNum());
        esProductBO.setCommentNum(spuExtension.getCommentNum());

        // 获取属性
        List<SpuAttrValueVO> spuAttrsBySpuId = spuAttrValueService.getSpuAttrsBySpuId(esProductBO.getSpuId());
        List<SpuAttrValueVO> attrs = spuAttrsBySpuId.stream().filter(spuAttrValueVO ->
                Objects.nonNull(spuAttrValueVO.getSearchType()) && Objects.equals(spuAttrValueVO.getSearchType(), 1)).toList();
        List<EsAttrBO> esAttrBOList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (SpuAttrValueVO attr : attrs) {
            EsAttrBO esAttrBO = new EsAttrBO();
            esAttrBO.setAttrId(attr.getAttrId());
            esAttrBO.setAttrValueId(attr.getAttrValueId());
            // 国际化信息
            Map<Integer, SpuAttrValueLangVO> spuAttrValueLangMap = attr.getSpuAttrValueLangList().stream()
                    .collect(Collectors.toMap(SpuAttrValueLangVO::getLang, s -> s));
            // 中文信息
            SpuAttrValueLangVO spuAttrValueZh = spuAttrValueLangMap.get(LanguageEnum.LANGUAGE_ZH_CN.getLang());
            esAttrBO.setAttrNameZh(spuAttrValueZh.getAttrName());
            esAttrBO.setAttrValueNameZh(spuAttrValueZh.getAttrValueName());
            // 英文信息
            SpuAttrValueLangVO spuAttrValueEn = spuAttrValueLangMap.get(LanguageEnum.LANGUAGE_EN.getLang());
            if (Objects.nonNull(spuAttrValueEn)) {
                esAttrBO.setAttrNameEn(spuAttrValueEn.getAttrName());
                esAttrBO.setAttrValueNameEn(spuAttrValueEn.getAttrValueName());
            }
            esAttrBOList.add(esAttrBO);
        }
        esProductBO.setAttrs(esAttrBOList);
    }

    private void setCategory(EsProductBO esProductBO) {
        if (!Objects.equals(esProductBO.getSpuType(), SpuType.SCORE.value())) {
            // 获取平台分类数据
            CategoryVO category = categoryService.getInfo(esProductBO.getCategoryId());
            if (Objects.isNull(category)) {
                LOG.error("商品id:" + esProductBO.getSpuId() + "绑定的分类不存在");
                return;
            }
            List<ParentCategoryVO> categories = category.getCategories();
            //平台三级分类名称
            String threeCategory = category.getCategoryLangList().get(0).getName();
            //平台二级分类名称
            String twoCategory = categories.get(1).getName();
            //平台一级分类名称
            String oneCategory = categories.get(0).getName();
            String categoryNames = oneCategory + "/" + twoCategory + "/" + threeCategory;
            esProductBO.setCategoryNames(categoryNames);
            esProductBO.setPrimaryCategoryId(categories.get(0).getCategoryId());
            esProductBO.setSecondaryCategoryId(categories.get(1).getCategoryId());
            // 平台三级分类信息
            esProductBO.setCategory(handleCategory(category));
            if (esProductBO.getAppDisplay() && !Objects.equals(category.getStatus(), StatusEnum.ENABLE.value())) {
                esProductBO.setAppDisplay(Boolean.FALSE);
            }
            // 获取店铺分类数据
            if (Objects.nonNull(esProductBO.getShopCategoryId()) && !Objects.equals(esProductBO.getShopCategoryId(), -1L) && !Objects.equals(esProductBO.getShopCategoryId(), Constant.DEFAULT_ID)) {
                CategoryVO shopCategory = categoryService.getInfo(esProductBO.getShopCategoryId());
                if (Objects.isNull(shopCategory)) {
                    throw new LuckException("商品id:" + esProductBO.getSpuId() + "绑定的店铺分类不存在");
                }
                esProductBO.setShopPrimaryCategoryId(shopCategory.getCategories().get(0).getCategoryId());
                // 店铺二级分类信息
                esProductBO.setShopCategory(handleCategory(shopCategory));

                if (esProductBO.getAppDisplay() && !Objects.equals(shopCategory.getStatus(), StatusEnum.ENABLE.value())) {
                    esProductBO.setAppDisplay(Boolean.FALSE);
                }
            }
        }
    }

    private SpuExtension getSpuExtension(EsProductBO esProductBO) {
        SpuExtension spuExtension;
        if (Objects.equals(esProductBO.getSupplierDeliveryType(), SupplierDeliveryType.SUPPLIER_DELIVERY.value())) {
            spuExtension = spuExtensionService.getBySpuId(esProductBO.getSupplierSpuId());
        } else {
            spuExtension = spuExtensionService.getBySpuId(esProductBO.getSpuId());
        }
        return spuExtension;
    }

    /**
     * 处理分类数据
     *
     * @param category
     * @return
     */
    private EsCategoryBO handleCategory(CategoryVO category) {
        EsCategoryBO categoryBO = new EsCategoryBO();
        categoryBO.setCategoryId(category.getCategoryId());
        Map<Integer, String> categoryMap = category.getCategoryLangList().stream().collect(Collectors.toMap(CategoryLangVO::getLang, CategoryLangVO::getName));
        categoryBO.setCategoryNameZh(categoryMap.get(LanguageEnum.LANGUAGE_ZH_CN.getLang()));
        categoryBO.setCategoryNameEn(categoryMap.get(LanguageEnum.LANGUAGE_EN.getLang()));
        return categoryBO;
    }

}
