package com.erp.customer.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.customer.entity.CustomerContact;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 客户联系人数据访问接口
 */
@Mapper
public interface CustomerContactRepository extends BaseMapper<CustomerContact> {
    
    /**
     * 根据客户ID查询所有联系人
     */
    @Select("SELECT * FROM customer_contacts WHERE customer_id = #{customerId} AND deleted_at IS NULL " +
            "ORDER BY is_primary DESC, created_at DESC")
    List<CustomerContact> findByCustomerId(@Param("customerId") Long customerId);
    
    /**
     * 根据客户ID查询主要联系人
     */
    @Select("SELECT * FROM customer_contacts WHERE customer_id = #{customerId} AND is_primary = true AND deleted_at IS NULL " +
            "ORDER BY created_at DESC LIMIT 1")
    CustomerContact findPrimaryByCustomerId(@Param("customerId") Long customerId);
    
    /**
     * 根据手机号查询
     */
    @Select("SELECT * FROM customer_contacts WHERE mobile = #{mobile} AND deleted_at IS NULL LIMIT 1")
    CustomerContact findByMobile(@Param("mobile") String mobile);
    
    /**
     * 根据邮箱查询
     */
    @Select("SELECT * FROM customer_contacts WHERE email = #{email} AND deleted_at IS NULL LIMIT 1")
    CustomerContact findByEmail(@Param("email") String email);
    
    /**
     * 根据联系人类型查询
     */
    @Select("SELECT * FROM customer_contacts WHERE customer_id = #{customerId} AND contact_type = #{contactType} " +
            "AND deleted_at IS NULL ORDER BY created_at DESC")
    List<CustomerContact> findByCustomerIdAndContactType(@Param("customerId") Long customerId, 
                                                           @Param("contactType") String contactType);
    
    /**
     * 统计客户联系人数量
     */
    @Select("SELECT COUNT(*) FROM customer_contacts WHERE customer_id = #{customerId} AND deleted_at IS NULL")
    Long countByCustomerId(@Param("customerId") Long customerId);
    
    /**
     * 查询有决策影响力的联系人
     */
    @Select("SELECT * FROM customer_contacts WHERE customer_id = #{customerId} AND influence_level = 'HIGH' " +
            "AND deleted_at IS NULL ORDER BY created_at DESC")
    List<CustomerContact> findHighInfluenceByCustomerId(@Param("customerId") Long customerId);
    
    /**
     * 根据姓名模糊搜索
     */
    @Select("SELECT * FROM customer_contacts WHERE customer_id = #{customerId} AND contact_name LIKE CONCAT('%', #{keyword}, '%') " +
            "AND deleted_at IS NULL ORDER BY created_at DESC")
    List<CustomerContact> searchByContactName(@Param("customerId") Long customerId, @Param("keyword") String keyword);
}
