<?php

namespace App\Services;

use App\Traits\ServiceAppAop;
use App\OrderPackageExceptionTypeCountingRecord;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class OrderPackageExceptionTypeCountingRecordService
{
    use ServiceAppAop;

    protected $modelClass = OrderPackageExceptionTypeCountingRecord::class;

    /**
     * 同步当前日期多少天前数据
     */
    public function updateOrCreate($days)
    {
        DB::table("order_packages")
            ->select(['exception_type',
                DB::raw('count( * ) AS exception_type_count'),
                DB::raw("DATE_FORMAT( sent_at, '%Y-%m-%d' ) AS sent_at_date "),
                'owner_id',
            ])
            ->where('sent_at', '>=', now()->subDays($days)->startOfDay())
            ->whereNotNull(['owner_id', 'sent_at'])
            ->where('exception_type','!=','无')
            ->groupBy(['exception_type',
                'sent_at_date',
                'owner_id'])->orderBy('sent_at_date')->chunk(1000, function ($items) {
                foreach ($items as $item) {
                    OrderPackageExceptionTypeCountingRecord::query()->updateOrCreate((array)$item);
                }
            });
    }

    public function updateOrCreateByDate($date)
    {
        DB::table("order_packages")
            ->select(['exception_type',
                DB::raw('count( * ) AS exception_type_count'),
                DB::raw("DATE_FORMAT( sent_at, '%Y-%m-%d' ) AS sent_at_date "),
                'owner_id',
            ])
            ->where('sent_at', '>=', Carbon::parse($date)->startOfDay())
            ->where('sent_at', '<=', Carbon::parse($date)->endOfDay())
            ->whereNotNull(['owner_id', 'sent_at'])
            ->where('exception_type','!=','无')
            ->groupBy(['exception_type',
                'sent_at_date',
                'owner_id'])->orderBy('sent_at_date')->chunk(1000, function ($items) {
                foreach ($items as $item) {
                    OrderPackageExceptionTypeCountingRecord::query()->updateOrCreate((array)$item);
                }
            });
    }

    public function get(array $kvPairs): ?Collection
    {
        return OrderPackageExceptionTypeCountingRecord::query()
            ->select(['exception_type', DB::raw('sum(exception_type_count) as count')])
            ->where('sent_at_date', '>=', Carbon::parse($kvPairs['start_date'])->startOfDay())
            ->where('sent_at_date', '<=', Carbon::parse($kvPairs['end_date'])->endOfDay())
            ->where('exception_type','!=','无')
            ->whereIn('owner_id', $kvPairs['owner_ids'])
            ->groupBy('exception_type')->get();
    }
}
