<?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.web.modules.trading.mapper.AppDistributorTradeMapper">

    <sql id="orderInRange">
        o.distributor_id = #{distributorId}
        and o.del_flag = '0'
        and o.create_time &gt;= #{rangeStart}
        and o.create_time &lt;= #{rangeEnd}
    </sql>

    <select id="selectTradeSummary"
            resultType="com.ruoyi.web.modules.trading.domain.dto.AppDistributorTradeSummaryDto">
        select count(*) as orderCount,
               coalesce(sum(case when o.order_status = '1' then 1 else 0 end), 0) as completedCount,
               coalesce(sum(o.total_amount), 0) as totalAmount,
               coalesce(sum(o.total_heads), 0) as totalHeads,
               count(distinct case when o.order_status = '1' then o.supplier_id else null end) as supplierCount
        from biz_trade_order o
        where <include refid="orderInRange"/>
    </select>

    <select id="selectHourlyAmountTrend"
            resultType="com.ruoyi.web.modules.trading.domain.dto.AppDistributorAmountBucketDto">
        select cast(hour(o.create_time) as char) as bucketKey,
               coalesce(sum(o.total_amount), 0) as amount
        from biz_trade_order o
        where <include refid="orderInRange"/>
        group by hour(o.create_time)
    </select>

    <select id="selectDailyAmountTrend"
            resultType="com.ruoyi.web.modules.trading.domain.dto.AppDistributorAmountBucketDto">
        select date_format(o.create_time, '%Y-%m-%d') as bucketKey,
               coalesce(sum(o.total_amount), 0) as amount
        from biz_trade_order o
        where <include refid="orderInRange"/>
        group by date_format(o.create_time, '%Y-%m-%d')
    </select>

</mapper>
