<?php


namespace Shop\Presentation\Modules\AdminShops;


use Core\Form\Control\Switchery;
use Core\Form\ControlBuilder;
use Diamond\Helpers\Form;
use Shop\Domain\Stock\Contracts\StockEntityInterface;
use Shop\Presentation\Helpers\Text;
use Shop\Infrastructure\Models\PriceAccess\PriceAccessQuery;
use Shop\Infrastructure\Models\PricelistSheet\PricelistSheet;

trait ColumnFormatTrait
{
    /**
     * @var ControlBuilder
     */
    protected $controlBuilder;

    /**
     * @param StockEntityInterface $stock
     * @return string
     */
    public function formatImages(StockEntityInterface $stock): string
    {
        $found = 0;
        if ($stock->getLogo()) {
            $found++;
        }
        if ($stock->getImage()) {
            $found++;
        }

        return $found > 1 ? Form::buildIcon('images') : ($found > 0 ? Form::buildIcon('image') : '');
    }

    public function formatGeo(StockEntityInterface $shop): string
    {
        if(!$shop->getAddress()){
            return '';
        }
        
        return $shop->getAddress()->getMapLng()>0 && $shop->getAddress()->getMapLat() > 0
            ?Form::buildSpriteIcon('geo')
            :'';
    }

    public function formatActive(StockEntityInterface $stock): string
    {
        $data = [
            'class' => self::class,
            'id' => $stock->getId(),
            'fn' => 'changeActive'
        ];
        return (new Switchery($data, $stock->getActive()))->render();
    }

    public function changeActive(int $id, bool $checked): void
    {
        $model = $this->stockRepository->findById($id);
        $model->setActive($checked);
        $this->stockRepository->save($model);
    }

    /**
     * @param StockEntityInterface $stock
     * @return string
     */
    public function formatManagersCount(StockEntityInterface $stock): string
    {

        if (!$count = $stock->countManagers()) {
            return '';
        }

        ///admin/shop/stocks/managers?search_by_name=&search_by_email=&filter_by_stockId=74&filter=1
        $manager = $stock->getManagers()->getFirst();

        if ($manager) {
            return anchor('/admin/shop/stocks/managers', $manager->getName() . ($count > 1 ? ',...' : ''), [], [
                'filter_by_stockId' => $stock->getId(),
                'filter' => 1
            ]);
        }


        return $count;
    }

    /**
     * @param StockEntityInterface $shop
     * @return string
     */
    public function formatContact(StockEntityInterface $shop): string
    {
        if (!$shop->getPhones()) {
            return '';
        }
        return Text::clearText($shop->getPhones(), 130);
    }

    /**
     * @param StockEntityInterface $shop
     * @return mixed
     */
    public function formatAddress(StockEntityInterface $shop): string
    {
        return $shop->getFullAddress();
    }


    /**
     * @param StockEntityInterface $shop
     * @return string
     */
    public function formatName(StockEntityInterface $shop): string
    {
        return $shop->getCountChildrens() > 0 ?
            '<i class="sprite folder interval10right"></i>' .
            $shop->getTitle() : ($shop->getParentId() > 0 ? nbs(7) : '') . $shop->getTitle();
    }


    /**
     * @param StockEntityInterface $shop
     * @return string
     */
    public function formatContractor(StockEntityInterface $shop): string
    {
        /**
         * @var Customer $contractor
         */
        if ($shop->getContractorId() > 0) {
            $contractor = $shop->getContractor();
            $name = $contractor->getName();


            return anchor('/admin/shop/stocks/contractors', $name, [], [
                'fn' => 'edit',
                'id' => $contractor->getId()
            ]);
        }
        return Form::buildIcon('alert', 'Контрагент не определен.');
    }


    public function formatType(StockEntityInterface $shop): string
    {
        return $shop->getTypeDisplay();
    }

    /**
     * @param StockEntityInterface $shop
     * @return string
     */
    public function formatPriceAccess(StockEntityInterface $shop): string
    {
        $results = PriceAccessQuery::create()->filterByShopId($shop->getId())->find();
        $txt = '';
        foreach ($results as $res) {

            /** @var PricelistSheet $price */
            if (!$price = $this->priceListRepository->findById((int)$res->getPriceScheetId())) {
                continue;
            }

            $txt .= $price->getTitle() . ' (' .$price->getPositions()->count(). ' поз.), ';
        }

        $txt = rtrim($txt, ', ');

        if (empty($txt)) {
            return '';
        }

        $priceList = array_filter(explode(',', $txt));

        return Text::toggleList($priceList);
    }

}