package com.tashow.cloud.product.mapper;

import java.util.*;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tashow.cloud.mybatis.mybatis.core.mapper.BaseMapperX;
import com.tashow.cloud.productapi.api.product.dto.SkuDO;
import com.tashow.cloud.productapi.api.product.vo.sku.SkuRecycleBinVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;

/**
 * 单品SKU Mapper
 *
 * @author 芋道源码
 */
@Mapper
public interface SkuMapper extends BaseMapperX<SkuDO> {

    IPage<SkuRecycleBinVO> getSkuRecycleBinPageList(Page<?> page, @Param("prodId") Long prodId, @Param("properties")String properties);

    IPage<SkuDO> getSkuPageList(Page<?> page, @Param("prodId") Long prodId,@Param("skuId") Long skuId, @Param("properties")String properties);


    List<SkuDO> getSkuListByName( @Param("prodId")Long prodId , @Param("propertiesName")String propertiesName);

    List<String> selectPropertiesByProdIdAndNotDeleted( @Param("prodId")Long prodId);

    List<String> selectPropertiesByProdIdShelf( @Param("prodId")Long prodId);

    int deleteBySkuId( @Param("skuId")Long skuId);

    void batchSkuDeleted(@Param("ids") List<Long> ids);

    void updateSkuDeleted(@Param("skuId") Long skuId);


    List<SkuDO> getskuListBySkuIds( @Param("ids")List<Long> ids);

    List<SkuDO> getskuListByDeleted( @Param("prodId")Long prodId,@Param("ids")List<Long> ids);

    void batchSkuRecover(@Param("ids") List<Long> ids);

    // 查询商品下所有 SKU 的 is_shelf 状态（未删除）
    List<Integer> selectShelfStatusByProdId(@Param("prodId") Long prodId);

    /**
     * 扣减库存（带乐观锁）
     * @param skuId 单品ID
     * @param stocksNum 扣减数量
     * @param version 版本号
     * @return 更新影响的行数
     */
    @Update("UPDATE tz_sku SET stocks = stocks - #{stocksNum}, version = version + 1, update_time = NOW() " +
            "WHERE sku_id = #{skuId} AND version = #{version} AND stocks >= #{stocksNum} AND deleted = 0")
    int reduceStocks(@Param("skuId") Long skuId,
                     @Param("stocksNum") Integer stocksNum,
                     @Param("version") Integer version);

    /**
     * 增加库存
     */
    @Update("UPDATE tz_sku SET stocks = stocks + #{stocksNum}, version = version + 1, update_time = NOW() " +
            "WHERE sku_id = #{skuId} AND deleted = 0")
    int increaseStocks(@Param("skuId") Long skuId,
                       @Param("stocksNum") Integer stocksNum);
}