<?php


namespace App\Services;


use App\Order;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use App\Traits\ServiceAppAop;


class RealtimePendingOrdersService
{
    use ServiceAppAop;
    protected $modelClass=RealtimePendingOrders::class;
    /**
     * 获取实时待处理订单
     * @param null $start
     * @param null $end
     * @return Builder[]|Collection|mixed
     */
    public function warehousesOrders($start = null, $end = null)
    {
        try {
            return Cache::remember('RealTimePendingOrders' . Auth::id(), 60, function () use ($start, $end) {
                return $this->getOrderStatistics($start, $end);
            });
        } catch (\Exception $e) {
            return $this->getOrderStatistics($start, $end);
        }
    }

    /**
     * @param $start
     * @param $end
     * @return Builder[]|Collection
     */
    public function getOrderStatistics($start, $end)
    {
        $start = $start ?? date('Y-m-d 00:00:00');
        $end = $end ?? date('Y-m-d 23:59:59');
        $ownerIds = app('OwnerService')->getSelection();
        $builders = Order::query()->selectRaw("warehouses.code," .
            "count(case wms_status when '创建订单' then 1 end) as createOrder, " .
            "count(case wms_status when '分配完成' then 1 end) as assignedComplete, " .
            "count(case wms_status when '部分分配' then 1 end) as partialAllocation, " .
            "count(case wms_status when '部分装箱' then 1 end) as partPacking, " .
            "count(case wms_status when '播种完成' then 1 end) as sowComplete, " .
            "count(1) as total"
        )->whereBetween('orders.created_at', [$start, $end,])
            ->whereIn('wms_status', ['创建订单', '分配完成', '部分分配', '部分装箱', '播种完成'])
            ->leftJoin('warehouses', 'orders.warehouse_id', 'warehouses.id')
            ->groupBy('warehouse_id');
        if ($ownerIds) $builders->whereIn('owner_id', $ownerIds);
        return $builders->get();
    }
}
