package com.erp.tenant.repository.customer;

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.customer.Customer;
import org.apache.ibatis.annotations.*;

/**
 * 客户数据访问
 */
@Mapper
public interface CustomerRepository extends BaseMapper<Customer> {

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

    @Select("<script>" +
            "SELECT c.* FROM customers c " +
            "WHERE c.tenant_id = #{tenantId} AND c.deleted_at IS NULL " +
            "<if test='keyword != null'> 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 c.level = #{level} </if>" +
            "<if test='status != null'> AND c.status = #{status} </if>" +
            "ORDER BY c.updated_at DESC" +
            "</script>")
    IPage<Customer> findPage(Page<Customer> page,
                              @Param("tenantId") Long tenantId,
                              @Param("keyword") String keyword,
                              @Param("level") String level,
                              @Param("status") Integer status);

    @Update("UPDATE customers 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);

    @Select("<script>" +
            "SELECT COUNT(*) FROM customers 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);
}
