<?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.sqx.modules.reconciliation.mapper.PlatformBillMapper">

    <select id="riderBill" resultType="com.sqx.modules.reconciliation.model.RiderBillVo">
        select pb.*,tu.user_name as userName,tu.phone ,rs.station_name as stationName
        from platform_bill pb left join tb_user tu on pb.user_id =tu.user_id
        left join rider_station rs on rs.id =tu.rider_station_id
        <where>
            pb.`type` =2
            <if test="params.startDate != null and params.startDate != '' and params.startDate != 'null'">
                and pb.day_id >= #{params.startDate}
            </if>
            <if test="params.endDate != null and params.endDate != '' and params.endDate != 'null'">
                and pb.day_id <![CDATA[ <= ]]> #{params.endDate}
            </if>
            <if test="params.riderStation != null and params.riderStation != ''">
                and rs.id = #{params.riderStation}
            </if>
            <if test="params.riderPhone != null and params.riderPhone != '' and params.riderPhone != 'null'">
                and tu.phone like concat('%',#{params.riderPhone},'%')
            </if>
            <if test="params.riderName != null and params.riderName != '' and params.riderName != 'null'">
                and tu.user_name like concat('%',#{params.riderName},'%')
            </if>
        </where>
        order by pb.day_id desc
    </select>

    <select id="shopBill" resultType="com.sqx.modules.reconciliation.model.ShopBillVo">
        select
            pb.*,
            gs.shop_name as shopName,
            gs.phone,
            gs.shop_id as shopId
        from
            platform_bill pb
            left join goods_shop gs on gs.user_id = pb.user_id and gs.status = 1
        <where>
            pb.`type` = 1
            <if test="params.startDate != null and params.startDate != '' and params.startDate != 'null'">
                and pb.day_id >= #{params.startDate}
            </if>
            <if test="params.endDate != null and params.endDate != '' and params.endDate != 'null'">
                and pb.day_id <![CDATA[ <= ]]> #{params.endDate}
            </if>
            <if test="params.shopPhone != null and params.shopPhone != '' and params.shopPhone != 'null'">
                and gs.phone like concat('%',#{params.shopPhone},'%')
            </if>
            <if test="params.shopName != null and params.shopName != '' and params.shopName != 'null'">
                and gs.shop_name like concat('%',#{params.shopName},'%')
            </if>
        </where>
        order by pb.day_id desc
    </select>

    <select id="platformBill" resultType="com.sqx.modules.reconciliation.model.PlatformBill">
        select pb.*
        from platform_bill pb
        <where>
            pb.`type` = 0
            <if test="params.startDate != null and params.startDate != '' and params.startDate != 'null'">
                and pb.day_id >= #{params.startDate}
            </if>
            <if test="params.endDate != null and params.endDate != '' and params.endDate != 'null'">
                and pb.day_id <![CDATA[ <= ]]> #{params.endDate}
            </if>
        </where>
        order by pb.day_id desc
    </select>

    <select id="excelRiderBillList" resultType="com.sqx.modules.reconciliation.model.RiderBillVo">
        select pb.*,tu.user_name as userName,tu.phone ,rs.station_name as stationName
        from platform_bill pb left join tb_user tu on pb.user_id =tu.user_id
        left join rider_station rs on rs.id =tu.rider_station_id
        <where>
            pb.`type` =2
            <if test="params.startDate != null and params.startDate != '' and params.startDate != 'null'">
                and pb.day_id >= #{params.startDate}
            </if>
            <if test="params.endDate != null and params.endDate != '' and params.endDate != 'null'">
                and pb.day_id <![CDATA[ <= ]]> #{params.endDate}
            </if>
            <if test="params.riderStation != null and params.riderStation != ''">
                and rs.id = #{params.riderStation}
            </if>
            <if test="params.riderPhone != null and params.riderPhone != '' and params.riderPhone != 'null'">
                and tu.phone like concat('%',#{params.riderPhone},'%')
            </if>
            <if test="params.riderName != null and params.riderName != '' and params.riderName != 'null'">
                and tu.user_name like concat('%',#{params.riderName},'%')
            </if>
        </where>
        order by pb.day_id desc
    </select>

    <select id="excelShopBillList" resultType="com.sqx.modules.reconciliation.model.ShopBillVo">
        select
            pb.*,
            gs.shop_name as shopName,
            gs.phone
        from
            platform_bill pb
            left join goods_shop gs on gs.user_id = pb.user_id and gs.status = 1
        <where>
            pb.`type` = 1
            <if test="params.startDate != null and params.startDate != '' and params.startDate != 'null'">
                and pb.day_id >= #{params.startDate}
            </if>
            <if test="params.endDate != null and params.endDate != '' and params.endDate != 'null'">
                and pb.day_id <![CDATA[ <= ]]> #{params.endDate}
            </if>
            <if test="params.shopPhone != null and params.shopPhone != '' and params.shopPhone != 'null'">
                and gs.phone like concat('%',#{params.shopPhone},'%')
            </if>
            <if test="params.shopName != null and params.shopName != '' and params.shopName != 'null'">
                and gs.shop_name like concat('%',#{params.shopName},'%')
            </if>
        </where>
        order by pb.day_id desc
    </select>

    <select id="excelPlatformBillList" resultType="com.sqx.modules.reconciliation.model.PlatformBill">
        select pb.*
        from platform_bill pb
        <where>
            pb.`type` = 0
            <if test="params.startDate != null and params.startDate != '' and params.startDate != 'null'">
                and pb.day_id >= #{params.startDate}
            </if>
            <if test="params.endDate != null and params.endDate != '' and params.endDate != 'null'">
                and pb.day_id <![CDATA[ <= ]]> #{params.endDate}
            </if>
        </where>
        order by pb.day_id desc
    </select>

    <update id="updatePlatFormStartMoney">
        update platform_bill a join platform_bill b on a.type =b.type and  TO_DAYS(a.day_id)-TO_DAYS(b.day_id)= 1
        set a.start_money=b.end_money
        where a.day_id =#{dayId} and a.type = 0
    </update>

    <update id="updateRiderStartMoney">
        update platform_bill a join platform_bill b on a.user_id =b.user_id and a.type =b.type and  TO_DAYS(a.day_id)-TO_DAYS(b.day_id)= 1
        set a.start_money=b.end_money
        where a.day_id =#{dayId} and a.type in(1,2)
    </update>

    <insert id="insertPlatformBill">
        INSERT INTO `tcwm2.5`.platform_bill (
            day_id, user_id, shop_name, `type`, start_money, revenue, revenue_count,
            shop_payouts, shop_payouts_rates, shop_payouts_count, rider_payouts, rider_payouts_rates,
            rider_payouts_count, refund_money, refund_count, end_money, sys_gift_amount, platform_rates,
            total_income, pay_money, create_time, update_time, shop_balance
        )
        -- 第一部分：骑手数据（type=2）
        SELECT
            #{dayId},
            tu.user_id,
            NULL,
            2,
            0,
            IFNULL(SUM(ti.rider_money), 0),      -- 骑手总收入（revenue）
            COUNT(ti.rider_money),               -- 收入订单数（revenue_count）
            NULL, NULL, NULL,                    -- 商户提现字段（未使用）
            IFNULL(SUM(co.money), 0),            -- 骑手提现金额（rider_payouts）
            IFNULL(SUM(co.rate), 0),             -- 骑手提现手续费（rider_payouts_rates）
            COUNT(co.id),                     -- 骑手提现次数（rider_payouts_count）
            NULL, NULL,                          -- 退款字段（未使用）
            IFNULL(MAX(tu.balance), 0),          -- 期末余额（end_money）
            -- 系统赠送金额 - 系统扣除金额（sys_gift_amount）：
            IFNULL(
                (
                    SELECT
                        SUM(money)
                    FROM
                        user_money_details ud1
                    WHERE
                        ud1.user_id = tu.user_id
                        AND ud1.title LIKE '系统赠送%'
                        AND ud1.create_time > #{startTime}
                        AND ud1.create_time <![CDATA[ <= ]]> #{endTime}
                )
                -
                (
                    SELECT
                        SUM(money)
                    FROM
                        user_money_details ud2
                    WHERE
                        ud2.user_id = tu.user_id
                        AND ud2.title LIKE '系统扣除%'
                        AND ud2.create_time > #{startTime}
                        AND ud2.create_time <![CDATA[ <= ]]> #{endTime}
                )
                , 0
            ) AS gift_amount,
            NULL,                                -- 平台抽成（未使用）
            IFNULL(SUM(ti.rider_money), 0),      -- 总收益（total_income）
            NULL,                                -- 用户支付金额（未使用）
            #{now}, #{now},                      -- 创建和更新时间
            0                                    -- 商户余额（shop_balance）
        FROM
        tb_user tu USE INDEX (tb_user_rider_open_id_IDX)
            LEFT JOIN tb_indent ti USE INDEX (tb_indent_finish_time_IDX) ON ti.finish_time > #{startTime} AND ti.finish_time <![CDATA[ <= ]]> #{endTime} AND ti.rider_user_id = tu.user_id AND ti.indent_state = '6'        -- 订单状态：已完成
            LEFT JOIN cash_out co ON co.user_id = tu.user_id AND co.type = 1 AND co.state = 1 AND co.out_at > #{startTime} AND co.out_at <![CDATA[ <= ]]> #{endTime}
        WHERE
            tu.rider_open_id IS NOT NULL         -- 筛选骑手用户
        GROUP BY
            tu.user_id
        UNION ALL
        -- 第二部分：商家数据（type=1）
        SELECT
            #{dayId},
            tu.user_id,
            NULL,
            1,
            0,
            IFNULL(SUM(tor.shop_income_money), 0),   -- 商家总收入（revenue）
            COUNT(tor.shop_income_money),            -- 收入订单数（revenue_count）
            IFNULL(SUM(co.money), 0),               -- 商家提现金额（shop_payouts）
            IFNULL(SUM(co.rate), 0),                -- 商家提现手续费（shop_payouts_rates）
            COUNT(co.id),                        -- 商家提现次数（shop_payouts_count）
            NULL, NULL, NULL,                       -- 骑手提现字段（未使用）
            IFNULL(SUM(to1.pay_money), 0),          -- 退款金额（refund_money）
            COUNT(to1.pay_money),                   -- 退款次数（refund_count）
            -- 未结算订单金额（end_money）：
            IFNULL(
                (
                    SELECT
                        SUM(to2.shop_income_money)
                    FROM
                        tb_order to2
                    WHERE
                        to2.status = 4
                        AND to2.shop_id = gs.shop_id
                )
            , 0),
            -- 系统赠送金额 - 系统扣除金额（sys_gift_amount）：
            IFNULL(
                (
                    SELECT
                        SUM(money)
                    FROM
                        user_money_details ud1
                    WHERE
                        ud1.user_id = tu.user_id
                        AND ud1.title LIKE '系统赠送%'
                        AND ud1.create_time > #{startTime}
                        AND ud1.create_time <![CDATA[ <= ]]> #{endTime}
                )
                -
                (
                    SELECT
                        SUM(money)
                    FROM
                        user_money_details ud2
                    WHERE
                        ud2.user_id = tu.user_id
                        AND ud2.title LIKE '系统扣除%'
                        AND ud2.create_time > #{startTime}
                        AND ud2.create_time <![CDATA[ <= ]]> #{endTime}
                )
            , 0) AS gift_amount,
            -- 平台抽成金额（platform_rates）：
            IFNULL(ROUND(SUM(tor.shop_income_money * (1 - IFNULL(gs.shop_rate, 1)) / IFNULL(gs.shop_rate, 1)), 2), 0),
            IFNULL(SUM(tor.shop_income_money), 0),   -- 总收益（total_income）
            IFNULL(SUM(tor.pay_money), 0),           -- 用户支付金额（pay_money）
            #{now},
            #{now},                         -- 创建和更新时间
            IFNULL(MAX(um.money), 0)                -- 商户余额（shop_balance）
        FROM
            tb_user tu
            LEFT JOIN
                goods_shop gs ON tu.user_id = gs.user_id          -- 关联商家店铺
            LEFT JOIN
                tb_order tor USE INDEX (tb_order_update_time_IDX) ON gs.shop_id = tor.shop_id AND tor.update_time > #{startTime} AND tor.update_time <![CDATA[ <= ]]> #{endTime} AND tor.status = 4                  -- 订单状态：已完成
            LEFT JOIN
                    tb_order to1 USE INDEX (tb_order_update_time_IDX) ON gs.shop_id = to1.shop_id AND to1.update_time > #{startTime} AND to1.update_time <![CDATA[ <= ]]> #{endTime} AND to1.status IN (5, 8)            -- 订单状态：退款/异常
            LEFT JOIN
                    cash_out co ON co.user_id = tu.user_id AND co.type = 2 AND co.state = 1 AND co.out_at > #{startTime} AND co.out_at <![CDATA[ <= ]]> #{endTime}
            LEFT JOIN
                    user_money um ON um.user_id = tu.user_id          -- 用户余额表
        WHERE
            tu.admin_user_id IS NOT NULL            -- 筛选商家用户
        GROUP BY
            tu.user_id;
    </insert>

    <insert id="insertTotalPlatformBill">
        INSERT INTO `tcwm2.5`.platform_bill
        (day_id, user_id, shop_name, `type`, start_money, revenue, revenue_count,
         shop_payouts, shop_payouts_rates, shop_payouts_count, rider_payouts, rider_payouts_rates,
         rider_payouts_count, refund_money, refund_count, end_money,sys_gift_amount, platform_rates,total_income,pay_money,create_time,update_time)
        select
            day_id,null,null,0,0,sum(if(type=1, revenue,0)),sum(if(type=1, revenue_count,0)),
            sum(if(type=1, shop_payouts ,0)),sum(if(type=1, shop_payouts_rates ,0)),sum(if(type=1, shop_payouts_count ,0)),
            sum(if(type=2, rider_payouts ,0)),sum(if(type=2, rider_payouts_rates ,0)),sum(if(type=2, rider_payouts_count ,0)),
            sum(if(type=1, refund_money ,0)),sum(if(type=1, refund_count ,0)),(select ifnull(sum(pay_money), 0) from tb_order where status in (3,4,6,7)),null,
            sum(if(type=1, platform_rates ,0)),null,null,max(create_time) ,max(update_time)
        from platform_bill pb where day_id =#{dayId}
    </insert>

    <!-- 按商家维度统计订单完成金额、订单完成数量、订单取消金额、订单取消数量 -->
    <!-- 3待取餐/派送中 4已完成 6制作中 7商家待接单 5已取消、8商家拒绝接单 -->
    <!-- 3,4,6,7状态下用户已经完成付款对账的时候视为已完成订单 5,8状态下表示订单已取消 -->
    <select id="getOrderData" resultType="com.sqx.modules.reconciliation.model.OrderDataBO">
        SELECT
            shop_id,
            IFNULL(SUM(pay_money), 0) AS pay_amount,  -- 当天用户支付总金额
            SUM(IF(status IN (5, 8), pay_money, 0)) AS canceled_amount,     -- 已取消订单总金额
            COUNT(IF(status IN (5, 8), 1, NULL)) AS canceled_count,  -- 已取消订单总数量
            SUM(IF(status IN (3, 4, 6, 7), shop_income_money, 0)) AS shop_amount, -- 已完成订单商家总收入
            COUNT(IF(status IN (3, 4, 6, 7), 1, NULL)) AS completed_count  -- 已完成订单总数量
        FROM
            tb_order
        WHERE
            is_pay = 1
            AND pay_time BETWEEN #{startTime} AND #{endTime}
        GROUP BY
            shop_id;
    </select>

    <select id="getShopMoneyRecord" resultType="com.sqx.modules.reconciliation.model.ShopMoneyRecordBO">
        SELECT
            shop_id,
            SUM(TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(content, '平台服务费:', -1), ',',1), ':', -1))) AS platform_fee
        FROM
            user_money_details
        WHERE
            shop_id IS NOT NULL
          AND type = 1
          AND classify = 3
          AND create_time BETWEEN #{startTime} AND #{endTime}
        GROUP BY shop_id;
    </select>

    <select id="getShopCashOutRecord" resultType="com.sqx.modules.reconciliation.model.CashOutRecordBO">
        SELECT
            user_id,
            IFNULL(SUM(money), 0) payouts, -- 提现金额
            IFNULL(SUM(rate), 0) payouts_rates, -- 提现手续费
            COUNT(id) payouts_count, -- 提现次数
            SUM(IF(state = 1, money, 0)) AS payouts_of_Success,  -- 已成功提现金额
            SUM(IF(state = 1, rate, 0)) AS payouts_rates_of_Success,  -- 已成功提现手续费
            COUNT(IF(state = 1, 1, NULL)) AS payouts_count_of_Success  -- 已成功提现次数
        FROM
            cash_out
        WHERE
            state != -1
            AND create_at BETWEEN #{startTime} AND #{endTime}
            AND shop_id IS NOT NULL
        GROUP BY user_id;
    </select>

    <select id="getRiderCashOutRecord" resultType="com.sqx.modules.reconciliation.model.CashOutRecordBO">
        SELECT
            user_id,
            IFNULL(SUM(money), 0) payouts, -- 提现金额
            IFNULL(SUM(rate), 0) payouts_rates, -- 提现手续费
            COUNT(id) payouts_count, -- 提现次数
            SUM(IF(state = 1, money, 0)) AS payouts_of_Success,  -- 已成功提现金额
            SUM(IF(state = 1, rate, 0)) AS payouts_rates_of_Success,  -- 已成功提现手续费
            COUNT(IF(state = 1, 1, NULL)) AS payouts_count_of_Success  -- 已成功提现次数
        FROM
            cash_out
        WHERE
            create_at BETWEEN #{startTime} AND #{endTime}
            AND shop_id IS NULL
        GROUP BY user_id;
    </select>

    <select id="getUserMoneyBalance" resultType="com.sqx.modules.reconciliation.model.UserMoneyBalanceBO">
        SELECT
            user_id,
            money balance
        FROM
            user_money
        WHERE
            user_id IN
                <foreach collection="userIds" item="userId" open="(" separator="," close=")">
                    #{userId}
                </foreach>
    </select>

    <select id="getIndentOrderData" resultType="com.sqx.modules.reconciliation.model.IndentOrderDataBO">
        SELECT
            rider_user_id user_id,
            SUM(rider_money) AS totalAmount,
            COUNT(indent_id) AS orderCount
        FROM
            tb_indent
        WHERE
            finish_time BETWEEN #{startTime} AND #{endTime}
          AND rider_user_id IS NOT NULL
          AND indent_state = '6'
        GROUP BY rider_user_id;
    </select>

    <select id="getSysGiftRecord" resultType="com.sqx.modules.reconciliation.model.SysGiftRecordBO">
        SELECT
            user_id,
            SUM(IF(type = 1, money, 0)) - SUM(IF(type = 2, money, 0)) as amount
        FROM
            user_money_details
        WHERE
            state = 2
          AND classify = 3
          AND create_time BETWEEN #{startTime} AND #{endTime}
          AND user_id IN
                <foreach collection="userIds" item="userId" open="(" separator="," close=")">
                    #{userId}
                </foreach>
          AND (title = '系统赠送骑手余额' or title = '系统扣除骑手余额')
        GROUP BY user_id;
    </select>
</mapper>
