<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.hzhub.erp.mapper.ErpApiStatsMapper">

    <resultMap id="ErpApiStatsResult" type="org.hzhub.erp.domain.entity.ErpApiStats">
        <id property="statsId" column="stats_id"/>
        <result property="apiId" column="api_id"/>
        <result property="callTime" column="call_time"/>
        <result property="callParams" column="call_params"/>
        <result property="responseTime" column="response_time"/>
        <result property="callStatus" column="call_status"/>
        <result property="errorMessage" column="error_message"/>
        <result property="errorStack" column="error_stack"/>
        <result property="clientIp" column="client_ip"/>
        <result property="userId" column="user_id"/>
        <result property="createTime" column="create_time"/>
    </resultMap>

    <sql id="selectErpApiStatsVo">
        select stats_id, api_id, call_time, call_params, response_time, call_status,
               error_message, error_stack, client_ip, user_id, create_time
        from erp_api_stats
    </sql>

    <select id="selectByApiIdAndTime" resultMap="ErpApiStatsResult">
        <include refid="selectErpApiStatsVo"/>
        where api_id = #{apiId}
        and call_time between #{startTime} and #{endTime}
        order by call_time desc
    </select>

    <select id="selectErrorLogByApiId" resultMap="ErpApiStatsResult">
        <include refid="selectErpApiStatsVo"/>
        where api_id = #{apiId}
        and call_status = 'ERROR'
        order by call_time desc
        limit #{limit}
    </select>

    <select id="countByApiId" resultType="Long">
        select count(*)
        from erp_api_stats
        where api_id = #{apiId}
        and call_time between #{startTime} and #{endTime}
    </select>

    <select id="avgResponseTimeByApiId" resultType="Integer">
        select avg(response_time)
        from erp_api_stats
        where api_id = #{apiId}
        and call_time between #{startTime} and #{endTime}
        and call_status = 'SUCCESS'
    </select>

    <select id="countErrorByApiId" resultType="Long">
        select count(*)
        from erp_api_stats
        where api_id = #{apiId}
        and call_time between #{startTime} and #{endTime}
        and call_status = 'ERROR'
    </select>

</mapper>