package com.hwrj.cloud.portal.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.hwrj.cloud.portal.dao.PmsProductDao;
import com.hwrj.cloud.portal.dao.PortalProductDao;
import com.hwrj.cloud.portal.domain.*;
import com.hwrj.cloud.portal.mapper.*;
import com.hwrj.cloud.portal.model.*;
import com.hwrj.cloud.portal.service.CouponService;
import com.hwrj.cloud.portal.service.PmsPortalProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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 PmsProductCategoryMapper pmsProductCategoryMapper;

    @Autowired
    private CouponService couponService;

    @Override
    public List<PmsProduct> search(String keyword, Long brandId, Long productCategoryId, 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);
        criteria.andVerifyStatusEqualTo(1);
        if (StrUtil.isNotEmpty(keyword)) {
            criteria.andNameLike("%" + keyword + "%");

        }
        if (brandId != null) {
            criteria.andBrandIdEqualTo(brandId);
        }
        if (productCategoryId != null) {
            List<Long> ids = getTwoCategoryIdById(productCategoryId);
            if (ids !=null&&ids.size()>0){
                criteria.andProductCategoryIdIn(ids);
            }

        }
        //默认按排序字段
        example.setOrderByClause("sort asc");
        //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");
        }
        return productMapper.selectByExample(example);
    }

    public List<Long> getTwoCategoryIdById(Long id){
        List<Long> list=new ArrayList<>();
        PmsProductCategory pmsProductCategory = pmsProductCategoryMapper.selectByPrimaryKey(id);
        if (pmsProductCategory != null){
            Long parentId = pmsProductCategory.getParentId();
            if (parentId!=0){
                list.add(id);
            }else {
                PmsProductCategoryExample example= new PmsProductCategoryExample();
                PmsProductCategoryExample.Criteria criteria = example.createCriteria();
                criteria.andParentIdEqualTo(id);
                List<PmsProductCategory> categoryList = pmsProductCategoryMapper.selectByExample(example);
                if (categoryList!=null&&categoryList.size()>0){
                    List<Long> collect = categoryList.stream().map(PmsProductCategory::getId).collect(Collectors.toList());
                    list.addAll(collect);
                }
            }
        }

        return  list;
    }

    @Override
    public List<PmsProductCategoryNode> categoryTreeList() {
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        PmsProductCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andShowStatusEqualTo(1);
        List<PmsProductCategory> allList = productCategoryMapper.selectByExample(example);
        example.setOrderByClause("sort ASC");
        List<PmsProductCategoryNode> result = allList.stream()
                .filter(item -> item.getParentId().equals(0L))
                .map(item -> covert(item, allList)).collect(Collectors.toList());
        return result;
    }

    @Override
    public List<PmsProductCategoryNode> categorySearchTreeList(String key) {
        List<PmsProductCategory> pms = new ArrayList<>();
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.setOrderByClause("sort ASC");
        PmsProductCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdNotEqualTo(0l);
        if (!StringUtils.isEmpty(key)){
            criteria.andNameLike("%"+key+"%");
        }

        List<PmsProductCategory> twoList = productCategoryMapper.selectByExample(example);
        pms.addAll(twoList);

        Map<Long, List<PmsProductCategory>> collect =
                twoList.stream().collect(Collectors.groupingBy(PmsProductCategory::getParentId));
        if (!collect.isEmpty()){
            PmsProductCategoryExample example1 = new PmsProductCategoryExample();
            PmsProductCategoryExample.Criteria criteria1 = example1.createCriteria();
            ArrayList<Long> longs = new ArrayList<>(collect.keySet());
            criteria1.andIdIn(longs);
            criteria1.andNavStatusEqualTo(1);
            List<PmsProductCategory> example2 = productCategoryMapper.selectByExample(example1);
            pms.addAll(example2);

        }
        List<PmsProductCategoryNode> result = pms.stream()
                .filter(item -> item.getParentId().equals(0L))
                .map(item -> covert(item, pms)).collect(Collectors.toList());
        return result;
    }

    @Override
    public PmsPortalProductDetail detail(Long id) {
        PmsPortalProductDetail result = new PmsPortalProductDetail();
        //获取商品信息
        PmsProduct product = productMapper.selectByPrimaryKey(id);
        result.setProduct(product);
        //获取品牌信息
        if (product.getBrandId() != null){
            PmsBrand brand = brandMapper.selectByPrimaryKey(product.getBrandId());
            result.setBrand(brand);
        }

        if (product.getProductAttributeCategoryId() != null){
            //获取商品属性信息
            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);
            }
        }



        if (product.getPromotionType() != null){
            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(couponService.getAvailableCouponList(product.getId(), product.getProductCategoryId()));
        }


        return result;
    }

    /**
     * 获取购物车中某个商品的规格,用于重选规格
     *
     * @param productId
     * @return
     */
    @Override
    public CartProduct getCartProduct(Long productId) {
        return portalProductDao.getCartProduct(productId);
    }

    /**
     * 获取促销商品
     *
     * @param productIdList
     * @return
     */
    @Override
    public List<PromotionProduct> getPromotionProductList(List<Long> productIdList) {
        return portalProductDao.getPromotionProductList(productIdList);
    }


    /**
     * 锁定下单商品的所有库存
     *
     * @param productSkuId
     * @param quantity
     * @return
     */
    @Override
    public void lockStock(Long productSkuId, Integer quantity) {
        PmsSkuStock skuStock = skuStockMapper.selectByPrimaryKey(productSkuId);
        skuStock.setLockStock(skuStock.getLockStock() + quantity);
        skuStockMapper.updateByPrimaryKeySelective(skuStock);
    }

    /**
     * 获取商品详情
     *
     * @param productId
     * @return
     */
    @Override
    public PmsProduct getPmsProductById(Long productId) {
        return productMapper.selectByPrimaryKey(productId);
    }
    @Autowired
    private PmsProductDao pmsProductDao;

    @Override
    public List<PmsProduct> getProductByCompanyId(Long companyId) {
        if (companyId == null){
            return null;
        }
        PmsProductExample example = new PmsProductExample();
        PmsProductExample.Criteria criteria = example.createCriteria();
        criteria.andCompIdEqualTo(companyId);
        criteria.andDeleteStatusEqualTo(0);
        List<PmsProduct> pmsProducts = productMapper.selectByExample(example);
        return pmsProducts;
    }

    @Override
    public List<BrandVO> getPmsPrands(Long compId) {
        return pmsProductDao.selectBandList(compId);
    }


    /**
     * 初始对象转化为节点对象
     */
    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;
    }
}
