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.jambox.business.entity.BrandExtend;
import com.cpop.jambox.business.service.BrandExtendService;
import com.cpop.mall.business.entity.Product;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.Map;

import static com.cpop.jambox.business.entity.table.BrandExtendTableDef.BRAND_EXTEND;

/**
 * @author DB
 * @createTime 2023/11/06 15:26
 * @description
 */
@Component
public class MemberRestrictStrategy implements BuyRestrictStrategy{

    /**
     * @descriptions 会员购买策略
     * @author DB
     * @date 2023/11/06 15:47
     * @param product 商品
     * @return: void
     */
    @Override
    public void buyRestrict(Product product, Map<String, Integer> recordNumIsEnough) {
        // 获取当前用户信息
        JSONObject loginUserInfo = SecurityUtils.getInstance().getLoginUserInfo();
        //获取品牌信息
        BrandExtend brandExtend = SpringUtils.getBean(BrandExtendService.class).queryChain()
                .where(BRAND_EXTEND.BRAND_ID.eq(loginUserInfo.getString("brandId")))
                .one();
        //查询当前用户是否是会员
        try {
            DataSourceKey.use("jambox");
            long count = Db.selectCountByQuery("j_membership", QueryWrapper.create()
                    .select()
                    .leftJoin("t_brand_info").on("t_brand_info.brand_id = j_membership.brand_id")
                    //手机号
                    .where("j_membership.phone = ?", loginUserInfo.getString("phoneNumber"))
                    //品牌id
                    .and("t_brand_info.brand_id = ?", brandExtend.getBrandCloudId())
                    //会员时间未过期
                    .and("j_membership.end_time >= ?", LocalDate.now())
                    .and("j_membership.deleted = 1"));
            //没有会员
            if (count == 0) {
                throw new ServiceException("你尚未成为会员,无法购买商品:" + product.getProductName());
            }
        } finally {
            DataSourceKey.clear();
        }
    }
}
