<?php

namespace Shop\Modules\AdminProviders;

use ActiveTable\ColumnTable;
use Core\Form\ControlBuilder;
use Diamond\Helpers\Form;
use DiamondTable\TableFactory;
use Shop\Application\Office\Exceptions\MainStockNotFoundException;
use Shop\Application\Office\Exceptions\MainStockSomeFoundException;
use Shop\Application\Office\OfficeService;
use Shop\Config\Main;
use Shop\Repositories\City\CityRepository;
use Shop\Repositories\Country\CountryRepository;
use Shop\Repositories\Currency\CurrencyCriteria;
use Shop\Repositories\Currency\CurrencyRepository;
use Shop\Repositories\Customer\CustomerRepository;
use Shop\Repositories\Manager\ManagerRepository;
use Shop\Repositories\Provider\ProviderCriteria;
use Shop\Repositories\Provider\ProviderRepository;
use Shop\Repositories\Region\RegionRepository;
use Shop\Repositories\Stock\StockRepository;


/**
 * Description of AdminProviders
 *
 * @author Diamond Code Generator
 */
class AdminProviders extends \Core\ModuleController
{

    use ColumnsFormatTrait;
    use ContractorFormTrait;

    protected $tableFactory;
    protected $currencyRepository;
    protected $customerGroupRepository;
    protected $managerRepository;
    protected $customerRepository;
    protected $countryRepository;
    protected $stockRepository;
    protected $cityRepository;
    protected $regionRepository;

    protected $officeService;

    public function __construct(ProviderRepository $providerRepository, TableFactory $tableFactory,
                                ControlBuilder $controlBuilder, CurrencyRepository $currencyRepository,
                                ManagerRepository $managerRepository,
                                CustomerRepository $customerRepository, CountryRepository $countryRepository,
                                OfficeService $officeService,
                                Main $mainConf,
                                CityRepository $cityRepository,
                                RegionRepository $regionRepository, StockRepository $stockRepository
    )
    {
        $this->providerRepository = $providerRepository;
        $this->tableFactory = $tableFactory;
        $this->controlBuilder = $controlBuilder;
        $this->currencyRepository = $currencyRepository;
        $this->managerRepository = $managerRepository;
        $this->customerRepository = $customerRepository;
        $this->countryRepository = $countryRepository;
        $this->officeService = $officeService;

        $this->mainConf = $mainConf;
        $this->cityRepository = $cityRepository;
        $this->regionRepository = $regionRepository;
        $this->stockRepository = $stockRepository;
    }

    public function process(): string
    {
        try {
            $mainStock = $this->officeService->getMainStock();
        } catch (MainStockSomeFoundException $ex) {
            return Form::buildAnnouncementMessage('Найдено несколько офисов с признаком головного, необходим только 1, доступ к разделу запрещен!');
        } catch (MainStockNotFoundException $ex) {
            return Form::buildAnnouncementMessage('Головной офис не задан, доступ к разделу запрещен!');
        }

        $currencies = $this->currencyRepository->findByCriteria(
            CurrencyCriteria::create()
        );


        $table = $this->tableFactory->buildAdminTable($this->providerRepository, ProviderCriteria::create());
        $table->setDefaultSortColumn('id', 'DESC');


        //заменяем комманду стандратной записи на свою
//        $table
//            ->getCommandFactory()
//            ->addCommand(CommandFactory::FORM_SAVE,
//                new SaveProviderCommand($table, $this->officeUseCase, $this->customerRepository)
//            );


        $table
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('name', 'Название'))
            )
            ->addColumn(
                (new ColumnTable('term', 'Срок доставки, дней'))
            )
            ->addColumn(
                (new ColumnTable('destination', 'Направление'))
            )
            ->addColumn(
                (new ColumnTable('contact', 'Контакты'))
            )
            ->addColumn(
                (new ColumnTable('currencyId', 'Валюта'))
                    ->setFormat($this, 'formatCurrency')

            )
            ->addColumn(
                (new ColumnTable('contractorId', 'Контрагент'))
                    ->setFormat($this, 'formatContractor')

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



        $table
            ->addField(
                $this->controlBuilder->buildFormHeader('Основная информация о поставщике', 'mainData')
            )
            ->addField(
                $this->controlBuilder->buildInput('name'), true
            )
            ->addField(
                $this->controlBuilder->buildSpinner('term')->setValue(1), true
            )
            ->addField(
                $this->controlBuilder->buildDropdownUniform('currencyId', Form::prepareDropdown($currencies)), true
            )
            ->addField(
                $this->controlBuilder->buildColorPicker('color'), false, 'Цвет в поиске'
            )
            ->addField(
                $this->controlBuilder->buildInputSmall('destination'), true, null, 'Будет отображаться вместо наименования'
            )
            ->addField(
                $this->controlBuilder->buildTextArea('contact')
            )
            ->addField(
                $this->controlBuilder->buildTextArea('desc'), false, 'Описание'
            )

            ->addFilter(
                $this->controlBuilder->buildInput('search_by_name')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_destination')
            )
            ;

        $this->makeContractorForm($table, $this->providerRepository);

        return $table->render();
    }

}