<?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="com.hotwj.platform.workbench.mapper.HotHiddenDangerDailyStatsMapper">

    <select id="selectStatsByDateRange" resultType="com.hotwj.platform.workbench.domain.entity.HotHiddenDangerDailyStats">
        SELECT stats_date,
               SUM(enterprise_risk) as enterprise_risk,
               SUM(vehicle_risk) as vehicle_risk,
               SUM(personnel_risk) as personnel_risk,
               SUM(total_risk) as total_risk
        FROM hot_hidden_danger_daily_stats
        WHERE region_code LIKE CONCAT(#{regionCode}, '%')
          AND stats_date BETWEEN #{startDate} AND #{endDate}
        GROUP BY stats_date
        ORDER BY stats_date ASC
    </select>

    <select id="selectStatsByCompanyAndDateRange" resultType="com.hotwj.platform.workbench.domain.entity.HotHiddenDangerDailyStats">
        SELECT stats_date,
               enterprise_risk,
               vehicle_risk,
               personnel_risk,
               total_risk
        FROM hot_hidden_danger_daily_stats
        WHERE company_id = #{companyId}
          AND stats_date BETWEEN #{startDate} AND #{endDate}
        ORDER BY stats_date ASC
    </select>

    <select id="selectTopRiskCompanies" resultType="com.hotwj.platform.workbench.domain.vo.GovCompanyRiskStatsVo">
        SELECT t.company_id, c.company_name, t.total_risk, t.enterprise_risk, t.vehicle_risk, t.personnel_risk
        FROM hot_hidden_danger_daily_stats t
                 INNER JOIN sys_company c ON t.company_id = c.id
        WHERE t.stats_date = #{statsDate}
          AND c.region_code LIKE CONCAT(#{districtCode}, '%')
          AND c.is_deleted = 0
        ORDER BY t.total_risk DESC, t.company_id ASC
            LIMIT #{limit}
    </select>

    <select id="selectCompanyRiskPage" resultType="com.hotwj.platform.workbench.domain.vo.GovCompanyRiskStatsVo">
        SELECT t.company_id, c.company_name, t.total_risk, t.enterprise_risk, t.vehicle_risk, t.personnel_risk
        FROM hot_hidden_danger_daily_stats t
        INNER JOIN sys_company c ON t.company_id = c.id
        WHERE t.stats_date = #{statsDate}
        AND c.region_code LIKE CONCAT(#{districtCode}, '%')
        AND c.is_deleted = 0
        <if test="companyName != null and companyName != ''">
            AND c.company_name LIKE CONCAT('%', #{companyName}, '%')
        </if>
        ORDER BY t.total_risk DESC, t.company_id ASC
    </select>

</mapper>
