package com.cpop.mall.framework.strategy.buyRestrict;

import com.alibaba.fastjson.JSONObject;
import com.cpop.core.base.exception.ServiceException;
import com.cpop.core.utils.SecurityUtils;
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.OrderDetailService;
import com.cpop.mall.business.service.ProductRecordService;
import com.mybatisflex.core.logicdelete.LogicDeleteManager;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.cpop.mall.business.entity.table.OrderDetailTableDef.ORDER_DETAIL;
import static com.cpop.mall.business.entity.table.OrderTableDef.ORDER;
import static com.cpop.mall.business.entity.table.ProductRecordTableDef.PRODUCT_RECORD;
import static com.cpop.mall.business.entity.table.ProductTableDef.PRODUCT;

/**
 * @author DB
 * @createTime 2023/11/06 16:42
 * @description 用户限购
 */
@Component
public class UserRestrictStrategy implements BuyRestrictStrategy{

    @Override
    public void buyRestrict(Product product, Map<String, Integer> recordNumIsEnough) {
        //查询用户已购买的数量
        JSONObject loginUserInfo = SecurityUtils.getInstance().getLoginUserInfo();
        OrderDetailService orderDetailService = SpringUtils.getBean(OrderDetailService.class);
        ProductRecordService productRecordService = SpringUtils.getBean(ProductRecordService.class);
        //产品记录
        List<ProductRecord> productRecordList = productRecordService.queryChain().where(PRODUCT_RECORD.PRODUCT_ID.eq(product.getId())).list();
        Set<String> recordSet = productRecordList.stream().map(ProductRecord::getId).collect(Collectors.toSet());
        //跳过逻辑删除
        LogicDeleteManager.execWithoutLogicDelete(() -> {
            //已存在订单数
            long count = orderDetailService.queryChain()
                    .leftJoin(ORDER).on(ORDER.ID.eq(ORDER_DETAIL.ORDER_ID))
                    .leftJoin(PRODUCT_RECORD).on(PRODUCT_RECORD.ID.eq(ORDER_DETAIL.PRODUCT_RECORD_ID))
                    .leftJoin(PRODUCT).on(PRODUCT.ID.eq(PRODUCT_RECORD.PRODUCT_ID))
                    .where(ORDER.PAY_USER_ID.eq(loginUserInfo.getString("userId")))
                    .and(PRODUCT.ID.eq(product.getId()))
                    .count();
            //产品购买数量
            AtomicInteger num = new AtomicInteger();
            recordNumIsEnough.forEach((key, value) -> {
                if (recordSet.contains(key)) {
                    num.addAndGet(value);
                }
            });
            if (product.getLimitNum() - count < num.get()) {
                //存在过购买记录
                throw new ServiceException("您购买的商品已超出限制,无法购买商品" + product.getProductName());
            }
        });

    }
}
