package com.erp.customer.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.customer.entity.CustomerAddress;
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 CustomerAddressRepository extends BaseMapper<CustomerAddress> {
    
    /**
     * 根据客户ID查询所有地址
     */
    @Select("SELECT * FROM customer_addresses WHERE customer_id = #{customerId} AND deleted_at IS NULL " +
            "ORDER BY is_default DESC, created_at DESC")
    List<CustomerAddress> findByCustomerId(@Param("customerId") Long customerId);
    
    /**
     * 根据客户ID查询默认地址
     */
    @Select("SELECT * FROM customer_addresses WHERE customer_id = #{customerId} AND is_default = true AND deleted_at IS NULL " +
            "ORDER BY created_at DESC LIMIT 1")
    CustomerAddress findDefaultByCustomerId(@Param("customerId") Long customerId);
    
    /**
     * 根据客户ID查询发货地址
     */
    @Select("SELECT * FROM customer_addresses WHERE customer_id = #{customerId} AND address_type = 'DELIVERY' " +
            "AND deleted_at IS NULL ORDER BY is_default DESC, created_at DESC")
    List<CustomerAddress> findDeliveryAddresses(@Param("customerId") Long customerId);
    
    /**
     * 根据地址类型查询
     */
    @Select("SELECT * FROM customer_addresses WHERE customer_id = #{customerId} AND address_type = #{addressType} " +
            "AND deleted_at IS NULL ORDER BY is_default DESC, created_at DESC")
    List<CustomerAddress> findByCustomerIdAndAddressType(@Param("customerId") Long customerId, 
                                                         @Param("addressType") String addressType);
    
    /**
     * 统计客户地址数量
     */
    @Select("SELECT COUNT(*) FROM customer_addresses WHERE customer_id = #{customerId} AND deleted_at IS NULL")
    Long countByCustomerId(@Param("customerId") Long customerId);
    
    /**
     * 根据省市区查询客户地址
     */
    @Select("SELECT * FROM customer_addresses WHERE customer_id = #{customerId} " +
            "AND province = #{province} AND city = #{city} AND district = #{district} " +
            "AND deleted_at IS NULL ORDER BY is_default DESC, created_at DESC")
    List<CustomerAddress> findByProvinceCityDistrict(@Param("customerId") Long customerId,
                                                      @Param("province") String province,
                                                      @Param("city") String city,
                                                      @Param("district") String district);
    
    /**
     * 查询有坐标的地址
     */
    @Select("SELECT * FROM customer_addresses WHERE customer_id = #{customerId} AND longitude IS NOT NULL " +
            "AND latitude IS NOT NULL AND deleted_at IS NULL ORDER BY is_default DESC, created_at DESC")
    List<CustomerAddress> findWithCoordinates(@Param("customerId") Long customerId);
}
