<?php

namespace App\Domains\Virtual\Commands\Sync;

use App\Models\Virtual\Company;
use Illuminate\Support\Facades\DB;
use App\Domains\Virtual\Services\CommonService;
use App\Domains\Virtual\Repositories\CompanyRepository;

class CompanySync extends Command
{
    protected $name = 'virtual:sync-company';

    protected $description = '同步VD企业数据';

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

        $data = DB::connection('vd_old')->table('ckb_company')->select([
            'id',
            'unicom_name as name',
            'create_time as created_at',
            'update_time as updated_at',
            'del'
        ])->get()->toArray();

        foreach ($data as &$item) {
            $item = (array)$item;
            $item['name'] = trim($item['name']);
            $item['sn'] = CommonService::stringifyCompanyId($item['id']);
            $item['created_at'] = date('Y-m-d H:i:s', $item['created_at']);
            $item['updated_at'] = date('Y-m-d H:i:s', $item['updated_at']);
            $item['deleted_at'] = $item['del'] ? $item['updated_at'] : null;
            unset($item['del']);
            unset($item['id']);
        }

        Company::upsert($data, ['sn', 'deleted_at']);

        app(CompanyRepository::class)->forgetCached();
    }
}
