<?php

namespace App\Domains\Real\Commands\Sync;

use Carbon\Carbon;
use App\Models\Card\Card;
use Illuminate\Support\Facades\DB;
use App\Domains\Card\Repositories\CardRepository;
use App\Domains\Virtual\Repositories\OrderCardPartitionRepository;

class CancelledSync extends Command
{
    protected $name = 'real:sync-cancelled';

    protected $description = '同步注销数据(每月同步上个月的注销数据)';

    protected $limit = 1000;

    public function handle()
    {
        $datetime = $this->getDateTime();
        $starttime = $datetime->copy()->startOfMonth()->startOfDay()->timestamp;
        $endtime = $datetime->copy()->endOfMonth()->endOfDay()->timestamp;

        $cancelRecords = DB::connection('real')->table('jxc_cancel_card')
            ->where('cn_create_time', '>=', $starttime)
            ->where('cn_create_time', '<=', $endtime)
            ->where('cn_status', 1)->get()->keyBy('cn_id');

        $this->line('待同步条数:'.count($cancelRecords));

        if (empty($cancelRecords)) {
            return;
        }

        $cards = DB::connection('real')->table('jxc_cancel_card_item')
            ->whereIn('item_cn_id', $cancelRecords->pluck('cn_id')->toArray())->get();

        $cards = $cards->chunk(1000);

        foreach ($cards as $values) {
            $array = [];

            foreach ($values as $item) {
                $record = $cancelRecords[$item->item_cn_id];
                $array[] = [
                    'sim' => $item->item_sim,
                    'cancelled_at' => Carbon::createFromTimestamp($record->cn_create_time),
                ];
            }

            Card::updateBatch($array, 'sim::int8');
        }

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