package com.yonge.cooleshow.portal.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.yonge.cooleshow.api.feign.AdminFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.mbg.mapper.*;
import com.yonge.cooleshow.mbg.model.*;
import com.yonge.cooleshow.portal.dao.PortalProductDao;
import com.yonge.cooleshow.portal.domain.PmsPortalProductDetail;
import com.yonge.cooleshow.portal.domain.PmsProductCategoryNode;
import com.yonge.cooleshow.portal.dto.ProductCategorySmallVo;
import com.yonge.cooleshow.portal.dto.ProductSearchConditionVo;
import com.yonge.cooleshow.portal.dto.ShareProductVo;
import com.yonge.cooleshow.portal.service.PmsPortalProductService;
import com.yonge.toolset.base.string.MessageFormatter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 前台订单管理Service实现类
 * Created by macro on 2020/4/6.
 */
@Service
public class PmsPortalProductServiceImpl implements PmsPortalProductService {
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsProductCategoryMapper productCategoryMapper;
    @Autowired
    private PmsBrandMapper brandMapper;
    @Autowired
    private PmsProductAttributeMapper productAttributeMapper;
    @Autowired
    private PmsProductAttributeValueMapper productAttributeValueMapper;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private PmsProductLadderMapper productLadderMapper;
    @Autowired
    private PmsProductFullReductionMapper productFullReductionMapper;
    @Autowired
    private PortalProductDao portalProductDao;

    @Autowired
    private AdminFeignService adminFeignService;

    @Autowired
    private PmsProductAttributeCategoryMapper productAttributeCategoryMapper;

    @Override
    public List<PmsProduct> search(String keyword, Long brandId, Long productCategoryId, Long productAttributeCategoryId, Integer pageNum, Integer pageSize, Integer sort) {
        PageHelper.startPage(pageNum, pageSize);
        PmsProductExample example = new PmsProductExample();
        PmsProductExample.Criteria criteria = example.createCriteria();
        criteria.andDeleteStatusEqualTo(0);
        criteria.andPublishStatusEqualTo(1);
        if (StrUtil.isNotEmpty(keyword)) {
            criteria.andNameLike("%" + keyword + "%");
        }
        if (brandId != null) {
            criteria.andBrandIdEqualTo(brandId);
        }
        if (productCategoryId != null) {
            List<Long> productCategoryIds = getProductCategoryIds(productCategoryId);
            criteria.andProductCategoryIdIn(productCategoryIds);
        }
        if (productAttributeCategoryId != null) {
            criteria.andProductAttributeCategoryIdEqualTo(productAttributeCategoryId);
        }
        //1->按新品；2->按销量；3->价格从低到高；4->价格从高到低
        if (sort == 1) {
            example.setOrderByClause("id desc");
        } else if (sort == 2) {
            example.setOrderByClause("sale desc");
        } else if (sort == 3) {
            example.setOrderByClause("price asc");
        } else if (sort == 4) {
            example.setOrderByClause("price desc");
        }
        List<PmsProduct> pmsProducts = productMapper.selectByExample(example);
        List<Long> productIdList = pmsProducts.stream().map(PmsProduct::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(productIdList)) {
            return pmsProducts;
        }
        PmsSkuStockExample skuExample = new PmsSkuStockExample();
        skuExample.createCriteria().andProductIdIn(productIdList);
        List<PmsSkuStock> skuStockList = skuStockMapper.selectByExample(skuExample);
        Map<Long, List<PmsSkuStock>> collect = skuStockList.stream()
                                                           .collect(Collectors.groupingBy(PmsSkuStock::getProductId));
        for (PmsProduct pmsProduct : pmsProducts) {
            pmsProduct.setSkuStockList(collect.get(pmsProduct.getId()));
        }
        return pmsProducts;

    }

    /**
     * 获取当前分类和下级分类 id
     *
     * @param productCategoryId
     * @return
     */
    private List<Long> getProductCategoryIds(Long productCategoryId) {
        PmsProductCategoryExample productCategoryExample = new PmsProductCategoryExample();
        productCategoryExample.setOrderByClause("sort desc");
        productCategoryExample.createCriteria().andParentIdEqualTo(productCategoryId)
               .andShowStatusEqualTo(1);
        List<PmsProductCategory> pmsProductCategories = productCategoryMapper.selectByExample(productCategoryExample);
        List<Long> productCategoryIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(pmsProductCategories)) {
            productCategoryIds = pmsProductCategories
                    .stream()
                    .map(PmsProductCategory::getId)
                    .collect(Collectors.toList());
        }
        productCategoryIds.add(productCategoryId);
        return productCategoryIds;
    }

    @Override
    public List<PmsProductCategoryNode> categoryTreeList() {
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        List<PmsProductCategory> allList = productCategoryMapper.selectByExample(example);
        return allList.stream()
                      .filter(item -> item.getParentId().equals(0L))
                      .map(item -> covert(item, allList)).collect(Collectors.toList());
    }

    @Override
    public PmsPortalProductDetail detail(Long id) {
        PmsPortalProductDetail result = new PmsPortalProductDetail();
        //获取商品信息
        PmsProduct product = productMapper.selectByPrimaryKey(id);
        result.setProduct(product);
        //获取品牌信息
        PmsBrand brand = brandMapper.selectByPrimaryKey(product.getBrandId());
        result.setBrand(brand);
        //获取商品属性信息
        PmsProductAttributeExample attributeExample = new PmsProductAttributeExample();
        attributeExample.createCriteria().andProductAttributeCategoryIdEqualTo(product.getProductAttributeCategoryId());
        List<PmsProductAttribute> productAttributeList = productAttributeMapper.selectByExample(attributeExample);
        result.setProductAttributeList(productAttributeList);
        //获取商品属性值信息
        if(CollUtil.isNotEmpty(productAttributeList)){
            List<Long> attributeIds = productAttributeList.stream().map(PmsProductAttribute::getId).collect(Collectors.toList());
            PmsProductAttributeValueExample attributeValueExample = new PmsProductAttributeValueExample();
            attributeValueExample.createCriteria().andProductIdEqualTo(product.getId())
                    .andProductAttributeIdIn(attributeIds);
            List<PmsProductAttributeValue> productAttributeValueList = productAttributeValueMapper.selectByExample(attributeValueExample);
            result.setProductAttributeValueList(productAttributeValueList);
        }
        //获取商品SKU库存信息
        PmsSkuStockExample skuExample = new PmsSkuStockExample();
        skuExample.createCriteria().andProductIdEqualTo(product.getId());
        List<PmsSkuStock> skuStockList = skuStockMapper.selectByExample(skuExample);
        result.setSkuStockList(skuStockList);
        //商品阶梯价格设置
        if(product.getPromotionType()==3){
            PmsProductLadderExample ladderExample = new PmsProductLadderExample();
            ladderExample.createCriteria().andProductIdEqualTo(product.getId());
            List<PmsProductLadder> productLadderList = productLadderMapper.selectByExample(ladderExample);
            result.setProductLadderList(productLadderList);
        }
        //商品满减价格设置
        if(product.getPromotionType()==4){
            PmsProductFullReductionExample fullReductionExample = new PmsProductFullReductionExample();
            fullReductionExample.createCriteria().andProductIdEqualTo(product.getId());
            List<PmsProductFullReduction> productFullReductionList = productFullReductionMapper.selectByExample(fullReductionExample);
            result.setProductFullReductionList(productFullReductionList);
        }
        //商品可用优惠券
        result.setCouponList(portalProductDao.getAvailableCouponList(product.getId(),product.getProductCategoryId()));
        return result;
    }

    @Override
    public ProductSearchConditionVo searchCondition() {
        ProductSearchConditionVo result = new ProductSearchConditionVo();
        // 设置品牌
        result.setBrandList(getBrandList());

        // 设置分类
        result.setProductCategorySmallVoList(getProductCategoryList());

        // 设置类别
        result.setProductAttributeCategoryList(getHomeProductAttributeCategory());
        return result;
    }

    @Override
    public ShareProductVo shareProductProfit(SysUser sysUser, Long productId) {
        PmsPortalProductDetail detail = detail(productId);
        ShareProductVo  shareProductVo = new ShareProductVo();
        shareProductVo.setProductDetail(detail);
        shareProductVo.setAvatar(sysUser.getAvatar());
        shareProductVo.setTeacherId(sysUser.getId());
        shareProductVo.setName(sysUser.getUsername());
        // String url = adminFeignService.findConfigValue(SysConfigConstant.TEACHER_PRODUCT_SHARE_PROFIT_URL).getData();

        // shareProductVo.setUrl(MessageFormatter.arrayFormat(url, detail.getProduct().getId(), sysUser.getId()));

        return shareProductVo;
    }


    private  List<PmsProductAttributeCategory>  getHomeProductAttributeCategory() {
        PmsProductAttributeCategoryExample example = new PmsProductAttributeCategoryExample();
        example.setOrderByClause("id desc");
        List<PmsProductAttributeCategory> pmsProductCategories = productAttributeCategoryMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(pmsProductCategories)) {
            return new ArrayList<>();
        }
        return pmsProductCategories;
    }

    private List<ProductCategorySmallVo> getProductCategoryList() {
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.setOrderByClause("sort desc");
        example.createCriteria()
               .andShowStatusEqualTo(1);
        List<PmsProductCategory> pmsProductCategories = productCategoryMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(pmsProductCategories)) {
            return new ArrayList<>();
        }
        List<ProductCategorySmallVo> collect = pmsProductCategories.stream().map(pmsProductCategory -> {
            ProductCategorySmallVo productCategorySmallVo = new ProductCategorySmallVo();
            BeanUtils.copyProperties(pmsProductCategory, productCategorySmallVo);
            return productCategorySmallVo;
        }).collect(Collectors.toList());

        List<ProductCategorySmallVo> tree = new ArrayList<>();
        for (ProductCategorySmallVo categorySmallVo : collect) {
            if (categorySmallVo.getParentId() == null || categorySmallVo.getParentId() == 0) {
                tree.add(categorySmallVo);
            }
            for (ProductCategorySmallVo tagVo : collect) {
                if (tagVo.getParentId() != null && tagVo.getParentId() != 0 && tagVo.getParentId().equals(categorySmallVo.getId())) {
                    if (categorySmallVo.getChildren() == null) {
                        categorySmallVo.setChildren(new ArrayList<>());
                    }
                    categorySmallVo.getChildren().add(tagVo);
                }

            }
        }
        return tree;
    }

    private List<PmsBrand> getBrandList() {
        PmsBrandExample pmsBrandExample = new PmsBrandExample();
        pmsBrandExample.createCriteria().andShowStatusEqualTo(1);
        pmsBrandExample.setOrderByClause("sort desc");
        return brandMapper.selectByExample(pmsBrandExample);
    }


    /**
     * 初始对象转化为节点对象
     */
    private PmsProductCategoryNode covert(PmsProductCategory item, List<PmsProductCategory> allList) {
        PmsProductCategoryNode node = new PmsProductCategoryNode();
        BeanUtils.copyProperties(item, node);
        List<PmsProductCategoryNode> children = allList.stream()
                .filter(subItem -> subItem.getParentId().equals(item.getId()))
                .map(subItem -> covert(subItem, allList)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }
}
