<?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.customer.CustomerRepository">

    <!-- 客户分页查询 -->
    <select id="findPage" resultType="com.erp.tenant.entity.customer.Customer">
        SELECT c.* FROM customers c
        WHERE c.tenant_id = #{tenantId} AND c.deleted_at IS NULL
        <if test="keyword != null and keyword != ''">
            AND (c.name LIKE CONCAT('%', #{keyword}, '%') 
                 OR c.customer_code LIKE CONCAT('%', #{keyword}, '%') 
                 OR c.phone LIKE CONCAT('%', #{keyword}, '%'))
        </if>
        <if test="level != null and level != ''">
            AND c.level = #{level}
        </if>
        <if test="status != null">
            AND c.status = #{status}
        </if>
        ORDER BY c.updated_at DESC
    </select>

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

    <!-- 更新客户状态 -->
    <update id="updateStatus">
        UPDATE customers SET status = #{status}, updated_at = NOW() 
        WHERE id = #{id} AND tenant_id = #{tenantId}
    </update>

</mapper>
