<?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.ruoyi.clock.mapper.ClockRecordMapper">

    <resultMap type="com.ruoyi.clock.domain.ClockRecord" id="ClockRecordResult">
        <result property="recordId" column="record_id"/>
        <result property="activityId" column="activity_id"/>
        <result property="employeeId" column="employee_id"/>
        <result property="clockDate" column="clock_date"/>
        <result property="screenshot" column="screenshot"/>
        <result property="status" column="status"/>
        <result property="createBy" column="create_by"/>
        <result property="createTime" column="create_time"/>
        <result property="updateBy" column="update_by"/>
        <result property="updateTime" column="update_time"/>
    </resultMap>

    <select id="queryClockStatisticRecord" resultType="com.ruoyi.clock.domain.vo.ClockStatisticRecordVo">
        select
            (
                SELECT
                    COUNT(record_id)
                FROM
                    tb_clock_record
                WHERE
                    employee_id = #{employeeId}
                  AND DATE_FORMAT(clock_date, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')
                  and status = 0) AS clockCountCurrentMonth,
            (
                SELECT
                    IFNULL(SUM(p.amount), 0)
                FROM
                    tb_clock_record r
                left join tb_clock_product_record p  on r.record_id = p.record_id
                WHERE
                r.employee_id = #{employeeId}
                AND DATE_FORMAT(r.clock_date, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')
                and r.status = 0
            )AS saleCountCurrentMonth,
            (
                select s.shop_name from tb_employee e
                left join tb_shop s on e.shop_id = s.shop_id
                where e.employee_id = #{employeeId}
            ) AS shopName
    </select>

    <select id="querySaleStatisticRecordList" resultType="com.ruoyi.clock.domain.vo.SaleStatisticRecordVo">
        SELECT
            RANK() OVER (ORDER BY IFNULL(SUM(p.amount), 0) DESC, COUNT(DISTINCT r.record_id) DESC) AS `rank`,
            r.employee_id AS employeeId,
            e.employee_name AS employeeName,
            e.avatar AS avatar,
            s.shop_name AS shopName,
            IFNULL(SUM(p.amount), 0) AS saleCount
        FROM
            tb_clock_record r
        LEFT JOIN tb_clock_product_record p ON r.record_id = p.record_id
        LEFT JOIN tb_activity act ON r.activity_id = act.activity_id
        LEFT JOIN tb_employee e ON r.employee_id = e.employee_id
        LEFT JOIN tb_shop s ON e.shop_id = s.shop_id
        WHERE
           r.status = 0 and act.type = 1
          <if test="bo.activityId != null">
            AND r.activity_id = #{bo.activityId}
          </if>
         <if test="bo.agentId != null">
              AND r.activity_id in (select activity_id from tb_activity_agent where agent_id = #{bo.agentId})
          </if>
        <if test="bo.employeeName != null and bo.employeeName != ''">
            AND e.employee_name LIKE CONCAT('%', #{bo.employeeName}, '%')
        </if>
        GROUP BY
            r.employee_id
        ORDER BY
            saleCount DESC
    </select>


    <select id="mySaleRank" resultType="com.ruoyi.clock.domain.vo.MySaleStatisticRecordVo">
        SELECT
            (SELECT COUNT(DISTINCT t.employee_id)
             FROM (
                      SELECT
                      r2.employee_id,
                      IFNULL(SUM(p2.amount), 0) AS total_sale
                      from tb_clock_record r2
                      LEFT JOIN tb_activity act2 ON r2.activity_id = act2.activity_id
                      LEFT JOIN tb_clock_product_record p2 ON r2.record_id = p2.record_id
                      WHERE r2.status = 0
                    <if test="bo.activityId != null">
                        AND  aa2.activity_id = #{bo.activityId}
                    </if>
                    <if test="bo.agentId != null">
                        AND r2.activity_id in (select activity_id from tb_activity_agent where agent_id = #{bo.agentId})
                    </if>
                    AND act2.status = 0
                    AND act2.del_flag = '0'
                    GROUP BY r2.employee_id
                  ) t
             WHERE t.total_sale > (
                 SELECT IFNULL(SUM(p.amount), 0)
                 FROM tb_clock_record r
                  LEFT JOIN tb_activity act ON r.activity_id = act.activity_id
                    LEFT JOIN tb_clock_product_record p ON r.record_id = p.record_id
                 WHERE
                    <if test="bo.activityId != null">
                        AND  r.activity_id = #{bo.activityId}
                    </if>
                    <if test="bo.agentId != null">
                        AND r.activity_id in (select activity_id from tb_activity_agent where agent_id = #{bo.agentId})
                    </if>
                    AND r.status = 0
                    AND r.employee_id = #{bo.employeeId}
                   AND act.status = 0
                   AND act.del_flag = '0'
                 GROUP BY r.employee_id
             )) + 1 AS `rank`,
            IFNULL(SUM(p.amount), 0) AS saleCount
        FROM
        tb_clock_record r
        LEFT JOIN tb_activity act ON r.activity_id = act.activity_id
        LEFT JOIN tb_clock_product_record p ON r.record_id = p.record_id
        WHERE
             r.status = 0
            AND r.employee_id = #{bo.employeeId}
        <if test="bo.activityId != null">
            AND  r.activity_id = #{bo.activityId}
        </if>
        <if test="bo.agentId != null">
            AND r.activity_id in (select activity_id from tb_activity_agent where agent_id = #{bo.agentId})
        </if>
        AND act.status = 0
        AND act.del_flag = '0'
        GROUP BY
            r.employee_id
    </select>

    <select id="myActivityStatistic" resultType="com.ruoyi.clock.domain.vo.MyActivityStatisticVo">
        SELECT
            (
                SELECT
                    COUNT(record_id)
                FROM
                    tb_clock_record
                WHERE
                    employee_id =#{employeeId}
                  AND status = 0
                  AND activity_id =#{activityId}
            ) as clockCount,
               (
                SELECT
                    IFNULL(SUM(p.amount), 0)
                FROM
                    tb_clock_record r
                LEFT JOIN tb_clock_product_record p ON r.record_id = p.record_id
                WHERE
                    r.employee_id =#{employeeId}
                  AND r.status = 0
                  AND r.activity_id =#{activityId}
            ) AS saleCount
    </select>

    <!-- 活动打卡记录公共查询条件 -->
    <sql id="activityClockRecordWhere">
        r.activity_id = #{bo.activityId}
        <if test="bo.employeeName != null and bo.employeeName != ''">
            AND e.employee_name LIKE CONCAT('%', #{bo.employeeName}, '%')
        </if>
        <if test="bo.agentId != null">
            AND e.agent_id = #{bo.agentId}
        </if>
        <if test="bo.shopId != null">
            AND e.shop_id = #{bo.shopId}
        </if>
        <if test="bo.status != null">
            AND r.status = #{bo.status}
        </if>
    </sql>

    <!-- 分页查询活动打卡记录列表 -->
    <select id="queryActivityClockRecordPage" resultType="com.ruoyi.clock.domain.vo.ActivityClockRecordVo">
        SELECT
            r.record_id        AS recordId,
            r.employee_id      AS employeeId,
            e.employee_name    AS employeeName,
            ag.agent_name      AS agentName,
            s.shop_name        AS shopName,
            r.clock_date       AS clockDate,
            IFNULL(SUM(p.amount), 0) AS saleCount,
            r.screenshot       AS screenshot,
            r.status           AS status
        FROM tb_clock_record r
        LEFT JOIN tb_employee e   ON r.employee_id = e.employee_id
        LEFT JOIN tb_agent ag     ON e.agent_id = ag.agent_id
        LEFT JOIN tb_shop s       ON e.shop_id = s.shop_id
        LEFT JOIN tb_clock_product_record p ON r.record_id = p.record_id
        WHERE
            <include refid="activityClockRecordWhere"/>
        GROUP BY r.record_id
        ORDER BY r.clock_date DESC
    </select>

    <!-- 查询活动打卡统计（打卡人数 + 销售数量合计） -->
    <select id="queryActivityClockStatistic" resultType="com.ruoyi.clock.domain.vo.ActivityClockStatisticVo">
        SELECT
            COUNT(DISTINCT r.employee_id) AS clockEmployeeCount,
            IFNULL(SUM(p.amount), 0)      AS totalSaleCount
        FROM tb_clock_record r
        LEFT JOIN tb_employee e   ON r.employee_id = e.employee_id
        LEFT JOIN tb_clock_product_record p ON r.record_id = p.record_id
        WHERE
            <include refid="activityClockRecordWhere"/>
    </select>

    <!-- 分页查询活动店铺销量列表（销量活动 type=1） -->
    <select id="queryActivityShopSalePage" resultType="com.ruoyi.clock.domain.vo.ActivityShopSaleVo">
        SELECT
            act.activity_name AS activityName,
            ag.agent_name     AS agentName,
            ap.product_name   AS productName,
            s.shop_name       AS shopName,
            IFNULL(SUM(p.amount), 0) AS saleCount
        FROM tb_clock_record r
        INNER JOIN tb_activity act ON r.activity_id = act.activity_id AND act.type = 1
        LEFT JOIN tb_employee e    ON r.employee_id = e.employee_id
        LEFT JOIN tb_agent ag      ON e.agent_id = ag.agent_id
        LEFT JOIN tb_shop s        ON e.shop_id = s.shop_id
        LEFT JOIN tb_clock_product_record p ON r.record_id = p.record_id
        LEFT JOIN tb_activity_product ap ON r.activity_id = ap.activity_id
        WHERE r.activity_id = #{bo.activityId}
          AND r.status = 0
        <if test="bo.agentName != null and bo.agentName != ''">
            AND ag.agent_name LIKE CONCAT('%', #{bo.agentName}, '%')
        </if>
        <if test="bo.shopName != null and bo.shopName != ''">
            AND s.shop_name LIKE CONCAT('%', #{bo.shopName}, '%')
        </if>
        GROUP BY act.activity_id, ag.agent_id, ap.id, s.shop_id
        ORDER BY saleCount DESC
    </select>

    <!-- 查询仪表板统计数据 -->
    <select id="queryDashboardStatistic" resultType="com.ruoyi.clock.domain.vo.DashboardStatisticVo">
        SELECT
            (SELECT COUNT(*) FROM tb_activity WHERE del_flag = '0') AS totalActivityCount,
            (SELECT COUNT(*) FROM tb_activity WHERE del_flag = '0' AND status = 0 AND CURDATE() BETWEEN start_date AND end_date) AS ongoingActivityCount,
            (SELECT COUNT(DISTINCT employee_id) FROM tb_clock_record WHERE status = 0 AND DATE(clock_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)) AS yesterdayClockCount,
            (SELECT COUNT(DISTINCT employee_id) FROM tb_clock_record WHERE status = 0 AND DATE(clock_date) = CURDATE()) AS todayClockCount
    </select>

    <!-- 查询昨日代理商活动参与人数排行 -->
    <select id="queryYesterdayAgentRank" resultType="com.ruoyi.clock.domain.vo.AgentRankVo">
        SELECT
            ag.agent_name AS agentName,
            COUNT(DISTINCT r.employee_id) AS participantCount
        FROM tb_clock_record r
        LEFT JOIN tb_employee e ON r.employee_id = e.employee_id
        LEFT JOIN tb_agent ag ON e.agent_id = ag.agent_id
        WHERE r.status = 0
          AND DATE(r.clock_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)
        GROUP BY ag.agent_id, ag.agent_name
        ORDER BY participantCount DESC
        LIMIT 10
    </select>

    <!-- 查询昨日门店活动参与人数排行 -->
    <select id="queryYesterdayShopRank" resultType="com.ruoyi.clock.domain.vo.ShopRankVo">
        SELECT
            s.shop_name AS shopName,
            COUNT(DISTINCT r.employee_id) AS participantCount
        FROM tb_clock_record r
        LEFT JOIN tb_employee e ON r.employee_id = e.employee_id
        LEFT JOIN tb_shop s ON e.shop_id = s.shop_id
        WHERE r.status = 0
          AND DATE(r.clock_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)
        GROUP BY s.shop_id, s.shop_name
        ORDER BY participantCount DESC
        LIMIT 10
    </select>

    <!-- 查询统计分析概览数据 -->
    <select id="queryAnalysisOverview" resultType="com.ruoyi.clock.domain.vo.AnalysisOverviewVo">
        SELECT
            (SELECT COUNT(DISTINCT employee_id) FROM tb_clock_record WHERE status = 0) AS totalParticipantCount,
            (SELECT COUNT(*) FROM tb_shop WHERE del_flag = '0') AS shopCount,
            (SELECT COUNT(*) FROM tb_agent WHERE del_flag = '0') AS agentCount,
            (SELECT COUNT(*) FROM tb_clock_record WHERE status = 0) AS clockCount,
            (SELECT IFNULL(SUM(amount), 0) FROM tb_clock_product_record p
             INNER JOIN tb_clock_record r ON p.record_id = r.record_id WHERE r.status = 0) AS productSales
    </select>

    <!-- 查询门店活跃度排行 -->
    <select id="queryShopActivityRank" resultType="com.ruoyi.clock.domain.vo.ShopActivityRankVo">
        SELECT
            s.shop_name AS shopName,
            COUNT(r.record_id) AS clockCount
        FROM tb_clock_record r
        LEFT JOIN tb_employee e ON r.employee_id = e.employee_id
        LEFT JOIN tb_shop s ON e.shop_id = s.shop_id
        WHERE r.status = 0
        <if test="bo.activityId != null">
            AND r.activity_id = #{bo.activityId}
        </if>
        GROUP BY s.shop_id, s.shop_name
        ORDER BY clockCount DESC
        LIMIT 10
    </select>

    <!-- 查询参与人数与销量趋势（最近30天） -->
    <select id="queryTrend" resultType="com.ruoyi.clock.domain.vo.TrendVo">
        SELECT
            DATE_FORMAT(r.clock_date, '%m-%d') AS date,
            COUNT(DISTINCT r.employee_id) AS participantCount,
            IFNULL(SUM(p.amount), 0) AS salesCount
        FROM tb_clock_record r
        LEFT JOIN tb_clock_product_record p ON r.record_id = p.record_id
        WHERE r.status = 0
          AND r.clock_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
        <if test="bo.activityId != null">
            AND r.activity_id = #{bo.activityId}
        </if>
        GROUP BY DATE(r.clock_date)
        ORDER BY DATE(r.clock_date)
    </select>

    <!-- 查询月度参与人数与销量对比（最近6个月） -->
    <select id="queryMonthlyComparison" resultType="com.ruoyi.clock.domain.vo.MonthlyComparisonVo">
        SELECT
            CONCAT(DATE_FORMAT(r.clock_date, '%c'), '月') AS month,
            COUNT(DISTINCT r.employee_id) AS participantCount,
            IFNULL(SUM(p.amount), 0) AS salesCount
        FROM tb_clock_record r
        LEFT JOIN tb_clock_product_record p ON r.record_id = p.record_id
        WHERE r.status = 0
          AND r.clock_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
        <if test="bo.activityId != null">
            AND r.activity_id = #{bo.activityId}
        </if>
        GROUP BY DATE_FORMAT(r.clock_date, '%Y-%m')
        ORDER BY DATE_FORMAT(r.clock_date, '%Y-%m')
    </select>

    <!-- 查询门店销量排行榜 TOP 6 -->
    <select id="queryShopSalesRank" resultType="com.ruoyi.clock.domain.vo.ShopSalesRankVo">
        SELECT
            s.shop_name AS shopName,
            COUNT(r.record_id) AS clockCount,
            IFNULL(SUM(p.amount), 0) AS salesCount
        FROM tb_clock_record r
        LEFT JOIN tb_employee e ON r.employee_id = e.employee_id
        LEFT JOIN tb_shop s ON e.shop_id = s.shop_id
        LEFT JOIN tb_clock_product_record p ON r.record_id = p.record_id
        WHERE r.status = 0
        GROUP BY s.shop_id, s.shop_name
        ORDER BY salesCount DESC
        LIMIT 6
    </select>

</mapper>
