<?php

namespace Shop\Presentation\Modules\AdminComplexRates;

use ActiveTable\ColumnTable;
use ActiveTable\DataTableEngine;
use Core\Form\ControlBuilder;
use Core\Form\FormBuilder;
use Core\Form\Simpleform;
use Diamond\Helpers\Form;
use DiamondTable\TableFactory;


use Core\Form\RepoForm;
use Core\Registry\Column;
use Core\Registry\Field;
use Core\Registry\RepoRegisry;

use Shop\Repositories\Brand\BrandCriteria;
use Shop\Repositories\Brand\BrandRepository;
use Shop\Repositories\Category;
use Shop\Repositories\ComplexRate\ComplexRateCriteria;
use Shop\Repositories\Customer\CustomerCriteria;
use Shop\Repositories\Customer\CustomerRepository;
use Shop\Repositories\CustomerGroup\CustomerGroupCriteria;
use Shop\Repositories\CustomerGroup\CustomerGroupRepository;
use Shop\Repositories\PriceList\PriceListCriteria;
use Shop\Repositories\PriceList\PriceListRepository;
use Shop\Repositories\ProductCategory\ProductCategoryCriteria;
use Shop\Repositories\ProductCategory\ProductCategoryRepository;
use Shop\Repositories\Stock\StockCriteria;
use Shop\Repositories\Stock\StockRepository;

/**
 * Description of AdminComplexRates
 * @todo добавить город страну регион
 * @author Diamond Code Generator
 */
class AdminComplexRates extends \Core\ModuleController
{

    protected $repo;
    protected $tableFactory;
    protected $cBuilder;
    protected $brandRepo;
    protected $groupRepo;
    protected $customerRepo;
    protected $shopRepo;
    protected $pricelistSheetRepo;
    protected $categoryRepo;

    /**
     * AdminComplexRates constructor.
     * @param TableFactory $tableFactory
     * @param \Core\Form\ControlBuilder $cBuilder
     * @param \Shop\Repositories\ComplexRate\ComplexRateRepository $repo
     * @param \Shop\Repositories\Brand $brandRepo
     * @param \Shop\Repositories\CustomerGroup $groupRepo
     * @param \Shop\Repositories\Customer $customerRepo
     * @param \Shop\Repositories\Shop $shopRepo
     * @param \Shop\Repositories\PricelistSheet $pricelistSheetRepo
     * @param Category $categoryRepo
     */
    public function __construct(TableFactory $tableFactory,
                                \Core\Form\ControlBuilder $cBuilder,
                                \Shop\Repositories\ComplexRate\ComplexRateRepository $repo,
                                BrandRepository $brandRepo,
                                CustomerGroupRepository $groupRepo,
                                CustomerRepository $customerRepo,
                                StockRepository $shopRepo,
                                PriceListRepository $pricelistSheetRepo,
                                ProductCategoryRepository $categoryRepo)
    {
        $this->tableFactory = $tableFactory;
        $this->repo = $repo;
        $this->cBuilder = $cBuilder;
        $this->brandRepo = $brandRepo;
        $this->customerRepo = $customerRepo;
        $this->groupRepo = $groupRepo;
        $this->shopRepo = $shopRepo;
        $this->pricelistSheetRepo = $pricelistSheetRepo;
        $this->categoryRepo = $categoryRepo;
    }

    public function process(): string
    {


        $table = $this->tableFactory->buildAdminTable($this->repo, ComplexRateCriteria::create());

        $table
            ->addColumn(new ColumnTable("id", "№"))
            ->addColumn(
                (new ColumnTable("brandId", "Производитель"))
                    ->setFormat($this, "formatBrand"))
            ->addColumn(
                (new ColumnTable("customerGroupId", "Группа клиента"))
                    ->setFormat($this, "formatGroup"))
            ->addColumn(
                (new ColumnTable("customerId", "Клиент"))
                    ->setFormat($this, "formatCustomer"))
            ->addColumn(
                (new ColumnTable("shopId", "Офис"))
                    ->setFormat($this, "formatShop"))
            ->addColumn(
                (new ColumnTable("pricelistSheetId", "Прайс-лист"))
                    ->setFormat($this, "formatPriceList"))
            ->addColumn(
                (new ColumnTable("categoryId", "Категория товара"))
                    ->setFormat($this, "formatCategory"))
            ->addColumn(
                (new ColumnTable("rate", "Скидка/Наценка,%"))
                    ->setFormat($this, "formatRate"))
            ->addColumn(new ColumnTable("priority", "Приоритет"))
            ->addColumn(
                (new ColumnTable("active", "Активна"))
                    ->setFormat($this, "formatActive"))
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setFormat($this->tableFactory, 'formatActions')
                    ->setWidth(120)
            );

        $bransCol = $this->brandRepo->findByCriteria(
            BrandCriteria::create()
        );
        $groupsCol = $this->groupRepo->findByCriteria(
            CustomerGroupCriteria::create()
        );

        $customerCol = $this->customerRepo->findByCriteria(
          CustomerCriteria::create()
        );
        $shopsCol = $this->shopRepo->findByCriteria(
          StockCriteria::create()
        );
        $priceCol = $this->pricelistSheetRepo->findByCriteria(
            PriceListCriteria::create()
        );
        $categoriesCol = $this->categoryRepo->findByCriteria(
          ProductCategoryCriteria::create()
        );

        $brands = \Shop\Helpers\Form::prepareDropdownWithDef($bransCol, "%", "производитель");
        $groups = \Shop\Helpers\Form::prepareDropdownWithDef($groupsCol, "%", "группа клиента");
        $customers = \Shop\Helpers\Form::prepareDropdownWithDef($customerCol, "%", "клиент");
        $shops = \Shop\Helpers\Form::prepareDropdownWithDef($shopsCol, "%", "офис");
        $prices = \Shop\Helpers\Form::prepareDropdownWithDef($priceCol, "%", "прайс-лист");
        $categories = \Shop\Helpers\Form::prepareDropdownWithDef($categoriesCol, "%", "категорию товара", "getDropdownListWithParent");

        $pri = [];
        for ($pr = 0; $pr <= 100; $pr++) {
            $pri [] = $pr;
        }

        $table
            ->addField(
                $this->cBuilder
                    ->buildInputLittle("rate"), true, null, "пример: 15.5% -наценка, -20.5% -скидка"
            )
            ->addField(

                $this->cBuilder
                    ->buildAutoDropdown("brandId", $brands)
            )
            ->addField(
                $this->cBuilder
                    ->buildDropdownUniform("customerGroupId", $groups)
            )
            ->addField(
                $this->cBuilder
                    ->buildAutoDropdown("customerId", $customers)
            )
            ->addField(
                $this->cBuilder
                    ->buildAutoDropdown("shopId", $shops)
            )
            ->addField(
                $this->cBuilder
                    ->buildAutoDropdown("pricelistSheetId", $prices)
            )
            ->addField(
                $this->cBuilder
                    ->buildAutoDropdown("categoryId", $categories)
            )
            ->addField(
                $this->cBuilder
                    ->buildDropdownUniform("priority", $pri)
            )
            ->addField(
                $this->cBuilder
                    ->buildDropdownYNDigitUniform("active")
            );

        return $table->render();
    }


    /**
     *
     * @param \Shop\Models\ComplexRate\ComplexRate $rate
     * @return type
     */
    public function formatPriceList(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        if ($rate->getPricelistSheetId() > 0 && $list = $this->pricelistSheetRepo->findById($rate->getPricelistSheetId())) {
            return $list->getTitle();
        }

        return $rate->getPricelistSheetId();
    }

    /**
     *
     * @param \Shop\Models\ComplexRate\ComplexRate $rate
     */
    public function formatBrand(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        if ($rate->getBrandId() > 0 && $brand = $this->brandRepo->findById($rate->getBrandId())) {
            return $brand->getName();
        }

        return $rate->getBrandId();
    }

    /**
     *
     * @param \Shop\Models\ComplexRate\ComplexRate $rate
     */
    public function formatGroup(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        if ($rate->getCustomerGroupId() > 0 && $group = $this->groupRepo->findById($rate->getCustomerGroupId())) {
            return $group->getName();
        }


        return $rate->getCustomerGroupId();
    }

    /**
     *
     * @param \Shop\Models\ComplexRate\ComplexRate $rate
     */
    public function formatCustomer(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        if ($rate->getCustomerId() > 0 && $customer = $this->customerRepo->findById($rate->getCustomerId())) {
            return $customer->getName();
        }

        return $rate->getCustomerId();
    }

    /**
     *
     * @param \Shop\Models\ComplexRate\ComplexRate $rate
     */
    public function formatShop(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        if ($rate->getShopId() > 0 && $shop = $this->shopRepo->findById($rate->getShopId())) {
            return $shop->getTitle();
        }

        return $rate->getShopId();
    }

    public function formatCategory(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        /**
         * @var \Shop\Models\Category\Category $category
         */
        if ($rate->getCategoryId() > 0 && $category = $this->categoryRepo->findById($rate->getCategoryId())) {
            return $category->getnameWithParent();
        }

        return $rate->getCategoryId();
    }

    /**
     *
     * @param \Shop\Models\ComplexRate\ComplexRate $rate
     */
    public function formatRate(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        return $rate->getRate();
    }

    public function formatActive(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        return $rate->getActive() === 1 ? "Да" : "Нет";
    }

}