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

import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.GetMenuResponseDto.DataBean.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.OrderSourceType;
import cn.freemud.enums.ProductType;
import cn.freemud.enums.StoreItemStatus;
import cn.freemud.utils.BeanUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class StoreItemAdapter {

    private static FastDateFormat yyyyMMddHHmmss = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss", Locale.CHINA);

    public GetMenuCategoryInfoDto convert2MemuCategoryInfoDto(GetMenuCategoryVo getMenuCategoryVo) {
        GetMenuCategoryInfoDto memuCategoryInfoDto = new GetMenuCategoryInfoDto();
        memuCategoryInfoDto.setBusinessDate(yyyyMMddHHmmss.format(new Date()));
        memuCategoryInfoDto.setChannelType(getMenuCategoryVo.getChannelType());
        memuCategoryInfoDto.setInfoLevel(getMenuCategoryVo.getInfoLevel());
        memuCategoryInfoDto.setPartnerId(getMenuCategoryVo.getPartnerId());
        memuCategoryInfoDto.setShopId(getMenuCategoryVo.getShopId());
        memuCategoryInfoDto.setValid(true);
        return memuCategoryInfoDto;
    }

    public GetProductDto convert2ProductDto(GetProductVo getProductVo) {
        GetProductDto getProductDto = BeanUtil.convertBean(getProductVo, GetProductDto::new);
        getProductDto.setMenuCategoryId(getProductVo.getNodeId());
        getProductDto.setValid(true);
        return getProductDto;
    }

    public GetProductInfoDto convert2ProductInfoDto(String partnerId, String shopId, Integer productInfoType, List<String> productIds) {
        GetProductInfoDto getProductInfoDto = new GetProductInfoDto();
        getProductInfoDto.setPartnerId(partnerId);
        getProductInfoDto.setShopId(shopId);
        getProductInfoDto.setProductInfoType(productInfoType);
        getProductInfoDto.setProductIds(productIds);
        // 商品服务增加channel
        getProductInfoDto.setChannel(OrderSourceType.SAAS.getCode());
        return getProductInfoDto;
    }

    public GetProductValidateDto convert2ProductValidateDto(GetProductValidateVo getProductValidateVo) {
        return BeanUtil.convertBean(getProductValidateVo, GetProductValidateDto::new);
    }

    public GetProductValidateDto convert2ProductValidateDto(String partnerId, String shopId, List<String> productIds) {
        GetProductValidateDto getProductValidateDto = new GetProductValidateDto();
        getProductValidateDto.setPartnerId(partnerId);
        getProductValidateDto.setShopId(shopId);
        getProductValidateDto.setProductIds(productIds);
        return getProductValidateDto;
    }

    public SpuProductVo convert2SpuProductVo(GetMenuResponseDto.DataBean.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean productBean) {
        SpuProductVo spuProductVo = BeanUtil.convertBean(productBean, SpuProductVo::new);
        spuProductVo.setSpuId(productBean.getPid());
        spuProductVo.setSpuName(productBean.getName());
        spuProductVo.setName(productBean.getName());
        spuProductVo.setStatusDesc(Optional.ofNullable(StoreItemStatus.getByCode(spuProductVo.getStatus()))
                .map(StoreItemStatus::getDesc).orElse(""));
        spuProductVo.setDefaultPrice(productBean.getFinalPrice());
        spuProductVo.setFinalPrice(productBean.getFinalPrice());
        spuProductVo.setPicture(productBean.getPicture() + "?imageView2/1/w/225/h/225/interlace/1/q/100");
        spuProductVo.setStockLimit(productBean.getStockLimit());
        List<ProductGroupDto> productGroups = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(productBean.getProductAttributeGroupList())) {
            productBean.getProductAttributeGroupList().sort(Comparator.comparing(ProductBean.ProductAttributeGroupListBean::getAttributeType));
            for (ProductBean.ProductAttributeGroupListBean attribute : productBean.getProductAttributeGroupList()) {
                ProductGroupDto productGroupDto = new ProductGroupDto();
                productGroupDto.setName(attribute.getAttributeName());
                List<ProductGroupDto.GroupDetailBean> groupDetailBeans = Lists.newArrayList();
                if (CollectionUtils.isNotEmpty(attribute.getAttributeValues())) {
                    for (ProductBean.ProductAttributeGroupListBean.AttributeValueBean attributeValue : attribute.getAttributeValues()) {
                        /**
                         * 过滤下架的规格和售罄的规格
                         */
                        if (StoreItemStatus.PUT_ON_SALE.getCode().equals(attributeValue.getStatus())) {
                            ProductGroupDto.GroupDetailBean groupDetailBean = new ProductGroupDto.GroupDetailBean();
                            groupDetailBean.setGroupId(attribute.getAttributeType().toString());
                            groupDetailBean.setProductId(attributeValue.getAttributeId());
                            groupDetailBean.setProductName(attributeValue.getAttributeValue());
                            groupDetailBean.setSequence(attributeValue.getSequence());
                            groupDetailBean.setProductFinalPrice(attributeValue.getPrice());
                            groupDetailBean.setProductPrice(attributeValue.getPrice());
                            groupDetailBean.setStatus(attributeValue.getStatus());
                            groupDetailBean.setStatusDesc(Optional.ofNullable(StoreItemStatus.getByCode(attributeValue.getStatus()))
                                    .map(StoreItemStatus::getDesc).orElse(""));
                            groupDetailBeans.add(groupDetailBean);
                        }
                    }
                }
                productGroupDto.setGroupDetail(groupDetailBeans);
                //如果规格为空则不返回该规格
                if (CollectionUtils.isNotEmpty(groupDetailBeans)) {
                    productGroups.add(productGroupDto);
                }
            }
        }
        //设置是否包括多规格
        if (CollectionUtils.isNotEmpty(productBean.getProductAttributeGroupList()) || ProductType.HAVESPEC.getCode() == productBean.getType()) {
            spuProductVo.setType(8);
            spuProductVo.setHasSku(true);
        } else {
            spuProductVo.setHasSku(false);
        }
        //TODO sku信息
        Set<String> skuSpecValueIds = Sets.newHashSet();
        List<SpuProductVo.SkuProductVo> skuList = Lists.newArrayList();
        List<ProductBean.SkuProductBean> skuProductBeans = productBean.getSkuList();
        if (CollectionUtils.isNotEmpty(skuProductBeans)) {
            for (ProductBean.SkuProductBean skuProductBean : skuProductBeans) {
                /**
                 * 过滤下架的规格
                 */
                if (StoreItemStatus.PUT_ON_SALE.getCode().equals(skuProductBean.getStatus())) {
                    SpuProductVo.SkuProductVo skuProductVo = new SpuProductVo.SkuProductVo();
                    skuProductVo.setSkuId(skuProductBean.getSkuId());
                    skuProductVo.setSkuName(skuProductBean.getProductName());
                    skuProductVo.setOriginalPrice(skuProductBean.getOriginalPrice());
                    skuProductVo.setFinalPrice(skuProductBean.getFinalPrice());
                    skuProductVo.setStatus(skuProductBean.getStatus());
                    skuProductVo.setStatusDesc(Optional.ofNullable(StoreItemStatus.getByCode(skuProductBean.getStatus())).map(StoreItemStatus::getDesc).orElse(""));
//                    skuProductVo.setStatus(skuProductBean());
                    List<ProductBean.SkuProductBean.SkuSpecValue> skuSpecValueDtos = skuProductBean.getSkuSpecValues();
                    List<String> specValueIdList = Lists.newArrayList();
                    if (CollectionUtils.isNotEmpty(skuSpecValueDtos)) {
                        skuSpecValueDtos.forEach(skuSpecValueDto -> {
                            specValueIdList.add(skuSpecValueDto.getSpecValueId());
                            skuSpecValueIds.add(skuSpecValueDto.getSpecValueId());
                        });
                    }
                    String[] specValueIdArry = specValueIdList.toArray(new String[0]);
                    specValueIdList.clear();
                    skuProductVo.setSpecValueId(specValueIdArry);
                    skuList.add(skuProductVo);
                }
            }
        }
        //TODO 多规格信息
        List<ProductBean.SpecificationGroupBean> specificationGroupList = productBean.getSpecificationGroupList();
        //规格处理
        List<SpuProductVo.SpecificationGroupVo> specificationGroupVos = redundantSpecification(skuSpecValueIds,specificationGroupList);

        if (CollectionUtils.isNotEmpty(productBean.getProductPictureList())) {
            spuProductVo.setPicture(productBean.getProductPictureList().get(0).getUrl() + "?imageView2/1/w/225/h/225/interlace/1/q/100");
        }
        //商品标签信息
        List<SpuProductVo.ProductLabel> productLabels = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(productBean.getLabelNames())) {
            productBean.getLabelNames().forEach(label -> {
                SpuProductVo.ProductLabel productLabel = new SpuProductVo.ProductLabel();
                productLabel.setLabelName(label.getName());
                productLabels.add(productLabel);
            });
        }
        spuProductVo.setSkuList(skuList);
        spuProductVo.setSpecificationGroupList(specificationGroupVos);
        spuProductVo.setProductLabels(productLabels);
        spuProductVo.setProductGroups(productGroups);
        return spuProductVo;
    }


    public ProductVo convert2ProductVo(GetMenuResponseDto.DataBean.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean productBean) {
        ProductVo productVo = BeanUtil.convertBean(productBean, ProductVo::new);
        productVo.setStatusDesc(Optional.ofNullable(StoreItemStatus.getByCode(productVo.getStatus()))
                .map(StoreItemStatus::getDesc).orElse(""));
        List<ProductGroupDto> productGroups = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(productBean.getProductAttributeGroupList())) {
            productBean.getProductAttributeGroupList().sort(Comparator.comparing(ProductBean.ProductAttributeGroupListBean::getAttributeType));
            for (ProductBean.ProductAttributeGroupListBean attribute : productBean.getProductAttributeGroupList()) {
                ProductGroupDto productGroupDto = new ProductGroupDto();
                productGroupDto.setName(attribute.getAttributeName());
                List<ProductGroupDto.GroupDetailBean> groupDetailBeans = Lists.newArrayList();
                if (CollectionUtils.isNotEmpty(attribute.getAttributeValues())) {
                    for (ProductBean.ProductAttributeGroupListBean.AttributeValueBean attributeValue : attribute.getAttributeValues()) {
                        /**
                         * 过滤下架的规格和售罄的规格
                         */
                        if (StoreItemStatus.PUT_ON_SALE.getCode().equals(attributeValue.getStatus())) {
                            ProductGroupDto.GroupDetailBean groupDetailBean = new ProductGroupDto.GroupDetailBean();
                            groupDetailBean.setGroupId(attribute.getAttributeType().toString());
                            groupDetailBean.setProductId(attributeValue.getAttributeId());
                            groupDetailBean.setProductName(attributeValue.getAttributeValue());
                            groupDetailBean.setSequence(attributeValue.getSequence());
                            groupDetailBean.setProductFinalPrice(attributeValue.getPrice());
                            groupDetailBean.setProductPrice(attributeValue.getPrice());
                            groupDetailBean.setStatus(attributeValue.getStatus());
                            groupDetailBean.setStatusDesc(Optional.ofNullable(StoreItemStatus.getByCode(attributeValue.getStatus()))
                                    .map(StoreItemStatus::getDesc).orElse(""));
                            groupDetailBeans.add(groupDetailBean);
                        }
                    }
                }
                productGroupDto.setGroupDetail(groupDetailBeans);
                //如果规格为空则不返回该规格
                if (CollectionUtils.isNotEmpty(groupDetailBeans)) {
                    productGroups.add(productGroupDto);
                }
            }
            //设置规格类型
            productVo.setType(8);
        }
        if (CollectionUtils.isNotEmpty(productBean.getProductPictureList())) {
            productVo.setPicture(productBean.getProductPictureList().get(0).getUrl());
        }
        //商品标签信息
        List<ProductVo.ProductLabel> productLabels = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(productBean.getLabelNames())) {
            productBean.getLabelNames().forEach(label -> {
                ProductVo.ProductLabel productLabel = new ProductVo.ProductLabel();
                productLabel.setLabelName(label.getName());
                productLabels.add(productLabel);
            });
        }
        productVo.setProductLabels(productLabels);
        productVo.setProductGroups(productGroups);
        return productVo;
    }

    /**
     * 处理多余规格
     * 多规格商品的下架或者不是限时特购商品去除不需要的规格值
     *
     * @param skuSpecValueIds sku商品的规格id集合
     * @param specificationGroupList sku商品的规格对象集合
     * @return
     */
    public List<SpuProductVo.SpecificationGroupVo> redundantSpecification(Set<String> skuSpecValueIds,List<ProductBean.SpecificationGroupBean> specificationGroupList) {
        //TODO 多规格信息
        List<SpuProductVo.SpecificationGroupVo> specificationGroupVos = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(specificationGroupList)) {
            specificationGroupList.forEach(specificationGroupBean -> {
                SpuProductVo.SpecificationGroupVo specificationGroupVo = new SpuProductVo.SpecificationGroupVo();
                specificationGroupVo.setSpecId(specificationGroupBean.getSpecId());
                specificationGroupVo.setSpecName(specificationGroupBean.getSpecName());
                List<ProductBean.SpecificationGroupBean.SpecValueVo> specValueDtos = specificationGroupBean.getSpecValueVos();
                List<SpuProductVo.SpecificationGroupVo.SpecValueVo> specValueVos = Lists.newArrayList();
                if (CollectionUtils.isNotEmpty(specValueDtos)) {
                    specValueDtos.forEach(specValueDto -> {
                        //过滤在sku中没有上架状态是规格
                        if (skuSpecValueIds.contains(specValueDto.getSpecValueId())) {
                            SpuProductVo.SpecificationGroupVo.SpecValueVo specValueVo = new SpuProductVo.SpecificationGroupVo.SpecValueVo();
                            specValueVo.setSpecId(specValueDto.getSpecId());
                            specValueVo.setSpecValueId(specValueDto.getSpecValueId());
                            specValueVo.setSpecValueName(specValueDto.getSpecValue());
                            specValueVos.add(specValueVo);
                        }
                    });
                }
                specificationGroupVo.setSpecValueVos(specValueVos);
                if (CollectionUtils.isNotEmpty(specValueVos)) {
                    specificationGroupVos.add(specificationGroupVo);
                }
            });
        }

        return specificationGroupVos;

    }

}
