/**
 * 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.base.entity.BaseResponse;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.GetMenuResponseDto.DataBean.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean;
import cn.freemud.entities.vo.GetProductsVo;
import cn.freemud.enums.ProductInfoType;
import cn.freemud.enums.ResponseResult;
import cn.freemud.enums.YesOrNoEnum;
import cn.freemud.redis.RedisCache;
import cn.freemud.service.ItemService;
import cn.freemud.service.thirdparty.StockClient;
import cn.freemud.service.thirdparty.StoreItemClient;
import cn.freemud.utils.ResponseUtil;
import cn.freemud.utils.Sha1Util;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ItemServiceImpl implements ItemService {

    private Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    private final Integer RESPONSE_SUCCESS_CODE = 100;
    private static Gson gson = new Gson();
    @Autowired
    private StoreItemClient storeItemClient;
    @Autowired
    private StoreItemAdapter storeItemAdapter;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private StockClient stockClient;







    public BaseResponse<Map<String, ProductBean>> getProducts(String partnerId, String shopId, List<String> productIds, boolean reflash ,String menuType) {
        Map<String, ProductBean> newProductBeanMap = Maps.newTreeMap();
        if (CollectionUtils.isEmpty(productIds)) {
            return ResponseUtil.success(newProductBeanMap);
        }
        productIds.sort(Comparator.comparing(p -> p));
        String key = "saas:productInfo:" + Sha1Util.sha1(gson.toJson(productIds));
        Map<String, ProductBean> productBeanMap = redisCache.getValue(key);
        if (!reflash && productBeanMap != null && productBeanMap.size() > 0) {
            return ResponseUtil.success(productBeanMap);
        }
        GetProductValidateDto getProductValidateDto = storeItemAdapter.convert2ProductValidateDto(partnerId, shopId, productIds);
        GetProductInfoDto getProductInfoDto = storeItemAdapter.convert2ProductInfoDto(partnerId, shopId, ProductInfoType.ALL.getCode(), productIds,menuType);
        ProductInfosDto productInfosDto = storeItemClient.listProductInfos(getProductInfoDto);
        if (!RESPONSE_SUCCESS_CODE.equals(productInfosDto.getErrcode()) || CollectionUtils.isEmpty(productInfosDto.getData().getProducts())) {
            log.error("getShoppingCartInfo checkProductValidate is error , getProductValidateDto:{} , productCheckVaildDto:{}",
                    gson.toJson(getProductValidateDto), gson.toJson(productInfosDto));
            return ResponseUtil.error(ResponseResult.STORE_ITEM_QUERY_ERROR);
        }
        List<String> productInfoIds = productInfosDto.getData().getProducts().stream()
                .map(ProductBean::getPid).collect(Collectors.toList());
        for (String productId : productIds) {
            if (!productInfoIds.contains(productId)) {
                return ResponseUtil.error(ResponseResult.STORE_ITEM_QUERY_ERROR.getCode(), "商品ID" + productId + "不存在");
            }
        }

        List<ProductBean> productInfosDtos = productInfosDto.getData().getProducts();
        newProductBeanMap = productInfosDtos.stream()
                .collect(Collectors.toMap(ProductBean::getPid, (p) -> p));
        redisCache.save(key, newProductBeanMap, 5L, TimeUnit.MINUTES);
        return ResponseUtil.success(newProductBeanMap);
    }


    /**
     * 获取商品所有属性map
     *
     * @param productBean
     * @return
     */
    public Map<String, ProductBean.ProductAttributeGroupListBean.AttributeValueBean> getAttributeValuesByProduct(ProductBean productBean) {
        Map<String, ProductBean.ProductAttributeGroupListBean.AttributeValueBean> attributeValueBeanMap = Maps.newTreeMap();
        if (productBean == null) {
            return attributeValueBeanMap;
        }
        if (CollectionUtils.isNotEmpty(productBean.getProductAttributeGroupList())) {
            productBean.getProductAttributeGroupList().forEach(productAttributeGroupListBean -> {
                if (CollectionUtils.isNotEmpty(productAttributeGroupListBean.getAttributeValues())) {
                    productAttributeGroupListBean.getAttributeValues().forEach(attributeValueBean -> {
                        if (!attributeValueBeanMap.containsKey(attributeValueBean.getAttributeId())) {
                            attributeValueBeanMap.put(attributeValueBean.getAttributeId(), attributeValueBean);
                        }
                    });
                }
            });
        }
        return attributeValueBeanMap;
    }

    /***
     *  判断属性是否在商品属性内
     */
    @Override
    public boolean hasAttributeAll(List<String> attributeIds, ProductBean productBean) {
        if (CollectionUtils.isEmpty(attributeIds)) {
            return true;
        }
        Map<String, ProductBean.ProductAttributeGroupListBean.AttributeValueBean> attributeValueBeanMap = getAttributeValuesByProduct(productBean);
        for (String attributeId : attributeIds) {
            if (!attributeValueBeanMap.containsKey(attributeId)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public Map<String, GetProductsVo> getProducts(List<String> pids, String partnerId, String storeId, String menuType) {
        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,menuType);
        ProductInfosDto productInfosDto = storeItemClient.listProductInfos(getProductInfoDto);
        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.setCategory(productBean.getCategory());
                getProductsVo.setCategoryName(productBean.getCategoryName());
                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;
    }



}
