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;
import java.util.Optional;

/**
 * @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);
        // 多规格赠品，需要带上规格name
        String skuName = Optional.ofNullable(goods.getSkuName()).orElse("");
        String spuName = Optional.ofNullable(goods.getSpuName()).orElse("");
        String skuPreName = "";
        if (skuName.length() > spuName.length()+1) {
            skuPreName = skuName.substring(spuName.length() + 1) + "/";
        }
        goods.setSubName(skuPreName + StringUtils.join(nameList, "/"));
        // 更新赠品缓存
        giftCacheManager.updateGiftGoods(partnerId, storeCode, user.getMemberId(), goods);
        return goods;
    }
}
