package com.seer.teach.mall.app.good.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.enums.GoodSaleEnum;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.mall.app.good.service.IAppGoodsService;
import com.seer.teach.mall.app.good.service.IAppGoodsSpecificationService;
import com.seer.teach.mall.convert.GoodsConvert;
import com.seer.teach.mall.convert.GoodsSpecificationConvert;
import com.seer.teach.mall.entity.GoodsEntity;
import com.seer.teach.mall.entity.GoodsSpecificationEntity;
import com.seer.teach.mall.request.CategoryTypeReq;
import com.seer.teach.mall.request.GoodSearchReq;
import com.seer.teach.mall.request.GoodsDetailsReq;
import com.seer.teach.mall.response.GoodSpuDetailResp;
import com.seer.teach.mall.response.GoodsResp;
import com.seer.teach.mall.response.GoodsSpecificationResp;
import com.seer.teach.mall.service.IGoodsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * WechatGoodsServiceImpl类实现IWechatGoodsService接口，提供微信商城商品相关服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AppGoodsServiceImpl implements IAppGoodsService {

    private final IGoodsService goodsService;

    private final IAppGoodsSpecificationService specificationService;

    /**
     * 根据商品类别查询商品列表
     * @param params
     * @return
     */
    @Override
    public IPage<GoodsEntity> getPageListByCategoryId(CategoryTypeReq params) {
        Page<GoodsEntity> page = new Page<>(params.getPage(), params.getLimits());
        IPage<GoodsEntity> pageList = goodsService.page(page,
                Wrappers.lambdaQuery(GoodsEntity.class)
                        .eq(GoodsEntity::getCategoryId, params.getCategoryId())
                        .eq(StringUtils.isNotBlank(params.getTenantId()),GoodsEntity::getTenantId, params.getTenantId()));
        if(CollectionUtils.isEmpty(pageList.getRecords())){
            return new Page<>();
        }
        pageList.getRecords().forEach(item-> {
            item.setSalesCount(item.getSalesCount() + item.getVirtualSellVolume());
        });
        return pageList;
    }

    /**
     * 根据商品ID查询商品详情
     * @param params
     * @return
     */
    @Override
    public GoodSpuDetailResp getGoodsDetails(GoodsDetailsReq params) {
        GoodsEntity goodsEntity = goodsService.getById(params.getId());

        List<GoodsSpecificationEntity> specificationEntities = specificationService.list(new LambdaUpdateWrapper<>(GoodsSpecificationEntity.class).eq(GoodsSpecificationEntity::getGoodsId, params.getId()));

        GoodSpuDetailResp detailResp = GoodsConvert.INSTANCE.one(goodsEntity);

        Map<Integer, GoodSpuDetailResp.Attribute> itemMap = new LinkedHashMap<>();
        Map<String, GoodSpuDetailResp.Item> specificationEntityMap = new HashMap<>();
        for(GoodsSpecificationEntity specification : specificationEntities){
            List<GoodsSpecificationEntity.Attribute> attributes = specification.getAttributes();
            StringJoiner key = new StringJoiner("_");
            for(GoodsSpecificationEntity.Attribute attribute : attributes){
                key.add(String.valueOf(attribute.getAttributeId())).add(String.valueOf(attribute.getValueId()));
                GoodSpuDetailResp.Attribute item = itemMap.get(attribute.getAttributeId());
                if( Objects.nonNull( item)){
                    GoodSpuDetailResp.Value value = new GoodSpuDetailResp.Value(attribute.getValueId(), attribute.getValueName());
                    item.addValue(value);
                }else{
                    item = new GoodSpuDetailResp.Attribute(attribute.getAttributeId(), attribute.getAttributeName(), attribute.getValueId(), attribute.getValueName());
                    itemMap.put(attribute.getAttributeId(), item);
                }
            }
            GoodSpuDetailResp.Item item = new GoodSpuDetailResp.Item();
            item.setSkuId(specification.getId());
            item.setBarCode(specification.getBarCode());
            item.setPicUrl(specification.getPicUrl());
            item.setStock(specification.getStock());
            item.setPrice(specification.getPrice());
            specificationEntityMap.put(key.toString(), item);
        }
        detailResp.setAttributes(itemMap.values());
        detailResp.setSkuItemMap(specificationEntityMap);
        detailResp.setSalesCount(goodsEntity.getSalesCount() + goodsEntity.getVirtualSellVolume());

        // 更新浏览量
        goodsService.update(new LambdaUpdateWrapper<>(GoodsEntity.class).eq(GoodsEntity::getId, params.getId()).set(GoodsEntity::getBrowseCount, goodsEntity.getBrowseCount() + 1));
        return detailResp;
    }

    @Override
    public IPage<GoodsEntity> searchGoods(GoodSearchReq params) {
        // 创建一个分页对象
        Page<GoodsEntity> page = Page.of(params.getPageNo(), params.getPageSize());
        // 初始化返回的分页列表对象
        IPage<GoodsEntity> resultPage = goodsService.page(page,
                Wrappers.lambdaQuery(GoodsEntity.class)
                        .like(StringUtils.isNotBlank(params.getSearchKey()), GoodsEntity::getName, params.getSearchKey())
                        .eq(Objects.nonNull(params.getCategoryId()), GoodsEntity::getCategoryId, params.getCategoryId())
                        .eq(Objects.nonNull(params.getIsNew()), GoodsEntity::getIsNew, params.getIsNew())
                        .eq(Objects.nonNull(params.getIsLimited()), GoodsEntity::getIsLimited, params.getIsLimited())
                        .eq(Objects.nonNull(params.getIsFeaturedRecommend()), GoodsEntity::getIsFeaturedRecommend, params.getIsFeaturedRecommend())
                        .eq(Objects.nonNull(params.getIsSpecialOffer()), GoodsEntity::getIsSpecialOffer, params.getIsSpecialOffer())
                        .eq(Objects.nonNull(params.getIsHot()), GoodsEntity::getIsHot, params.getIsHot())
                        .eq(StringUtils.isNotBlank(params.getTenantId()), GoodsEntity::getTenantId, params.getTenantId())
                        .eq(GoodsEntity::getIsOnSale, GoodSaleEnum.ON_SALE.getCode())
                        .orderByDesc(GoodsEntity::getSalesCount));
        if(log.isDebugEnabled()){
            log.info("模糊查询商品列表结果：{}", resultPage.getRecords());
        }
        return resultPage;
    }



    @Override
    public PageListBean<GoodsResp> getPageList(GoodSearchReq searchReq) {
        IPage<GoodsEntity> iPage = searchGoods(searchReq);
        List<GoodsEntity> records = iPage.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return new PageListBean<>();
        }
        Set<Integer> goodIds = records.stream().map(GoodsEntity::getId).collect(Collectors.toSet());
        List<GoodsSpecificationEntity> specificationEntities = specificationService.list(new LambdaUpdateWrapper<>(GoodsSpecificationEntity.class).in(GoodsSpecificationEntity::getGoodsId,goodIds));
        PageListBean<GoodsResp> pageListBean = PageConverterUtils.convertPageListBean(iPage, GoodsConvert.INSTANCE::convertList);

        List<GoodsSpecificationResp> goodsSpecificationRespList = GoodsSpecificationConvert.INSTANCE.list(specificationEntities);
        Map<Integer, List<GoodsSpecificationResp>> specificationMap = goodsSpecificationRespList.stream().collect(Collectors.groupingBy(GoodsSpecificationResp::getGoodsId));
        pageListBean.getList().forEach(goodsResp -> {
            goodsResp.setSpecifications(specificationMap.get(goodsResp.getId()));
        });
        return pageListBean;
    }

}
