package com.erp.tenant.repository.goods;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.tenant.entity.goods.Goods;
import org.apache.ibatis.annotations.*;

/**
 * 商品数据访问
 */
@Mapper
public interface GoodsRepository extends BaseMapper<Goods> {

    @Select("SELECT * FROM goods WHERE id = #{id} AND tenant_id = #{tenantId} AND deleted_at IS NULL")
    Goods findById(@Param("id") Long id, @Param("tenantId") Long tenantId);

    @Select("SELECT * FROM goods WHERE goods_code = #{goodsCode} AND tenant_id = #{tenantId} AND deleted_at IS NULL")
    Goods findByGoodsCode(@Param("goodsCode") String goodsCode, @Param("tenantId") Long tenantId);

    @Select("<script>" +
            "SELECT g.* FROM goods g " +
            "WHERE g.tenant_id = #{tenantId} AND g.deleted_at IS NULL " +
            "<if test='keyword != null'> AND (g.name LIKE CONCAT('%', #{keyword}, '%') OR g.goods_code LIKE CONCAT('%', #{keyword}, '%') OR g.alias LIKE CONCAT('%', #{keyword}, '%')) </if>" +
            "<if test='categoryId != null'> AND g.category_id = #{categoryId} </if>" +
            "<if test='brandId != null'> AND g.brand_id = #{brandId} </if>" +
            "<if test='status != null'> AND g.status = #{status} </if>" +
            "ORDER BY g.updated_at DESC" +
            "</script>")
    IPage<Goods> findPage(Page<Goods> page,
                          @Param("tenantId") Long tenantId,
                          @Param("keyword") String keyword,
                          @Param("categoryId") Long categoryId,
                          @Param("brandId") Long brandId,
                          @Param("status") Integer status);

    @Select("<script>" +
            "SELECT COUNT(*) FROM goods WHERE tenant_id = #{tenantId} AND deleted_at IS NULL " +
            "<if test='status != null'> AND status = #{status} </if>" +
            "</script>")
    Long countByStatus(@Param("tenantId") Long tenantId, @Param("status") Integer status);

    @Update("UPDATE goods SET status = #{status}, updated_at = NOW() " +
            "WHERE id = #{id} AND tenant_id = #{tenantId}")
    int updateStatus(@Param("id") Long id, @Param("tenantId") Long tenantId, @Param("status") Integer status);

    @Update("UPDATE goods SET status = 1, updated_at = NOW() WHERE id = #{id} AND tenant_id = #{tenantId}")
    int putOnSale(@Param("id") Long id, @Param("tenantId") Long tenantId);

    @Update("UPDATE goods SET status = 0, updated_at = NOW() WHERE id = #{id} AND tenant_id = #{tenantId}")
    int putOffSale(@Param("id") Long id, @Param("tenantId") Long tenantId);
}
