/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: ItemServiceImpl
 * @Package cn.freemud.service.impl
 * @Description:
 * @author: liming.guo
 * @date: 2018/5/15 19:24
 * @version V1.0
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */

package cn.freemud.service.impl;

import cn.freemud.adapter.StoreItemAdapter;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.product.*;
import cn.freemud.entities.vo.GetProductsVo;
import cn.freemud.enums.ProductInfoType;
import cn.freemud.enums.YesOrNoEnum;
import cn.freemud.service.ItemService;
import cn.freemud.service.thirdparty.StoreItemClient;
import cn.freemud.utils.LogUtil;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class ItemServiceImpl implements ItemService{

    private static Gson gson = new Gson();

    @Autowired
    private StoreItemClient storeItemClient;
    @Autowired
    private StoreItemAdapter storeItemAdapter;


    @Override
    public Map<String, GetProductsVo> getProducts(List<String> pids, String partnerId, String storeId) {
        Map<String, GetProductsVo> resultMap = new HashMap<>();
        if (CollectionUtils.isEmpty(pids)) {
            return resultMap;
        }
        List<String> skuIds = Lists.newArrayList();
        //查询商品详情
        GetProductInfoDto getProductInfoDto = storeItemAdapter.convert2ProductInfoDto(partnerId, storeId, ProductInfoType.ALL.getCode(), pids);
//        log.info("start:{}", JSON.toJSONString(getProductInfoDto));
        ProductInfosDto productInfosDto = storeItemClient.listProductInfos(getProductInfoDto);
//        log.info("end:{}", JSON.toJSONString(productInfosDto));
        LogUtil.info("storeItemClient_listProductInfos", gson.toJson(getProductInfoDto), gson.toJson(productInfosDto));
        if (ResponseCodeConstant.RESPONSE_SUCCESS.equals(productInfosDto.getErrcode())
                && productInfosDto.getData() != null
                && CollectionUtils.isNotEmpty(productInfosDto.getData().getProducts())) {
            productInfosDto.getData().getProducts().parallelStream().forEach(productBean -> {
                //多规格获取sku信息
                GetProductsVo getProductsVo = new GetProductsVo();
                getProductsVo.setSkuId(productBean.getPid());
                getProductsVo.setSkuName(productBean.getName());
                String picture = CollectionUtils.isNotEmpty(productBean.getProductPictureList())
                        ? productBean.getProductPictureList().get(0).getUrl() : null;
                getProductsVo.setSpuId(productBean.getPid());
                getProductsVo.setSpuName(productBean.getName());
                getProductsVo.setSpuPicture(picture);
                getProductsVo.setOriginalPrice(productBean.getOriginalPrice());
                getProductsVo.setFinalPrice(productBean.getFinalPrice());
                getProductsVo.setProductAttributeGroupList(productBean.getProductAttributeGroupList());
                getProductsVo.setStatus(productBean.getStatus());
                getProductsVo.setStock(productBean.getStock());
                getProductsVo.setStockLimit(productBean.getStockLimit());
                getProductsVo.setCustomerCode(productBean.getCustomerCode());
                getProductsVo.setProductCode(productBean.getProductCode());
                resultMap.put(productBean.getPid(), getProductsVo);
                getProductsVo.setType(1);
                // 规格ID 剔除单品
                if (Objects.equals(productBean.getIsSkuProduct(), YesOrNoEnum.YES.getCode())) {
                    getProductsVo.setType(10);
                    skuIds.add(productBean.getPid());
                }
            });
        }
        if (CollectionUtils.isEmpty(skuIds)) {
            return resultMap;
        }
        // 通过skuid查询spuid
        GetSpuIdsBySkuIdsDto bySkuIdsDto = new GetSpuIdsBySkuIdsDto();
        bySkuIdsDto.setProductIds(skuIds);
        bySkuIdsDto.setPartnerId(partnerId);
        ProductListDto productListDto = storeItemClient.getSpuIdsBySkuIds(bySkuIdsDto);
        if (ResponseCodeConstant.RESPONSE_SUCCESS.equals(productListDto.getErrcode())
                && CollectionUtils.isNotEmpty(productListDto.getData())) {
            productListDto.getData().parallelStream().forEach(product -> {
                product.getSkuList().parallelStream().forEach(skuProductBean -> {
                    if (resultMap.get(skuProductBean.getSkuId()) != null) {
                        GetProductsVo getProductsVo = resultMap.get(skuProductBean.getSkuId());
                        getProductsVo.setSpuId(product.getPid());
                        getProductsVo.setSpuName(product.getName());
                        String picture = CollectionUtils.isNotEmpty(product.getProductPictureList())
                                ? product.getProductPictureList().get(0).getUrl() : product.getPicture();
                        getProductsVo.setSpuPicture(picture);
                        getProductsVo.setStatus(product.getStatus());
                        resultMap.put(skuProductBean.getSkuId(), getProductsVo);
                    }
                });
            });
        }
        return resultMap;
    }

    /**
     * 传spuid集合查询所有里面所有sku商品信息
     * 包括商品的套餐子商品
     * 返回商品的第三方编号（唯一）、第三方货号、第三方规格id，第三方属性id
     */
    public Map<String, GetProductsVo> getSpuProducts(List<String> spuIds, String partnerId, String storeId) {
        Map<String, GetProductsVo> resultMap = new HashMap<>();
        if (CollectionUtils.isEmpty(spuIds)) {
            return resultMap;
        }
        //去重
        List<String> result = spuIds.stream().distinct().collect(Collectors.toList());
        //查询商品详情
        GetProductInfoDto getProductInfoDto = storeItemAdapter.convert2ProductInfoDto(partnerId, storeId, ProductInfoType.ALL.getCode(), result);
        ProductInfosDto productInfosDto = storeItemClient.listProductInfos(getProductInfoDto);
        LogUtil.info("storeItemClient_listProductInfos", gson.toJson(getProductInfoDto), gson.toJson(productInfosDto));
        if (ResponseCodeConstant.RESPONSE_SUCCESS.equals(productInfosDto.getErrcode()) && productInfosDto.getData() != null
                && CollectionUtils.isNotEmpty(productInfosDto.getData().getProducts())) {
            productInfosDto.getData().getProducts().forEach(productBean -> {
                GetProductsVo spuProductsVo = new GetProductsVo();
                spuProductsVo.setCustomerCode(productBean.getCustomerCode());
                spuProductsVo.setProductCode(productBean.getProductCode());
                List<AttributeValue> attributeValues  = new ArrayList<>();
                //第三方商品属性信息
                if (CollectionUtils.isNotEmpty(productBean.getProductAttributeGroupList())) {
                    for (ProductAttributeGroup attributeGroupListBean : productBean.getProductAttributeGroupList()) {
                        if (CollectionUtils.isEmpty(attributeGroupListBean.getAttributeValues())) {
                            continue;
                        }
                        attributeValues.addAll(attributeGroupListBean.getAttributeValues());
                    }
                }
                spuProductsVo.setProductAttributeGroupList(productBean.getProductAttributeGroupList());

                // todo 商品组信息
                if(CollectionUtils.isNotEmpty(productBean.getProductGroupList())){
                    spuProductsVo.setProductGroupList(productBean.getProductGroupList());
                }

                resultMap.put(productBean.getPid(), spuProductsVo);

                //多规格商品
                saveSkuProductsThirdInfo(productBean,productBean.getProductAttributeGroupList(),resultMap);
                //套餐商品内子商品
                saveComboProductsThirdInfo(productBean,resultMap);
            });
        }
        return resultMap;
    }


    /**
     * 多规格商品保存第三方信息
     */
    private void saveSkuProductsThirdInfo(ProductInfo productBean,List<ProductAttributeGroup> productAttributeGroupList,Map<String, GetProductsVo> resultMap){
        if (CollectionUtils.isNotEmpty(productBean.getSkuList())) {
            for (SkuProduct skuProductBean : productBean.getSkuList()) {
                GetProductsVo skuProductsVo = new GetProductsVo();
                skuProductsVo.setCustomerCode(skuProductBean.getCustomerCode());
                skuProductsVo.setProductCode(skuProductBean.getProductCode());
                //第三方商品规格值id
                if (CollectionUtils.isNotEmpty(skuProductBean.getSkuSpecValues())) {
                    List<String> list = new ArrayList<>();
                    for (SkuSpecValue skuSpecValue : skuProductBean.getSkuSpecValues()) {
                        if (StringUtils.isBlank(skuSpecValue.getSpecValueCustomerCode())) {
                            continue;
                        }
                        list.add(skuSpecValue.getSpecValueCustomerCode());
                    }
                    if (CollectionUtils.isNotEmpty(list)) {
                        String specCustomerCodes = StringUtils.join(list, ",");
                        skuProductsVo.setThirdProductSpecId(specCustomerCodes);
                    }
                }
                skuProductsVo.setProductAttributeGroupList(productAttributeGroupList);
                resultMap.put(skuProductBean.getSkuId(), skuProductsVo);
            }
        }
    }

    /**
     * 套餐商品保存第三方信息
     */
    private void saveComboProductsThirdInfo(ProductInfo productBean,Map<String, GetProductsVo> resultMap){
        //套餐固定商品
        if (CollectionUtils.isNotEmpty(productBean.getProductComboList())) {
            for (ProductComboListDto productComboListDto : productBean.getProductComboList()) {
                GetProductsVo comboProductsVo = new GetProductsVo();
                comboProductsVo.setCustomerCode(productComboListDto.getCustomerCode());
                comboProductsVo.setProductCode(productComboListDto.getProductCode());
                //第三方商品属性信息
                comboProductsVo.setProductAttributeGroupList(productComboListDto.getProductAttributeGroupList());
                resultMap.put(productComboListDto.getProductId(), comboProductsVo);
            }
        }

        //套餐商品内可选商品
        if (CollectionUtils.isNotEmpty(productBean.getProductGroupList()) && CollectionUtils.isNotEmpty(productBean.getProductGroupList().get(0).getGroupDetail())) {
            //套餐商品可选商品集合
            List<GroupDetail> groupDetails = productBean.getProductGroupList().get(0).getGroupDetail();
            for (GroupDetail groupDetailBean : groupDetails){
                //多规格获取sku信息
                GetProductsVo groupProductsVo = new GetProductsVo();
                groupProductsVo.setCustomerCode(groupDetailBean.getCustomerCode());
                groupProductsVo.setProductCode(groupDetailBean.getProductCode());
                //第三方商品属性信息
                groupProductsVo.setProductAttributeGroupList(groupDetailBean.getProductAttributeGroupList());
                resultMap.put(groupDetailBean.getProductId(), groupProductsVo);
            }
        }
    }

}
