package cn.freemud.service.impl;

import cn.freemud.entities.vo.CartGoods;
import cn.freemud.entities.vo.CustomerInfoVo;
import cn.freemud.entities.vo.UpdateGiftAttrRequestVo;
import cn.freemud.service.CartGiftService;
import cn.freemud.service.cache.GiftCacheManager;
import cn.freemud.service.customer.CustomerInfoManager;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Clover.z
 * @Date 2021/11/1
 * @Desc
 */
@RequiredArgsConstructor
@Service
public class CartGiftServiceImpl implements CartGiftService {

    private final CustomerInfoManager customerInfoManager;
    private final GiftCacheManager giftCacheManager;

    /**
     * 更新赠品的购物车行中属性信息
     *
     * @param requestVo
     * @return
     */
    @Override
    public CartGoods updateGiftAttr(UpdateGiftAttrRequestVo requestVo) {
        // 查询登陆用户信息
        CustomerInfoVo user = customerInfoManager.getCustomerInfoVo(requestVo.getSessionId());
        String partnerId = requestVo.getPartnerId();
        String storeCode = requestVo.getShopId();
        // 查询赠品缓存
        CartGoods goods = giftCacheManager.queryGiftGoods(partnerId, storeCode, user.getMemberId(), requestVo.getUid());
        List<CartGoods.CartGoodsExtra> attrList = new ArrayList<>();
        List<String> nameList = new ArrayList<>();
        requestVo.getExtra().forEach(a -> {
            CartGoods.CartGoodsExtra e = new CartGoods.CartGoodsExtra();
            e.setAttributeId(a.getAttributeId());
            e.setAttributeName(a.getAttributeName());
            attrList.add(e);
            nameList.add(a.getAttributeName());
        });
        goods.setExtra(attrList);
        goods.setSubName(StringUtils.join(nameList, "/"));
        // 更新赠品缓存
        giftCacheManager.updateGiftGoods(partnerId, storeCode, user.getMemberId(), goods);
        return goods;
    }
}
