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.service.OrderService;
import com.mybatisflex.core.logicdelete.LogicDeleteManager;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.cpop.mall.business.entity.table.OrderTableDef.ORDER;


/**
 * @author DB
 * @createTime 2023/11/06 16:16
 * @description 新客限定策略
 */
@Component
public class NewCustomerRestrictStrategy implements BuyRestrictStrategy{

    /**
     * 购买限制
     * @param product 产品
     */
    @Override
    public void buyRestrict(Product product, Map<String, Integer> recordNumIsEnough) {
        //查询当前用户是否有购买记录
        JSONObject loginUserInfo = SecurityUtils.getInstance().getLoginUserInfo();
        OrderService orderService = SpringUtils.getBean(OrderService.class);
        //跳过逻辑删除
        LogicDeleteManager.execWithoutLogicDelete(() -> {
            long count = orderService.queryChain()
                    .where(ORDER.PAY_USER_ID.eq(loginUserInfo.getString("userId")))
                    .count();
            if (count > 0) {
                //存在过购买记录
                throw new ServiceException("您已不是新客,无法购买商品" + product.getProductName());
            }
        });
    }
}
