<?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\StoreRequest;
use App\Model\Store;
use Hyperf\DbConnection\Db;
use App\Utils\Log;
use Exception;

use function Symfony\Component\String\s;

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

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

    public function handle()
    {
        $stores = StoreRequest::all();

        try{
            Db::beginTransaction();

            $stores->each(function($el){
                
                // 处理 $warehouse_id，空字符串转换为 null
                $warehouse_id = !empty($el['warehouse']['id']) ? (int)$el['warehouse']['id'] : null;

                // 准备扩展字段数据
                $ext = [
                    'is_self_managed' => $el['is_self_managed'] ?? false,
                    'is_warehouse' => $el['is_warehouse'] ?? false,
                ];

                $storeData = [
                    'company_id' => (int)$el['company']['id'],
                    'platform_id' => (int)$el['platform']['id'],
                    'platform_store_id' => !empty($el['platform_store_id']) ? strval($el['platform_store_id']): null,  
                    'warehouse_id' => $warehouse_id,
                    'currency_id' => (int)$el['currency']['id'],
                    'enabled' => \boolval($el['is_enabled']) === true ? true : false,
                    'name' => $el['name'],
                    'label' => $el['label'] ?? null,
                    'created_at' => $el['createdDate'],
                    'ext' => $ext,
                ];

                $existStore = Store::find($el['id']);
                if($existStore){
                    # @attention update 方法不会进行 cast 类型转换，执行时需要注意
                    $existStore->update($storeData);
                    return;
                }

                Store::create(array_merge(['id' => (int)$el['id']], $storeData));
            });

            Db::commit();

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

        } catch(Exception $e){

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

        }

    }
}
