package com.buy507.mall.portal.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.buy507.mall.mapper.CmsSubjectMapper;
import com.buy507.mall.mapper.PmsCommentMapper;
import com.buy507.mall.mapper.PmsCommentReplayMapper;
import com.buy507.mall.mapper.PmsProductAttributeMapper;
import com.buy507.mall.mapper.PmsProductAttributeValueMapper;
import com.buy507.mall.mapper.PmsProductCategoryMapper;
import com.buy507.mall.mapper.PmsProductFullReductionMapper;
import com.buy507.mall.mapper.PmsProductMapper;
import com.buy507.mall.mapper.PmsSkuStockMapper;
import com.buy507.mall.mapper.SmsFlashPromotionMapper;
import com.buy507.mall.mapper.SmsFlashPromotionSessionMapper;
import com.buy507.mall.mapper.SmsHomeAdvertiseMapper;
import com.buy507.mall.model.CmsSubject;
import com.buy507.mall.model.CmsSubjectExample;
import com.buy507.mall.model.PmsComment;
import com.buy507.mall.model.PmsCommentReplay;
import com.buy507.mall.model.PmsProduct;
import com.buy507.mall.model.PmsProductAttribute;
import com.buy507.mall.model.PmsProductAttributeExample;
import com.buy507.mall.model.PmsProductAttributeValue;
import com.buy507.mall.model.PmsProductAttributeValueExample;
import com.buy507.mall.model.PmsProductCategory;
import com.buy507.mall.model.PmsProductCategoryExample;
import com.buy507.mall.model.PmsProductExample;
import com.buy507.mall.model.PmsProductFullReduction;
import com.buy507.mall.model.PmsSkuStock;
import com.buy507.mall.model.PmsSkuStockExample;
import com.buy507.mall.model.SmsFlashPromotion;
import com.buy507.mall.model.SmsFlashPromotionExample;
import com.buy507.mall.model.SmsFlashPromotionSession;
import com.buy507.mall.model.SmsFlashPromotionSessionExample;
import com.buy507.mall.model.SmsHomeAdvertise;
import com.buy507.mall.model.SmsHomeAdvertiseExample;
import com.buy507.mall.model.UmsMember;
import com.buy507.mall.portal.dao.HomeDao;
import com.buy507.mall.portal.domain.FlashPromotionProduct;
import com.buy507.mall.portal.domain.HomeContentResult;
import com.buy507.mall.portal.domain.HomeFlashPromotion;
import com.buy507.mall.portal.domain.MemberProductCollection;
import com.buy507.mall.portal.domain.ProductAttributeResult;
import com.buy507.mall.portal.domain.ProductCategoryOptions;
import com.buy507.mall.portal.domain.ProductDetailResult;
import com.buy507.mall.portal.domain.ProductSkuResult;
import com.buy507.mall.portal.repository.MemberProductCollectionRepository;
import com.buy507.mall.portal.service.HomeService;
import com.buy507.mall.portal.service.PortalCommonService;
import com.buy507.mall.portal.service.UmsMemberService;
import com.buy507.mall.portal.util.DateUtil;
import com.github.pagehelper.PageHelper;

/**
 * 首页内容管理Service实现类
 */
@Service
public class HomeServiceImpl implements HomeService {
    @Autowired
    private SmsHomeAdvertiseMapper advertiseMapper;
    @Autowired
    private HomeDao homeDao;
    @Autowired
    private SmsFlashPromotionMapper flashPromotionMapper;
    @Autowired
    private SmsFlashPromotionSessionMapper promotionSessionMapper;
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsProductCategoryMapper productCategoryMapper;
    @Autowired
    private CmsSubjectMapper subjectMapper;
    @Autowired
    private PmsCommentReplayMapper pmsCommentReplayMapper;
    @Autowired
    private PmsCommentMapper pmsCommentMapper;
    
    @Autowired
    private PmsProductFullReductionMapper pmsProductFullReductionMapper;

    @Autowired
    private PmsProductAttributeMapper pmsProductAttributeMapper;
    
    @Autowired
    private PmsProductAttributeValueMapper productAttributeValueMapper;
    
    @Autowired
    private MemberProductCollectionRepository productCollectionRepository;
    
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    
    @Autowired
    private UmsMemberService memberService;
    
    @Autowired
	private PortalCommonService commonService;
    
    @Override
    public HomeContentResult content() {
    	
        HomeContentResult result = new HomeContentResult();
        //获取首页广告
        result.setAdvertiseList(getHomeAdvertiseList());
        //获取推荐品牌
        result.setBrandList(homeDao.getRecommendBrandList(0,4));
        //获取秒杀信息
        result.setHomeFlashPromotion(getHomeFlashPromotion());
        
        List<PmsProduct> newProductList = homeDao.getNewProductList(0, 4);
        List<PmsProduct> hotProductList = homeDao.getHotProductList(0, 4);
        List<PmsProduct> allProductList = homeDao.getAllPioductList();
        
        //根据会员等级显示不同的商品价格
        UmsMember member = memberService.getCurrentMember();
        if(member != null) {
        	BigDecimal discount = commonService.getDiscount(member.getId());
        	if(discount != null) {
        		for(PmsProduct product : newProductList) {
        			product.setPrice(product.getPrice().multiply(discount).setScale(2, BigDecimal.ROUND_HALF_UP));
        		}
        		for(PmsProduct product : hotProductList) {
        			product.setPrice(product.getPrice().multiply(discount).setScale(2, BigDecimal.ROUND_HALF_UP));
        		}
        		for(PmsProduct product : allProductList) {
        			product.setPrice(product.getPrice().multiply(discount).setScale(2, BigDecimal.ROUND_HALF_UP));
        		}
        	}
        }
        
        //获取新品推荐
        result.setNewProductList(newProductList);
        //获取人气推荐
        result.setHotProductList(hotProductList);
        //获取推荐专题
        //result.setSubjectList(homeDao.getRecommendSubjectList(0,4));
        //获取上次所有商品，按销量排序
        result.setAllProductList(allProductList);
        return result;
    }

    @Override
    public List<PmsProduct> recommendProductList(Integer pageSize, Integer pageNum) {
        // TODO: 2019/1/29 暂时默认推荐所有商品
        PageHelper.startPage(pageNum,pageSize);
        PmsProductExample example = new PmsProductExample();
        example.createCriteria()
                .andDeleteStatusEqualTo(0)
                .andPublishStatusEqualTo(1);
        return productMapper.selectByExample(example);
    }

    @Override
    public List<ProductCategoryOptions> getProductCateList() {
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.createCriteria()
                .andShowStatusEqualTo(1);
        example.setOrderByClause("sort desc");
        List<PmsProductCategory> productCategories = productCategoryMapper.selectByExample(example);
        
        List<ProductCategoryOptions> options = new ArrayList<>();
    	for(PmsProductCategory category : productCategories) {
    		//我们这里最大的根节点ID是0，所以找出所有parent id为0的节点，然后调用我们的递归算法
    		if(category.getParentId().equals(0L)){
    			options.add(recursionCategory(category, productCategories));
    		}
    	}
    	
        return options;
    }
    
    private ProductCategoryOptions recursionCategory(PmsProductCategory category, List<PmsProductCategory> list) {
    	List<ProductCategoryOptions> childList = new ArrayList<>();
        // 为每一个父节点增加子树（List形式，没有则为空的list）
    	ProductCategoryOptions node = new ProductCategoryOptions();
    	node.setId(category.getId());
    	node.setName(category.getName());
    	node.setLevel(category.getLevel());
    	node.setIcon(category.getIcon());
    	node.setPid(category.getParentId());
     	for (PmsProductCategory childCategory : list){
            //如果子节点的pid等于父节点的ID，则说明是父子关系
    	    if(childCategory.getParentId().equals(category.getId())){
                // 继续调用递归算法，将当前作为父节点，继续找他的子节点，反复执行。
    	    	childList.add(recursionCategory(childCategory, list));
    	    }
    	}
     	
        // 当遍历完成，返回调用的节点
     	if(!childList.isEmpty()) {
     		node.setChildren(childList);
     	} else {
     		node.setChildren(null);
     	}
    	return node;
    }

    @Override
    public List<CmsSubject> getSubjectList(Long cateId, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        CmsSubjectExample example = new CmsSubjectExample();
        CmsSubjectExample.Criteria criteria = example.createCriteria();
        criteria.andShowStatusEqualTo(1);
        if(cateId!=null){
            criteria.andCategoryIdEqualTo(cateId);
        }
        return subjectMapper.selectByExample(example);
    }

    private HomeFlashPromotion getHomeFlashPromotion() {
        HomeFlashPromotion homeFlashPromotion = new HomeFlashPromotion();
        //获取当前秒杀活动
        Date now = new Date();
        SmsFlashPromotion flashPromotion = getFlashPromotion(now);
        if (flashPromotion != null) {
            //获取当前秒杀场次
            SmsFlashPromotionSession flashPromotionSession = getFlashPromotionSession(now);
            if (flashPromotionSession != null) {
                homeFlashPromotion.setStartTime(flashPromotionSession.getStartTime());
                homeFlashPromotion.setEndTime(flashPromotionSession.getEndTime());
                homeFlashPromotion.setName(flashPromotion.getTitle());
                //获取下一个秒杀场次
                SmsFlashPromotionSession nextSession = getNextFlashPromotionSession(homeFlashPromotion.getStartTime());
                if(nextSession!=null){
                    homeFlashPromotion.setNextStartTime(nextSession.getStartTime());
                    homeFlashPromotion.setNextEndTime(nextSession.getEndTime());
                }
                //获取秒杀商品
                List<FlashPromotionProduct> flashProductList = homeDao.getFlashProductList(flashPromotion.getId(), flashPromotionSession.getId());
                homeFlashPromotion.setProductList(flashProductList);
            }
        }
        return homeFlashPromotion;
    }

    //获取下一个场次信息
    private SmsFlashPromotionSession getNextFlashPromotionSession(Date date) {
        SmsFlashPromotionSessionExample sessionExample = new SmsFlashPromotionSessionExample();
        sessionExample.createCriteria()
                .andStartTimeGreaterThan(date);
        sessionExample.setOrderByClause("start_time asc");
        List<SmsFlashPromotionSession> promotionSessionList = promotionSessionMapper.selectByExample(sessionExample);
        if (!CollectionUtils.isEmpty(promotionSessionList)) {
            return promotionSessionList.get(0);
        }
        return null;
    }

    private List<SmsHomeAdvertise> getHomeAdvertiseList() {
        SmsHomeAdvertiseExample example = new SmsHomeAdvertiseExample();
        example.createCriteria().andTypeEqualTo(1).andStatusEqualTo(1);
        example.setOrderByClause("sort desc");
        return advertiseMapper.selectByExample(example);
    }

    //根据时间获取秒杀活动
    private SmsFlashPromotion getFlashPromotion(Date date) {
        Date currDate = DateUtil.getDate(date);
        SmsFlashPromotionExample example = new SmsFlashPromotionExample();
        example.createCriteria()
                .andStatusEqualTo(1)
                .andStartDateLessThanOrEqualTo(currDate)
                .andEndDateGreaterThanOrEqualTo(currDate);
        List<SmsFlashPromotion> flashPromotionList = flashPromotionMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(flashPromotionList)) {
            return flashPromotionList.get(0);
        }
        return null;
    }

    //根据时间获取秒杀场次
    private SmsFlashPromotionSession getFlashPromotionSession(Date date) {
        Date currTime = DateUtil.getTime(date);
        SmsFlashPromotionSessionExample sessionExample = new SmsFlashPromotionSessionExample();
        sessionExample.createCriteria()
                .andStartTimeLessThanOrEqualTo(currTime)
                .andEndTimeGreaterThanOrEqualTo(currTime);
        List<SmsFlashPromotionSession> promotionSessionList = promotionSessionMapper.selectByExample(sessionExample);
        if (!CollectionUtils.isEmpty(promotionSessionList)) {
            return promotionSessionList.get(0);
        }
        return null;
    }
    //获取商品详情
	@Override
	public ProductDetailResult getProductInfo(Long productId) {
		PmsProduct product = productMapper.selectByPrimaryKey(productId);
		ProductDetailResult detailResult = new ProductDetailResult();
		BeanUtils.copyProperties(product, detailResult);
		List<String> result = Arrays.asList(detailResult.getAlbumPics().toString().split(","));
		detailResult.setListAlbumPics(result);
		detailResult.setAlbumPics(null);
		PmsProductFullReduction ppFullReduction =(PmsProductFullReduction)pmsProductFullReductionMapper.getPmsProductFullReduction(productId);
		detailResult.setPmsProductFullReduction(ppFullReduction);//满减商品
		
		UmsMember currentMember = memberService.getCurrentMember();//获取用户信息
		if(currentMember == null) {
			detailResult.setWhetherTheCollection(0);//默认商品未收藏，1代表收藏
		} else {
			for(MemberProductCollection scproduct:productCollectionRepository.findByMemberId(currentMember.getId())){
				if(productId==scproduct.getProductId()){
					detailResult.setWhetherTheCollection(1);
				}
			}
		}
		//商品属性名称 
		PmsProductAttributeExample productAttributeExample = new PmsProductAttributeExample();
		productAttributeExample.createCriteria().andProductAttributeCategoryIdEqualTo(product.getProductAttributeCategoryId()).andTypeEqualTo(0);//属性的类型；0->商品规格；1->商品参数
		productAttributeExample.setOrderByClause("sort desc");
		List<PmsProductAttribute> attributeList = pmsProductAttributeMapper.selectByExample(productAttributeExample);
		List<ProductAttributeResult> specList = new ArrayList<>();
		List<ProductAttributeResult> specChildList = new ArrayList<>();
		ProductAttributeResult spec = null;
		ProductAttributeResult specChild = null;
		String array [] = null;
		
		for(PmsProductAttribute attribute : attributeList) {
			spec = new ProductAttributeResult();
			spec.setId(attribute.getId());
			spec.setName(attribute.getName());
			specList.add(spec);
			
			//属性录入方式：0->手工录入；1->从列表中选取
			//是否支持手动新增；0->不支持；1->支持
			if(1 == attribute.getInputType() && 0 == attribute.getHandAddStatus()) {
				array = attribute.getInputList().split(",");
				for(int i=0; i<array.length; i++) {
					specChild = new ProductAttributeResult();
					specChild.setPid(attribute.getId());
					specChild.setName(array[i]);
					specChildList.add(specChild);
				}
			} else {
				PmsProductAttributeValueExample attributeValueExample = new PmsProductAttributeValueExample();
				attributeValueExample.createCriteria().andProductIdEqualTo(product.getId()).andProductAttributeIdEqualTo(attribute.getId());
				List<PmsProductAttributeValue> attributeValueList = productAttributeValueMapper.selectByExample(attributeValueExample);
				for(PmsProductAttributeValue value : attributeValueList) {
					array = value.getValue().split(",");
					for(String s : array) {
						specChild = new ProductAttributeResult();
						specChild.setPid(attribute.getId());
						specChild.setName(s);
						specChildList.add(specChild);
					}
				}
			}
		}
		
		detailResult.setSpecList(specList);
		detailResult.setSpecChildList(specChildList);
		List<PmsComment> pmsComment =(List<PmsComment>) pmsCommentMapper.getPmsComment(productId);//评论基础信息
		if(pmsComment.size()>0){
		int i=pmsCommentMapper.getCountComment(productId);//评论总数
		int j=pmsCommentMapper.getApplauseCount(productId)*100/i;//好评率  好评数除以评论 总数 默认好评为大于等于2星
		detailResult.setCountComent(i);
		detailResult.setApplauseRate(j);
		for(int a=0;a<pmsComment.size();a++){
			List<PmsCommentReplay> pcr =(List<PmsCommentReplay>) pmsCommentReplayMapper.getPmsCommentReplay(pmsComment.get(a).getId());
			pmsComment.get(a).setPmsCommentReplay(pcr);//评论回复 逐个添加
		}
		detailResult.setPmsComment(pmsComment);
		}
		
		//根据会员等级显示不同的商品价格
		UmsMember member = memberService.getCurrentMember();
        if(member != null) {
        	BigDecimal discount = commonService.getDiscount(member.getId());
        	if(discount != null) {
        		detailResult.setPrice(detailResult.getPrice().multiply(discount).setScale(2, BigDecimal.ROUND_HALF_UP));
        	}
        }	
		
		return detailResult;
	}

	@Override
	public ProductSkuResult getProductSku(Long productId, String sp1, String sp2, String sp3) {
		PmsSkuStockExample example = new PmsSkuStockExample();
		PmsSkuStockExample.Criteria criteria = example.createCriteria();
		criteria.andProductIdEqualTo(productId).andSp1EqualTo(sp1);
		if(!StringUtils.isEmpty(sp2)) {
			criteria.andSp2EqualTo(sp2);
		}
		if(!StringUtils.isEmpty(sp3)) {
			criteria.andSp2EqualTo(sp3);
		}
		List<PmsSkuStock> list = skuStockMapper.selectByExample(example);
		ProductSkuResult skuResult = new ProductSkuResult();
		for(PmsSkuStock stock : list) {
			BeanUtils.copyProperties(stock, skuResult);
		}
		
		//根据会员等级显示不同的商品价格
		UmsMember member = memberService.getCurrentMember();
        if(member != null) {
        	BigDecimal discount = commonService.getDiscount(member.getId());
        	if(discount != null) {
        		skuResult.setPrice(skuResult.getPrice().multiply(discount).setScale(2, BigDecimal.ROUND_HALF_UP));
        	}
        }
		
		return skuResult;
	}

	@Override
	public List<PmsProduct> getProductList(Long brandId, Long categoryId, String sortType,
			Integer pageSize, Integer pageNum) {
		PageHelper.startPage(pageNum, pageSize);
		PmsProductExample example = new PmsProductExample();
		PmsProductExample.Criteria criteria = example.createCriteria();
		criteria.andDeleteStatusEqualTo(0);
		if(brandId != null) {
			criteria.andBrandIdEqualTo(brandId);
		}
		if(categoryId != null) {
			criteria.andProductCategoryIdEqualTo(categoryId);
		}
		
		//综合排序
		if("1".equals(sortType)) {
			example.setOrderByClause("id asc");
		}
		//销量
		if("2".equals(sortType)) {
			example.setOrderByClause("sale desc");
		}
		//价格升序
		if("3".equals(sortType)) {
			example.setOrderByClause("price asc");
		}
		//价格降序
		if("4".equals(sortType)) {
			example.setOrderByClause("price desc");
		}
		
		List<PmsProduct> productList = productMapper.selectByExample(example);
		
		//根据会员等级显示不同的商品价格
		UmsMember member = memberService.getCurrentMember();
        if(member != null) {
        	BigDecimal discount = commonService.getDiscount(member.getId());
        	if(discount != null) {
        		for(PmsProduct product : productList) {
        			product.setPrice(product.getPrice().multiply(discount).setScale(2, BigDecimal.ROUND_HALF_UP));
        		}
        	}
        }
    	
		return productList;
	}
	
	
}
