<?php

declare(strict_types=1);

namespace App\Command;

use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
use App\Platform\Tools\Request\CompanyRequest;
use App\Model\Company;
use Hyperf\DbConnection\Db;
use App\Utils\Log;
use Exception;

#[Command]
class AppCompanySync extends HyperfCommand
{
    public function __construct(protected ContainerInterface $container)
    {
        parent::__construct('app:company:sync');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('Sync companies from Tools Dashboard');
    }

    public function handle()
    {
        $companies = CompanyRequest::all();

        try{
            Db::beginTransaction();

            $companies->each(function($el){
                $exist_company = Company::find($el['id']);
                if($exist_company){
                    # @attention update 方法不会进行 cast 类型转换，执行时需要注意, tools 数据中 isEnabled 存在值为 空字符串的情况
                    $exist_company->update([
                        'name' => $el['name'],
                        'enabled' => \boolval($el['isEnabled']) === true ? true : false,
                    ] );
                    return;
                }
                
                Company::create([
                    'id' => $el['id'],
                    'name' => $el['name'],
                    'enabled' => \boolval($el['isEnabled']) === true ? true : false,
                ]);
                
            });

            Db::commit();

            $this->info("公司数据同步已完成");

        } catch(Exception $e){

            Db::rollBack();
            dump($e->getMessage());
            Log::error($e->getMessage());
            $this->error($e->getMessage());
            $this->info("公司数据同步失败，数据更新已撤销");

        }

    }
}
