<?php

namespace App\Dao\Settlement;

use App\Consts\BaseConst;
use App\Consts\BillConst;
use App\Models\Order\Order;
use App\Models\Settlement\Bills;

class BillDao
{
    /**
     * 获取渠道结算账单列表
     *
     * @param $param
     * @return mixed
     */
    public function getBills($param)
    {
        $query = Bills::select('id', 'date', 'recharge_amount', 'rate', 'service_amount', 'settlement_price')
                      ->where('type', BillConst::SETTLEMENT_TYPE_CHANNEL);

        // 站点
        $channelId = (int)getProp($param, 'channel_id');
        if ($channelId) {
            $query->where('distribution_channel_id', $channelId);
        }

        $dateRange = getProp($param, 'date_range');
        if ($dateRange) {
            [$startDate, $endDate] = explode(',', $dateRange);
            if ($startDate && $endDate && $startDate <= $endDate) {
                $query->where('date', '>=', $startDate);
                $query->where('date', '<=', $endDate);
            }
        } else {
            // 只显示7日前数据
            $query->where('date', '<=', date('Y-m-d', strtotime('-' . BaseConst::DATE_RANGE_DAYS . ' days')));
        }

        // 导出用
        $all = (int)getProp($param, 'export');
        if ($all) {
            return $query->orderBy('id', 'desc')->get();
        }

        return $query->orderBy('id', 'desc')->paginate(10);
    }

    /**
     * @param $channelId
     * @param $date
     * @return mixed
     */
    public function billOrders($channelId, $date)
    {
        return Order::select('orders.id', 'price', 'send_order_id', 'send_orders.name as send_order_name', 'orders.created_at')
                    ->leftJoin('send_orders', 'orders.send_order_id', '=', 'send_orders.id')
                    ->where('orders.distribution_channel_id', $channelId)
                    ->where('orders.status', 'PAID')
                    ->where('orders.send_order_id', '>', 0)
                    ->where('orders.created_at', '>=', date('Y-m-d 00:00:00', strtotime($date)))
                    ->where('orders.created_at', '<=', date('Y-m-d 23:59:59', strtotime($date)))
                    ->orderBy('orders.id', 'desc')
                    ->paginate();
    }

    /**
     * @param $channelId
     * @param string $startDate
     * @param string $endDate
     * @return mixed
     */
    public function getBillsRechargeAmount($channelId, string $startDate = '', string $endDate = '')
    {
        $query = Bills::where('distribution_channel_id', $channelId)->where('type', 'channel');
        if ($startDate && $endDate) {
            $query->whereBetween('date', [$startDate, $endDate]);
        }
        if ($endDate && !$startDate) {
            $query->where('date', '<=', $endDate);
        }

        return $query->sum('recharge_amount');
    }
}