package cn.freemud.service.impl;

import cn.freemud.entities.dto.GoodsBeanDto;
import cn.freemud.entities.dto.UserLoginInfoDto;
import cn.freemud.entities.dto.activity.ActivityQueryDto;
import cn.freemud.entities.dto.activity.ActivityQueryResponseDto;
import cn.freemud.entities.vo.SpuProductVo;
import cn.freemud.enums.ActivityTypeEnum;
import cn.freemud.service.ActivityService;
import cn.freemud.service.ItemService;
import cn.freemud.service.UserService;
import com.google.gson.Gson;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 买赠活动
 */
@Service
public class BuyOneGetActivityServiceImpl {

    private final static String ACTIVITYNAME = "买一赠一";
    @Autowired
    private ActivityService activityService;

    @Autowired
    private UserService userService;
    public List<SpuProductVo> getBuyOneGetSpuProductVo(List<SpuProductVo> products,String partnerId, String shopId, String wxappid,String sessionId, Integer orderType) {
        UserLoginInfoDto userLoginInfoDto = userService.getUserLoginInfoBySessionId(sessionId);
        String userId = userLoginInfoDto.getMemberId();
        Map<String, GoodsBeanDto> goodsBeanDtoMap = getBuyOneGetActivity(partnerId, shopId, wxappid, userId, orderType);
        if (CollectionUtils.isNotEmpty(products) && goodsBeanDtoMap != null) {
            products.forEach(spuProductVo -> {
                GoodsBeanDto goodsBeanDto = goodsBeanDtoMap.get(spuProductVo.getSpuId());
                if (goodsBeanDto != null) {
                    spuProductVo.setActivityType(ActivityTypeEnum.TYPE_61.getCode());
                    spuProductVo.setActivityName(ACTIVITYNAME);
                }
            });
        }
        return products;
    }
    public Map<String,GoodsBeanDto> getBuyOneGetActivity(String partnerId, String shopId, String wxappid,String userId, Integer orderType) {
        ActivityQueryDto activityQueryDto = ActivityQueryDto.builder().partnerId(partnerId).appId(wxappid).storeId(shopId).userId(userId).orderType(orderType).build();
        ActivityQueryResponseDto activityQueryResponseDto = activityService.queryActivitys(activityQueryDto, ActivityTypeEnum.TYPE_61, null);
        if (activityQueryResponseDto != null && CollectionUtils.isNotEmpty(activityQueryResponseDto.getResult())) {
            List<GoodsBeanDto> goodsBeanDtos = activityQueryResponseDto.getResult().get(0).getGoods();
            if (CollectionUtils.isNotEmpty(goodsBeanDtos)) {
                Map<String,GoodsBeanDto> goodsBeanDtoMap=goodsBeanDtos.stream().collect(Collectors.toMap(GoodsBeanDto::getCategory,a -> a,(k1,k2)->k1));
                return goodsBeanDtoMap;
            }
        }
        return null;
    }
}
