package com.caimei.www.service.page.impl;

import com.caimei.www.mapper.ShoppingDao;
import com.caimei.www.mapper.AccountDao;
import com.caimei.www.pojo.JsonModel;
import com.caimei.www.pojo.order.CartItem;
import com.caimei.www.pojo.order.CartSupplier;
import com.caimei.www.pojo.account.Account;
import com.caimei.www.service.CommonServiceUtil;
import com.caimei.www.service.page.ShoppingService;
import com.caimei.www.utils.ImageUtil;
import com.caimei.www.utils.PriceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Description
 *
 * @author : Charles
 * @date : 2020/7/23
 */
@Slf4j
@Service
public class ShoppingServiceImpl implements ShoppingService {
    @Value("${caimei.wwwDomain}")
    private String domain;
    @Resource
    private ShoppingDao shoppingDao;
    @Resource
    private AccountDao accountDao;
    @Resource
    private CommonServiceUtil commonServiceUtil;
    /**
     * 顶部购物车数据
     *
     * @param userId
     * @return
     */
    @Override
    public JsonModel<List<CartItem>> getHeaderCart(Integer userId) {
        if (userId == null || userId == 0) { return JsonModel.error("参数异常", null);}
        List<CartItem> headCarts = shoppingDao.getHeadCarts(userId);
        return JsonModel.success(headCarts);
    }

    /**
     * 购物车列表
     *
     * @param userId
     * @return
     */
    @Override
    public JsonModel<Map<String, Object>> getShoppingCarts(Integer userId) {
        if (userId == null || userId == 0) { return JsonModel.error("参数异常", null);}
        List<CartSupplier> cartSuppliers = shoppingDao.getCartSuppliers(userId);
        List<CartItem> invalidCarts = new ArrayList<>();
        Account account = accountDao.getUserById(userId);
        AtomicInteger totalCount = new AtomicInteger();
        AtomicInteger totalSize = new AtomicInteger();
        AtomicReference<Double> totalPrice = new AtomicReference<>(0d);
        cartSuppliers.forEach(supplier -> {
            List<CartItem> cartItems = shoppingDao.getShoppingCartBySupplierId(supplier.getId(), userId);
            AtomicReference<Double> supplierPrice = new AtomicReference<>(0d);
            AtomicInteger itemCount = new AtomicInteger();
            Iterator<CartItem> iterator = cartItems.iterator();
            while (iterator.hasNext()) {
                CartItem cartItem = iterator.next();
                cartItem.setImage(ImageUtil.getImageURL("product", cartItem.getImage(), 0, domain));
                if (cartItem.getValidFlag() == 2) {
                    // 已上架
                    cartItem.setStatus(0);
                    // 价格是否可见
                    boolean priceVisible = (cartItem.getPriceFlag() == 0 || (cartItem.getPriceFlag() == 2 && account.getIdentity() ==2));
                    if (priceVisible) {
                        // 设置商品价格
                        commonServiceUtil.setCartItemPrice(cartItem, userId);
                        // 该供应商下价格累加
                        supplierPrice.updateAndGet(v -> v + PriceUtil.add(supplierPrice, cartItem.getPrice()).doubleValue());
                        itemCount.incrementAndGet();
                        totalCount.updateAndGet(v -> v + cartItem.getNumber());
                    } else {
                        // 失效商品
                        if (cartItem.getPriceFlag() == 1){
                            // 未公开价格
                            cartItem.setStatus(6);
                        } else if (cartItem.getPriceFlag() == 2) {
                            // 价格仅会员可见
                            cartItem.setStatus(5);
                        }
                    }
                } else {
                    // 失效商品
                    if (cartItem.getValidFlag() == 0) {
                        // 后台逻辑删除
                        cartItem.setStatus(1);
                    } else if (cartItem.getValidFlag() == 9) {
                        // 已冻结
                        cartItem.setStatus(2);

                    } else if (cartItem.getValidFlag() == 3) {
                        // 已下架
                        cartItem.setStatus(3);
                    } else if (cartItem.getStock() == null || cartItem.getStock() == 0) {
                        // 售罄
                        cartItem.setStatus(4);
                    } else if (cartItem.getStock() != null && (cartItem.getStock() < cartItem.getMin() || cartItem.getStock() < cartItem.getNumber())) {
                        // 库存不足
                        cartItem.setStatus(7);
                    }
                    invalidCarts.add(cartItem);
                    iterator.remove();
                }
            }
            supplier.setCartList(cartItems);
            supplier.setTotalPrice(supplierPrice.get());
            supplier.setCount(itemCount.get());
            totalPrice.updateAndGet(v -> v + PriceUtil.add(totalPrice, supplierPrice.get()).doubleValue());
            totalSize.updateAndGet(v -> v + itemCount.get());
        });
        cartSuppliers.removeIf(supplier -> (null != supplier && supplier.getCount() == 0));
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", cartSuppliers);
        resultMap.put("invalid", invalidCarts);
        resultMap.put("totalSize", totalSize);
        resultMap.put("totalCount", totalCount);
        resultMap.put("totalPrice", totalPrice);
        return JsonModel.success(resultMap);
    }

}
