<?php

namespace Shop\Modules\AdminOrderItems;

use ActiveTable\ColumnTable;
use ActiveTable\DataTableEngine;
use Core\Form\ControlBuilder;
use Core\ModuleController;
use Diamond\Helpers\Form;
use DiamondTable\TableFactory;
use Shop\Repositories\OrderItem\OrderItemCriteria;
use Shop\Repositories\OrderItem\OrderItemRepository;
use Shop\Repositories\Provider\ProviderCriteria;
use Shop\Repositories\Provider\ProviderRepository;
use Shop\Repositories\State\StateCriteria;
use Shop\Repositories\State\StateRepository;
use Shop\Repositories\Stock\StockCriteria;
use Shop\Repositories\Stock\StockRepository;
use Shop\UseCases\Checkout\Checkout;

/**
 * Description of AdminOrderItems
 *
 * @author Diamond Code Generator
 */
class AdminOrderItems extends ModuleController
{

    use FormatColumnsTrait;
    protected $repository;
    protected $tableFactory;
    protected $controlBuilder;
    protected $providerRepository;
    protected $stateRepository;
    protected $checkoutUseCase;
    protected $stockRepository;

    public function __construct(OrderItemRepository $repository, TableFactory $tableFactory,
                                ControlBuilder $controlBuilder, ProviderRepository $providerRepository,
                                StateRepository $stateRepository, Checkout $checkoutUseCase,
                                StockRepository $stockRepository)
    {
        $this->repository = $repository;
        $this->tableFactory = $tableFactory;
        $this->controlBuilder = $controlBuilder;
        $this->providerRepository = $providerRepository;
        $this->stateRepository = $stateRepository;
        $this->stockRepository = $stockRepository;
        $this->checkoutUseCase = $checkoutUseCase;
    }

    /**
     * @return string
     * @throws \ReflectionException
     * @throws \Repo\Concrete\Exceptions\Collection
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function process(): string
    {

        $stocks = $this->stockRepository->findByCriteria(
            StockCriteria::create()
        );

        $providers = $this->providerRepository->findByCriteria(
            ProviderCriteria::create()
        );

        $states = $this->stateRepository->findByCriteria(
            StateCriteria::create()
        );

        $table =
            $this->tableFactory->buildAdminTable(
                $this->repository,
                OrderItemCriteria::create()
            )
            ->removeControlAccess(DataTableEngine::CONTROL_ACCESS_ADD)
            ->setDefaultSortColumn('id', 'DESC')
            ->addColumn(
                (new ColumnTable(
                    'id', '№'
                ))
                    ->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable(
                    'orderCode', 'Номер заказа'
                ))
                    ->setExported(true)
                    ->setFormat($this, 'formatOrder')

            )
            ->addColumn(
                (new ColumnTable('datetime', 'Дата заказа'))
                    ->setExported(true)
                    ->setFormat($this, 'formatDate')

            )
            ->addColumn(
                (new ColumnTable(
                    'contractorId', 'Клиент'
                ))
                    ->setExported(true)
                    ->setFormat($this, 'formatClientFull')

            )

            ->addColumn(
                (new ColumnTable(
                    'name', 'Наименование товара'
                ))
                    ->setExported(true)

            )
            ->addColumn(
                (new ColumnTable(
                    'article', 'Артикул'
                ))
                    ->setExported(true)

            )
            ->addColumn(
                (new ColumnTable(
                    'brand', 'Производитель'
                ))
                    ->setExported(true)

            )
//            ->addColumn(
//                (new ColumnTable(
//                    'desc', 'Характеристики'
//                ))
//                    ->setWidth(10, true)
//            )
            ->addColumn(
                (new ColumnTable(
                    'price', 'Цена'
                ))
                    ->setExported(true)

            )
            ->addColumn(
                (new ColumnTable(
                    'amount', 'Кол-во'
                ))
                    ->setExported(true)
            )
//            ->addColumn(
//                (new ColumnTable(
//                    'managerComment', 'Коментарий менеджера'
//                ))
//                    ->setWidth(15, true)
//            )
            ->addColumn(
                (new ColumnTable(
                    'stateId', 'Состояние'
                ))
                    ->setExported(true)
                    ->setFormat($this, 'formatState')

            )
            ->addColumn(
                (new ColumnTable(
                    'contractorId', 'Торговая точка'
                ))
                    ->setExported(true)
                    ->setFormat($this, 'formatStock')

            )
            ->addColumn(
                (new ColumnTable(
                    'destination', 'Направление'
                ))
                    ->setExported(true)
            )
            ->addColumn(
                (new ColumnTable(
                    'providerId', 'Поставщик'
                ))
                    ->setExported(true)
                    ->setFormat($this, 'formatProvider')

            )
            ->addColumn(
                (new ColumnTable(
                    'actions', ''
                ))
                    ->setFormat($this, 'formatActions')
                    ->setWidth(110)
            );


        $table
            ->addFilter(
                $this->controlBuilder->buildInput('filter_by_orderCode')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_name')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_article')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_brand')
            )
            ->addFilter(
                $this->controlBuilder->buildDropdownUniform('filter_by_contractorId', Form::prepareDropdown($stocks))
            )
            ->addFilter(
                $this->controlBuilder->buildDropdownUniform('filter_by_providerId', Form::prepareDropdown($providers))
            )
            ->addFilter(
                $this->controlBuilder->buildDropdownUniform('filter_by_stateId', Form::prepareDropdown($states))
            );

        $table
            ->addField(
                $this->controlBuilder
                    ->buildTextLabel('orderCode')
                    ->setFn($this, 'formatOrder')
            )
            ->addField(
                $this->controlBuilder->buildInput('name'), true
            )
            ->addField(
                $this->controlBuilder->buildInput('article')
            )
            ->addField(
                $this->controlBuilder->buildInput('brand')
            )
            ->addField(
                $this->controlBuilder->buildInput('price'), true
            )
            ->addField(
                $this->controlBuilder->buildSpinner('amount'), true
            )
            ->addField(
                $this->controlBuilder->buildDropdownUniform('stateId', Form::prepareDropdown($states)), true
            )
            ->addField(
                $this->controlBuilder->buildDropdownUniform('providerId', Form::prepareDropdown($providers)), true
            )
            ->addField(
                $this->controlBuilder->buildTextArea('managerComment'), false, 'Коментарий менеджера'
            )
            ->addField(
                $this->controlBuilder->buildTextArea('desc'), false, 'Характеристики'
            )
            ->addField(
                $this->controlBuilder->buildInput('destination'), false, 'Направление'
            );


        foreach ($states as $state) {
            $table
                ->addRowActionCommand(
                    'change-state-selected-' . $state->getId(),
                    new ChangeStateCommand($table, $state, $this->checkoutUseCase),
                    sprintf('Сменить на состояние `%s`', $state->getTitle())
                );
        }

        $table
            ->addRowActionCommand(
                'create-provider-order-selected',
                new CreateProviderOrderCommand($table, $this->checkoutUseCase),
                'Создать заказ поставщику'
            );

        return $table->render();
    }




}               