<?php

namespace Shop\Application\Shopping\CreateProviderOrder;

use MoySklad\Application\Commands\CreateOrder\CreateOrderCommand;
use Shop\Application\Shopping\ChangeOrderItemState\ChangeOrderItemStateCommand;
use Shop\Application\Shopping\CreateCustomerOrder\BuildOrderPositionTrait;
use Shop\Application\Shopping\CreateProviderOrdersFromCustomerOrderItem\CreateProviderOrdersException;
use Shop\Config\Main;
use Shop\Repositories\ProviderOrder\ProviderOrderRepository;
use Shop\Repositories\State\StateRepository;
use spaceonfire\CommandBus\CommandBus;

class CreateProviderOrderHandler
{
    use BuildOrderPositionTrait;

    protected $stateRepository;
    protected $mainConf;
    protected $providerOrderRepository;
    protected $commandBus;

    /**
     * CreateProviderOrderHandler constructor.
     * @param StateRepository $stateRepository
     * @param ProviderOrderRepository $providerOrderRepository
     * @param CommandBus $commandBus
     * @param Main $mainConf
     */
    public function __construct(StateRepository $stateRepository,
                                ProviderOrderRepository $providerOrderRepository,
                                CommandBus $commandBus,
                                Main $mainConf)
    {
        $this->stateRepository = $stateRepository;
        $this->mainConf = $mainConf;
        $this->providerOrderRepository = $providerOrderRepository;
        $this->commandBus = $commandBus;
    }


    public function handle(CreateProviderOrderCommand $command): void
    {


        $orderRequest = $command->getOrderRequest();

        /**
         * @var ProviderOrderItemRequest $item
         * @var StateEntityInterface $state
         */
        if (!$state = $this->stateRepository->findById($this->mainConf->getStateProviderDefault())) {
            throw new CreateProviderOrdersException(sprintf(
                'default `%s` state not found', $this->mainConf->getStateProviderDefault()
            ));
        }

        $order = ProviderOrderRepository::createEntity()
            ->setCustomerId($orderRequest->getClientId())
            ->setPaymentId($orderRequest->getPaymentId())
            ->setComment($orderRequest->getComment())
            ->setDeliveryAddress($orderRequest->getDeliveryAddress())
            ->setContractorId($orderRequest->getContractorId())
            ->setStateId($this->mainConf->getStateProviderDefault())
            ->setDiscountSumm($orderRequest->getDiscount());

        foreach ($orderRequest->getItems() as $item) {
            $orderItem = $this->buildOrderItem($item);
            $orderItem->setStateId($this->mainConf->getStateProviderDefault());
            $order->addOrderItem($orderItem);
        }

        $this->providerOrderRepository->save($order);

        //меняем состояния у кдиентских позийий и свяхываем клиентские с заказом аоставщика
        //@todo проработать момент таблицы с делегированием различных признаков
        foreach ($order->getOrderItems() as $orderItem) {

            //меняем состояния позиций клиентского заказа
            foreach ($orderRequest->getItems() as $item) {

                if ($orderItem->getRefId() === $item->getRefId() &&
                    $orderItem->getArticle() === $item->getArticle() &&
                    $orderItem->getBrand() === $item->getBrand()
                ) {

                    $this->commandBus->handle(new ChangeOrderItemStateCommand($item->getCustomerOrderItemId(),$state->getId()));

                    /**
                     * @var OrderItem $itemEntity
                     */
//                    $itemEntity = $this->itemRepository->findById($item->getCustomerOrderItemId());
//
//                    //$providerItem = new ProviderOrderItem();
//                    //$providerItem->setPrimaryKey($orderItem);
//
//                    $itemEntity->setProviderOrderItem(new ProviderOrderItem());
//                  //  dd($itemEntity->getOrder(),$orderItem->getOrder());
//                    $itemEntity->save();
                    continue;
                }
            }
        }

        $command->getResult()->setOrder($order);
    }
}