/**
 * 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.CProductType;
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, String menuType) {
        GetProductInfoDto getProductInfoDto = new GetProductInfoDto();
        getProductInfoDto.setPartnerId(partnerId);
        getProductInfoDto.setShopId(shopId);
        getProductInfoDto.setProductInfoType(productInfoType);
        getProductInfoDto.setProductIds(productIds);
        // 商品服务增加channel
        getProductInfoDto.setChannel(menuType);
        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 PremiumExchangeResponseVo.PremiumExchangeProduct convert2SpuProductVo(ValidateProductInfosDto.ProductBean productBean, String skuId) {
        PremiumExchangeResponseVo.PremiumExchangeProduct spuProductVo = BeanUtil.convertBean(productBean, PremiumExchangeResponseVo.PremiumExchangeProduct::new);
        spuProductVo.setDetailText(productBean.getDetailText());
        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());
        if(CollectionUtils.isNotEmpty(productBean.getSkuList())) {
            for(ValidateProductInfosDto.ProductBean.SkuProductBean skuProductBean : productBean.getSkuList()) {
                if(Objects.equals(skuProductBean.getSkuId(), skuId)) {
                    spuProductVo.setDefaultPrice(skuProductBean.getFinalPrice());
                    spuProductVo.setFinalPrice(skuProductBean.getFinalPrice());
                    break;
                }
            }
        }
        spuProductVo.setOriginalPrice(productBean.getOriginalPrice());
        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(ValidateProductInfosDto.ProductBean.ProductAttributeGroupListBean::getAttributeType));
            for (ValidateProductInfosDto.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 (ValidateProductInfosDto.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);
//        }
        //设置是否包括多规格
        if (ProductType.HAVESPEC.getCode() == productBean.getType()) {
            spuProductVo.setType(ProductType.HAVESPEC.getCode());
            spuProductVo.setHasSku(true);
        } else if(CollectionUtils.isNotEmpty(productBean.getProductAttributeGroupList())){ //单规格，多属性
            spuProductVo.setType(8);
            spuProductVo.setHasSku(true);
        }else {
            spuProductVo.setHasSku(false);
        }
        //设置是否包括多规格
        if(ProductType.NOSPEC.getCode() == productBean.getType() && CollectionUtils.isEmpty(productBean.getProductAttributeGroupList())) {
            //单品无属性
            spuProductVo.setProductType(CProductType.PRODUCT_TYPE_1.getCode());
        } else if(ProductType.NOSPEC.getCode() == productBean.getType() && !CollectionUtils.isEmpty(productBean.getProductAttributeGroupList())) {
            //单品有属性
            spuProductVo.setProductType(CProductType.PRODUCT_TYPE_2.getCode());
        } else if(ProductType.HAVESPEC.getCode() == productBean.getType() && CollectionUtils.isEmpty(productBean.getProductAttributeGroupList())) {
            //多规格有属性
            spuProductVo.setProductType(CProductType.PRODUCT_TYPE_8.getCode());
        }else if(ProductType.HAVESPEC.getCode() == productBean.getType() && !CollectionUtils.isEmpty(productBean.getProductAttributeGroupList())) {
            //多规格无属性
            spuProductVo.setProductType(CProductType.PRODUCT_TYPE_10.getCode());
        }else if(ProductType.SETMEAL_UPPRICE_PRODUCT.getCode() == productBean.getType()) {
            //套餐
            spuProductVo.setProductType(CProductType.PRODUCT_TYPE_7.getCode());
        }
        //TODO sku信息
        Set<String> skuSpecValueIds = Sets.newHashSet();
        List<SpuProductVo.SkuProductVo> skuList = Lists.newArrayList();
        List<ValidateProductInfosDto.ProductBean.SkuProductBean> skuProductBeans = productBean.getSkuList();

        if (CollectionUtils.isNotEmpty(skuProductBeans)) {
            for (ValidateProductInfosDto.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<ValidateProductInfosDto.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<ValidateProductInfosDto.ProductBean.SpecificationGroupBean> specificationGroupList = productBean.getSpecificationGroupList();
        //规格处理
        List<SpuProductVo.SpecificationGroupVo> specificationGroupVos = redundantSpecification(skuSpecValueIds, specificationGroupList);
        addDefaultAttribute(specificationGroupVos, skuList);

        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<ValidateProductInfosDto.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<ValidateProductInfosDto.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;

    }
    /**
     * 默认价格，修复前端bug
     * specificationGroupVos 和 skuList 排序不一致时，会出现选的价格14元，加入到购物车15元
     * @param specificationGroupVos
     * @param skuList
     */
    private void addDefaultAttribute(List<SpuProductVo.SpecificationGroupVo> specificationGroupVos, List<SpuProductVo.SkuProductVo> skuList) {
        if (CollectionUtils.isNotEmpty(skuList) && CollectionUtils.isNotEmpty(specificationGroupVos)) {
            List<String> specValueIds = new ArrayList<>();
            for (SpuProductVo.SpecificationGroupVo groupVo : specificationGroupVos) {
                specValueIds.add(groupVo.getSpecValueVos().get(0).getSpecValueId());
            }
            SpuProductVo.SkuProductVo defaultSkuProductVo = null;

            for (SpuProductVo.SkuProductVo sku : skuList) {
                boolean hasDefault = true;
                for (String spc : sku.getSpecValueId()) {
                    if (!specValueIds.contains(spc)) {
                        hasDefault = false;
                        break;
                    }
                }
                if (hasDefault) {
                    defaultSkuProductVo = sku;
                    break;
                }
            }
            if (defaultSkuProductVo != null) {
                skuList.remove(defaultSkuProductVo);
                skuList.add(0, defaultSkuProductVo);
            }
        }
    }
}
