package com.fs.hisStore.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.fs.common.constant.LiveKeysConstant;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.core.redis.RedisCacheT;
import com.fs.common.utils.DateUtils;
import com.fs.hisStore.domain.FsStoreProductAttrScrm;
import com.fs.hisStore.domain.FsStoreProductAttrValueScrm;
import com.fs.hisStore.domain.FsStoreProductPurchaseLimitScrm;
import com.fs.hisStore.domain.FsStoreProductScrm;
import com.fs.hisStore.mapper.FsStoreProductAttrScrmMapper;
import com.fs.hisStore.mapper.FsStoreProductAttrValueScrmMapper;
import com.fs.hisStore.mapper.FsStoreProductPurchaseLimitScrmMapper;
import com.fs.hisStore.mapper.FsStoreProductScrmMapper;
import com.fs.hisStore.service.IFsStoreProductPurchaseLimitScrmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 商品限购Service业务层处理
 *
 * @author fs
 * @date 2024-01-01
 */
@Service
public class FsStoreProductPurchaseLimitScrmServiceImpl implements IFsStoreProductPurchaseLimitScrmService {
    @Autowired
    private FsStoreProductPurchaseLimitScrmMapper fsStoreProductPurchaseLimitMapper;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RedisCacheT<FsStoreProductPurchaseLimitScrm> redisCacheT;
    @Autowired
    private FsStoreProductScrmMapper fsStoreProductScrmMapper;
    @Autowired
    private FsStoreProductAttrScrmMapper fsStoreProductAttrScrmMapper;
    @Autowired
    private FsStoreProductAttrValueScrmMapper fsStoreProductAttrValueScrmMapper;


    /**
     * 查询商品限购
     *
     * @param id 商品限购ID
     * @return 商品限购
     */
    @Override
    public FsStoreProductPurchaseLimitScrm selectFsStoreProductPurchaseLimitById(Long id) {
        return fsStoreProductPurchaseLimitMapper.selectFsStoreProductPurchaseLimitById(id);
    }

    /**
     * 查询商品限购列表
     *
     * @param fsStoreProductPurchaseLimit 商品限购
     * @return 商品限购
     */
    @Override
    public List<FsStoreProductPurchaseLimitScrm> selectFsStoreProductPurchaseLimitList(FsStoreProductPurchaseLimitScrm fsStoreProductPurchaseLimit) {
        return fsStoreProductPurchaseLimitMapper.selectFsStoreProductPurchaseLimitList(fsStoreProductPurchaseLimit);
    }

    /**
     * 根据商品ID和用户ID查询限购记录
     *
     * @param productId 商品ID
     * @param userId    用户ID
     * @return 商品限购
     */
    @Override
    public FsStoreProductPurchaseLimitScrm selectByProductIdAndUserId(Long productId, Long userId) {
        String key = "live:order:limit:" + productId + ":" + userId;
        FsStoreProductPurchaseLimitScrm scrm = redisCacheT.getCacheObject(key);
        if(scrm != null){
            return scrm;
        }
        scrm = fsStoreProductPurchaseLimitMapper.selectByProductIdAndUserId(productId, userId);
        redisCacheT.setCacheObject(key, scrm);
        return scrm;
    }

    /**
     * 新增商品限购
     *
     * @param fsStoreProductPurchaseLimit 商品限购
     * @return 结果
     */
    @Override
    public int insertFsStoreProductPurchaseLimit(FsStoreProductPurchaseLimitScrm fsStoreProductPurchaseLimit) {
        fsStoreProductPurchaseLimit.setCreateTime(DateUtils.getNowDate());
        return fsStoreProductPurchaseLimitMapper.insertFsStoreProductPurchaseLimit(fsStoreProductPurchaseLimit);
    }

    /**
     * 修改商品限购
     *
     * @param fsStoreProductPurchaseLimit 商品限购
     * @return 结果
     */
    @Override
    public int updateFsStoreProductPurchaseLimit(FsStoreProductPurchaseLimitScrm fsStoreProductPurchaseLimit) {
        fsStoreProductPurchaseLimit.setUpdateTime(DateUtils.getNowDate());
        return fsStoreProductPurchaseLimitMapper.updateFsStoreProductPurchaseLimit(fsStoreProductPurchaseLimit);
    }

    /**
     * 批量删除商品限购
     *
     * @param ids 需要删除的商品限购ID
     * @return 结果
     */
    @Override
    public int deleteFsStoreProductPurchaseLimitByIds(Long[] ids) {
        return fsStoreProductPurchaseLimitMapper.deleteFsStoreProductPurchaseLimitByIds(ids);
    }

    /**
     * 删除商品限购信息
     *
     * @param id 商品限购ID
     * @return 结果
     */
    @Override
    public int deleteFsStoreProductPurchaseLimitById(Long id) {
        return fsStoreProductPurchaseLimitMapper.deleteFsStoreProductPurchaseLimitById(id);
    }

    /**
     * 增加用户限购数量
     *
     * @param productId 商品ID
     * @param userId    用户ID
     * @param num       增加的数量
     * @return 结果
     */
    @Override
    public int increasePurchaseLimit(Long productId, Long userId, Integer num) {
        String cacheKey = String.format(LiveKeysConstant.PRODUCT_DETAIL_CACHE, productId);
        Map<String, Object> cachedData = redisCache.getCacheObject(cacheKey);

        FsStoreProductScrm product;
        List<FsStoreProductAttrScrm> productAttr;
        List<FsStoreProductAttrValueScrm> productValues;

        if (cachedData != null) {
            // 从缓存中获取数据
            product = (FsStoreProductScrm) cachedData.get("product");
        } else {
            // 缓存中没有，从数据库查询
            product = fsStoreProductScrmMapper.selectFsStoreProductById(productId);
            if (product == null) {
                return -1;
            }
            productAttr = fsStoreProductAttrScrmMapper.selectFsStoreProductAttrByProductId(productId);
            productValues = fsStoreProductAttrValueScrmMapper.selectFsStoreProductAttrValueByProductId(productId);

            // 将数据存入缓存
            Map<String, Object> cacheData = new HashMap<>();
            cacheData.put("product", product);
            cacheData.put("productAttr", productAttr);
            cacheData.put("productValues", productValues);
            redisCache.setCacheObject(cacheKey, cacheData, LiveKeysConstant.PRODUCT_DETAIL_CACHE_EXPIRE, TimeUnit.SECONDS);
        }

        if (product != null && product.getPurchaseLimit() != null && product.getPurchaseLimit() > 0) {
            FsStoreProductPurchaseLimitScrm limit = selectByProductIdAndUserId(productId, userId);
            String key = "live:order:limit:" + productId + ":" + userId;
            if (limit == null) {
                // 创建新记录
                limit = new FsStoreProductPurchaseLimitScrm();
                limit.setProductId(productId);
                limit.setUserId(userId);
                limit.setNum(num);
                redisCacheT.setCacheObject(key, limit);
                return insertFsStoreProductPurchaseLimit(limit);
            } else {
                // 更新现有记录
                limit.setNum(limit.getNum() + num);
                redisCacheT.setCacheObject(key, limit);
                return updateFsStoreProductPurchaseLimit(limit);
            }
        }
        return -1;
    }

    /**
     * 减少用户限购数量
     *
     * @param productId 商品ID
     * @param userId    用户ID
     * @param num       减少的数量
     * @return 结果
     */
    @Override
    public int decreasePurchaseLimit(Long productId, Long userId, Integer num) {
        String cacheKey = String.format(LiveKeysConstant.PRODUCT_DETAIL_CACHE, productId);
        Map<String, Object> cachedData = redisCache.getCacheObject(cacheKey);

        FsStoreProductScrm product;
        List<FsStoreProductAttrScrm> productAttr;
        List<FsStoreProductAttrValueScrm> productValues;

        if (cachedData != null) {
            // 从缓存中获取数据
            product = (FsStoreProductScrm) cachedData.get("product");
        } else {
            // 缓存中没有，从数据库查询
            product = fsStoreProductScrmMapper.selectFsStoreProductById(productId);
            if (product == null) {
                return -1;
            }
            productAttr = fsStoreProductAttrScrmMapper.selectFsStoreProductAttrByProductId(productId);
            productValues = fsStoreProductAttrValueScrmMapper.selectFsStoreProductAttrValueByProductId(productId);

            // 将数据存入缓存
            Map<String, Object> cacheData = new HashMap<>();
            cacheData.put("product", product);
            cacheData.put("productAttr", productAttr);
            cacheData.put("productValues", productValues);
            redisCache.setCacheObject(cacheKey, cacheData, LiveKeysConstant.PRODUCT_DETAIL_CACHE_EXPIRE, TimeUnit.SECONDS);
        }
        if (product != null && product.getPurchaseLimit() != null && product.getPurchaseLimit() > 0) {
            FsStoreProductPurchaseLimitScrm limit = selectByProductIdAndUserId(productId, userId);
            if (limit != null) {
                int newNum = limit.getNum() - num;
                if (newNum <= 0) {
                    // 如果数量为0或负数,删除记录
                    return deleteFsStoreProductPurchaseLimitById(limit.getId());
                } else {
                    // 更新数量
                    limit.setNum(newNum);
                    return updateFsStoreProductPurchaseLimit(limit);
                }
            }
            return 0;
        }
        return -1;
    }
}

