<?php

namespace App\Domains\Real\Commands\Sync;

use Illuminate\Support\Facades\DB;
use App\Domains\Real\Repositories\OrderCardPartitionRepository;
use App\Domains\Virtual\Repositories\OrderCardPartitionRepository as VirtualOrderCardPartitionRepository;

class RefundSync extends Command
{
    protected $name = 'real:sync-refund';

    protected $description = '同步RD退货数据';

    protected $companies;

    public function handle()
    {
        $datetime = $this->getDateTime();

        $starttime = $datetime->copy()->startOfMonth()->startOfDay();
        $endtime = $datetime->copy()->endOfMonth()->endOfDay();

        $refunds = DB::connection('real')->table('jxc_back_card')
            ->select(['sim', 'create_time'])
            ->where('status', 2)
            ->where('create_time', '>=', $starttime)
            ->where('create_time', '<=', $endtime)
            ->get();

        $simArray = [];

        $refunds->map(function ($item) use (&$simArray) {
            $item->sim = str_to_array($item->sim, ',');
            $simArray = array_merge($simArray, $item->sim);
        });

        DB::transaction(function () use ($refunds) {
            foreach ($refunds as $item) {
                DB::table('real_order_cards')
                    ->whereIn('sim', $item->sim)
                    ->where('created_at', '<=', $item->create_time)
                    ->update(['refunded_at' => $item->create_time]);

                DB::table('virtual_order_cards_partition')
                    ->whereIn('sim', $item->sim)
                    ->where('created_at', '<=', $item->create_time)
                    ->whereNull('service_start_at')
                    ->update(['refunded_at' => $item->create_time]);
            }
        });

        app(OrderCardPartitionRepository::class)->forgetCached();
        app(VirtualOrderCardPartitionRepository::class)->forgetCached();
    }
}
