package com.haha.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haha.entity.Replenisher;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 补货员Mapper
 */
@Mapper
public interface ReplenisherMapper extends BaseMapper<Replenisher> {

    /**
     * 关键词搜索补货员
     */
    @Select("<script>" +
            "SELECT * FROM t_replenisher " +
            "<where>" +
            "  <if test='keyword != null and keyword != \"\"'>" +
            "    AND (name LIKE CONCAT('%', #{keyword}, '%') " +
            "         OR phone LIKE CONCAT('%', #{keyword}, '%') " +
            "         OR employee_id LIKE CONCAT('%', #{keyword}, '%'))" +
            "  </if>" +
            "  AND status = 1" +
            "</where>" +
            "ORDER BY create_time DESC" +
            "</script>")
    List<Replenisher> searchByKeyword(@Param("keyword") String keyword);

    /**
     * 统计补货员的绑定设备数
     */
    @Select("SELECT COUNT(*) FROM t_replenisher_device WHERE replenisher_id = #{replenisherId}")
    int countBoundDevices(@Param("replenisherId") Long replenisherId);

    /**
     * 分页查询补货员列表（带设备绑定数量和搜索条件）
     */
    IPage<Replenisher> selectWithDeviceCount(Page<Replenisher> page,
                                              @Param("keyword") String keyword,
                                              @Param("status") Integer status);

    /**
     * 通过门店ID查询补货员列表（通过设备关联反向推导）
     */
    @Select("SELECT DISTINCT r.* FROM t_replenisher r " +
            "INNER JOIN t_replenisher_device rd ON r.id = rd.replenisher_id " +
            "INNER JOIN t_device d ON rd.device_id = d.device_id " +
            "WHERE d.shop_id = #{shopId} " +
            "ORDER BY r.create_time DESC")
    List<Replenisher> selectByShopId(@Param("shopId") Long shopId);

    /**
     * 通过设备ID查询绑定的补货员列表
     */
    @Select("SELECT r.* FROM t_replenisher r " +
            "INNER JOIN t_replenisher_device rd ON r.id = rd.replenisher_id " +
            "WHERE rd.device_id = #{deviceId} " +
            "ORDER BY r.create_time DESC")
    List<Replenisher> selectByDeviceId(@Param("deviceId") String deviceId);
}
