<?php

namespace App\Console\Commands;

use App\Logistic;
use App\Services\common\BatchUpdateService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SyncCarrier extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:carrier';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync carriers every hour';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $carriers = DB::connection("oracle")->select(DB::raw("SELECT CUSTOMERID,CUSTOMER_TYPE,DESCR_C,CASE DESCR_E WHEN 'WL' THEN '物流' ELSE '快递' END AS TYPE FROM BAS_CUSTOMER WHERE CUSTOMER_TYPE = 'CA'"));
        $logistics = Logistic::query()->whereIn("code",array_column($carriers,"customerid"))->get();
        $changes = diff($carriers,$logistics,"code",["code"=>"customerid","name"=>"descr_c","type"=>"type"]);
        if ($changes['attached'])Logistic::query()->insert($changes['attached']);
        if ($changes['updated']){
            array_unshift($changes['updated'],["code","name","type"]);
            app(BatchUpdateService::class)->batchUpdate("logistics",$changes['updated']);
        }
        if ($changes["detached"])Logistic::query()->whereIn("code",$changes["detached"])->delete();
    }
}
