<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.erp.tenant.repository.goods.GoodsRepository">

    <!-- 商品分页查询 -->
    <select id="findPage" resultType="com.erp.tenant.entity.goods.Goods">
        SELECT g.* FROM goods g
        WHERE g.tenant_id = #{tenantId} AND g.deleted_at IS NULL
        <if test="keyword != null and keyword != ''">
            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
    </select>

    <!-- 统计商品数量（按状态） -->
    <select id="countByStatus" resultType="java.lang.Long">
        SELECT COUNT(*) FROM goods 
        WHERE tenant_id = #{tenantId} AND deleted_at IS NULL
        <if test="status != null">
            AND status = #{status}
        </if>
    </select>

    <!-- 上架商品 -->
    <update id="putOnSale">
        UPDATE goods SET status = 1, updated_at = NOW() 
        WHERE id = #{id} AND tenant_id = #{tenantId}
    </update>

    <!-- 下架商品 -->
    <update id="putOffSale">
        UPDATE goods SET status = 0, updated_at = NOW() 
        WHERE id = #{id} AND tenant_id = #{tenantId}
    </update>

</mapper>
