package com.common.mapper;

import com.common.entity.DeviceInterlockingLog;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface DeviceInterlockingLogMapper {

    /**
     * 根据ID查询
     */
    @Select("SELECT * FROM device_interlocking_log WHERE id = #{id}")
    DeviceInterlockingLog selectById(Long id);

    /**
     * 根据指令ID查询
     */
    @Select("SELECT * FROM device_interlocking_log WHERE device_interlocking_cmd_id = #{cmdId}")
    List<DeviceInterlockingLog> selectByCmdId(@Param("cmdId") Long cmdId);

    /**
     * 插入记录
     */
    @Insert("INSERT INTO device_interlocking_log (device_interlocking_cmd_id, device_interlocking_id, ban_ip, " +
            "device_name, ban_time, ban_method, ban_result, tenant_id, create_dept, create_by, " +
            "create_time, remark, resp_body, req_body) " +
            "VALUES (#{deviceInterlockingCmdId}, #{deviceInterlockingId}, #{banIp}, #{deviceName}, " +
            "#{banTime}, #{banMethod}, #{banResult}, #{tenantId}, #{createDept}, #{createBy}, " +
            "NOW(), #{remark}, #{respBody}, #{reqBody})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(DeviceInterlockingLog log);

    /**
     * 批量插入记录
     */
    @Insert("<script>" +
            "INSERT INTO device_interlocking_log (device_interlocking_cmd_id, device_interlocking_id, ban_ip, " +
            "device_name, ban_time, ban_method, ban_result, tenant_id, create_dept, create_by, " +
            "create_time, remark, resp_body, req_body) VALUES " +
            "<foreach collection='logs' item='item' separator=','>" +
            "(#{item.deviceInterlockingCmdId}, #{item.deviceInterlockingId}, #{item.banIp}, " +
            "#{item.deviceName}, #{item.banTime}, #{item.banMethod}, #{item.banResult}, " +
            "#{item.tenantId}, #{item.createDept}, #{item.createBy}, NOW(), " +
            "#{item.remark}, #{item.respBody}, #{item.reqBody})" +
            "</foreach>" +
            "</script>")
    int batchInsert(@Param("logs") List<DeviceInterlockingLog> logs);

    /**
     * 查询所有记录
     */
    @Select("SELECT * FROM device_interlocking_log ORDER BY create_time DESC")
    List<DeviceInterlockingLog> selectAll();

    /**
     * 统计某指令的成功/失败数量
     */
    @Select("SELECT ban_result, COUNT(*) as count FROM device_interlocking_log " +
            "WHERE device_interlocking_cmd_id = #{cmdId} GROUP BY ban_result")
    List<java.util.Map<String, Object>> countByCmdId(@Param("cmdId") Long cmdId);
}
