<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~
  ~      Copyright (c) 2018-2025, lengleng All rights reserved.
  ~
  ~  Redistribution and use in source and binary forms, with or without
  ~  modification, are permitted provided that the following conditions are met:
  ~
  ~ Redistributions of source code must retain the above copyright notice,
  ~  this list of conditions and the following disclaimer.
  ~  Redistributions in binary form must reproduce the above copyright
  ~  notice, this list of conditions and the following disclaimer in the
  ~  documentation and/or other materials provided with the distribution.
  ~  Neither the name of the pig4cloud.com developer nor the names of its
  ~  contributors may be used to endorse or promote products derived from
  ~  this software without specific prior written permission.
  ~  Author: lengleng (wangiegie@gmail.com)
  ~
  -->

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pig4cloud.pig.marketing.mapper.MarketingDataMapper">

	<select id="countFirstLevelMarketingData" resultType="com.pig4cloud.pig.marketing.api.vo.data.PageFirstLevelDataVO">
        SELECT
        ip,
        COUNT(*) AS total,
        SUM(CASE WHEN create_time >= #{lastHourTime} THEN 1 ELSE 0 END) AS hourly,
        SUM(CASE WHEN create_time >= #{todayStartTime} THEN 1 ELSE 0 END) AS daily
        FROM
        mkt_mgmt_data
        <where>
            <if test="ip != null and ip != ''">
                AND ip LIKE CONCAT('%', #{ip}, '%')
            </if>
			<if test="appId != null and appId != ''">
				AND app_id LIKE CONCAT('%', #{appId}, '%')
			</if>
        </where>
        GROUP BY ip
        LIMIT #{offset}, #{pageSize}
    </select>

	<select id="countFirstLevelDataTotal" resultType="java.lang.Long">
		SELECT
		COUNT(DISTINCT ip)
		FROM
		mkt_mgmt_data
		<where>
			<if test="ip != null and ip != ''">
				AND ip LIKE CONCAT('%', #{ip}, '%')
			</if>
			<if test="appId != null and appId != ''">
				AND app_id LIKE CONCAT('%', #{appId}, '%')
			</if>
		</where>
	</select>

	<select id="countSecondLevelMarketingData"
			resultType="com.pig4cloud.pig.marketing.api.vo.data.PageSecondLevelDataVO">
        SELECT
            domain, referrer, fingerprint, COUNT(*) AS total, SUM(CASE WHEN create_time >= #{lastHourTime} THEN 1 ELSE 0 END) AS hourly, SUM(CASE WHEN create_time >=
                                                                                             #{todayStartTime} THEN 1 ELSE 0 END) AS daily
        FROM
            mkt_mgmt_data
        WHERE
            ip = #{ip}
        GROUP BY
            domain, referrer, fingerprint
            LIMIT #{offset}, #{pageSize}
    </select>

	<select id="countSecondLevelDataTotal" resultType="java.lang.Long">
		SELECT COUNT(DISTINCT domain, referrer, fingerprint)
		FROM mkt_mgmt_data
		WHERE ip = #{ip}
	</select>
</mapper>
