<?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;

    protected $subMonths = 1;

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

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

        $lastTime = $starttime->copy()->subMonths($this->subMonths)->startOfMonth();

        $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, $lastTime) {
            foreach ($refunds as $item) {
                DB::table('real_order_cards')
                    ->whereIn('sim', $item->sim)
                    ->where('created_at', '<=', $item->create_time)
                    ->where('created_at', '>=', $lastTime)
                    ->update(['refunded_at' => $item->create_time]);

                $simArrayText = implode(',', $item->sim);

                $sql = "
                    UPDATE virtual_order_cards_partition AS v
                    SET refunded_at = '%s'
                    FROM cards AS c
                    WHERE c.sim = v.sim
                    AND v.sim IN (%s)
                    AND v.created_at <= '%s'
                    AND v.created_at >= '%s'
                ";

                DB::update(sprintf($sql, $item->create_time, $simArrayText, $item->create_time, $lastTime));
            }
        });

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