package cn.freemud.demo.service;

import cn.freemud.demo.entities.CheckCartRequest;
import cn.freemud.demo.entities.ShoppingCartContext;
import cn.freemud.entities.vo.CartGoods;
import cn.freemud.entities.vo.ShoppingCartGoodsBaseResponseVo;
import cn.freemud.service.impl.AssortmentSdkService;
import com.alibaba.fastjson.JSONObject;
import com.freemud.sdk.api.assortment.shoppingcart.service.impl.ShoppingCartBaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class ShoppingBaseServiceImpl implements ShoppingCartService {

    @Autowired
    private AssortmentSdkService assortmentSdkService;

    @Autowired
    private ShoppingCartBaseServiceImpl shoppingCartBaseService;

    @Override
    public List<CartGoods> updateAndGetShoppingCart(List<CartGoods> cartGoodsList, CartGoods cartGoods, ShoppingCartContext cartContext) {

        List<CartGoods> nowCartGoodsList = new ArrayList<>();
        //判断当前商品在购物车是否已存在,存在则数量＋1,不存在商品行 + 1
        cartGoodsList.forEach(oldCartGoods -> {
            int index;
            if ((index = nowCartGoodsList.indexOf(oldCartGoods)) >= 0) {
                nowCartGoodsList.get(index).setQty(nowCartGoodsList.get(index).getQty() + cartGoods.getQty());
            } else {
                nowCartGoodsList.add(oldCartGoods);
            }
        });
        // 重新set购物车信息到缓存中
        assortmentSdkService.setShoppingCart(cartContext.getPartnerId(), cartContext.getShopId(),
                cartContext.getUserId(), nowCartGoodsList, cartContext.getSessionId(), cartContext.getTableNumber(), this.shoppingCartBaseService);
        cartGoodsList.clear();
        cartGoodsList.addAll(nowCartGoodsList);
        return nowCartGoodsList;

    }

    @Override
    public CheckCartRequest checkShoppingCart(List<CartGoods> cartGoodsList, CartGoods cartGoods, ShoppingCartContext cartContext) {

        ShoppingCartGoodsBaseResponseVo shoppingCartGoodsResponseVo = new ShoppingCartGoodsBaseResponseVo();
        if (cartGoods != null){
            cartGoodsList.add(cartGoods);
        }


        //当商品全部添加完毕,校验购物车商品(是否合法,上下架,点餐方式,是否在当前菜单中...),并移除非法商品
        com.freemud.sdk.api.assortment.shoppingcart.request.CheckCartRequest checkCartRequest = assortmentSdkService.checkShoppingCartSdk(cartGoodsList, cartContext.getPartnerId(),
                cartContext.getShopId(), shoppingCartGoodsResponseVo, cartContext.getOrderType(),
                "", cartContext.getMenuType(), shoppingCartBaseService);

        CheckCartRequest result = JSONObject.parseObject(JSONObject.toJSONString(checkCartRequest), CheckCartRequest.class);
        result.setChanged(checkCartRequest.getShoppingCartGoodsResponseVo().getChanged());
        result.setToastMsg(checkCartRequest.getShoppingCartGoodsResponseVo().getToastMsg());

        return result;
    }
}
