package com.cpop.mall.framework.task;

import com.cpop.core.utils.SpringUtils;
import com.cpop.mall.business.entity.Product;
import com.cpop.mall.business.entity.ProductRecord;
import com.cpop.mall.business.service.ProductRecordService;
import com.cpop.mall.business.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

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

import static com.cpop.mall.business.entity.table.ProductRecordTableDef.PRODUCT_RECORD;
import static com.cpop.mall.business.entity.table.ShoppingCartTableDef.SHOPPING_CART;

/**
 * @author DB
 * @createTime 2023/11/09 16:42
 * @description
 */
@Component
@Slf4j
public class ShoppingCartAsyncTask {

    /**
     * @Description: 异步更新购物车价格
     * @param product 商品
     * @Author DB
     * @Date: 2023/11/1 0:09
     */
    @Async("customAsyncThreadPool")
    public void asyncUpdateShoppingCartAmount(Product product) {
        //获取商品记录
        List<ProductRecord> recordList = SpringUtils.getBean(ProductRecordService.class).queryChain()
                .where(PRODUCT_RECORD.PRODUCT_ID.eq(product.getId()))
                .list();
        //批量修改购物车产品价格
        ShoppingCartService cartService = SpringUtils.getBean(ShoppingCartService.class);
        recordList.forEach(item->{
            cartService.updateChain().setRaw(SHOPPING_CART.AMOUNT, item.getRecordPrice() + " * number")
                    .setRaw(SHOPPING_CART.POINT, item.getRecordPoints() + " * number")
                    .where(SHOPPING_CART.PRODUCT_RECORD_ID.eq(item.getId())).update();
        });
    }

    /**
     * @Description: 异步删除购物车
     * @param productId 商品Id
     * @Author DB
     * @Date: 2023/11/1 0:09
     */
    @Async("customAsyncThreadPool")
    public void asyncRemoveShoppingCart(String productId) {
        //获取商品记录
        List<ProductRecord> recordList = SpringUtils.getBean(ProductRecordService.class).queryChain()
                .where(PRODUCT_RECORD.PRODUCT_ID.eq(productId))
                .list();
        //批量修改购物车产品价格
        if (!recordList.isEmpty()){
            ShoppingCartService cartService = SpringUtils.getBean(ShoppingCartService.class);
            cartService.updateChain()
                    .where(SHOPPING_CART.PRODUCT_RECORD_ID.in(recordList.stream().map(ProductRecord::getId).collect(Collectors.toSet())))
                    .remove();
        }
    }
}
