<?php

namespace Application\Service\Extension\Formatter;


use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Laminas;
use Laminas\Db\Sql\Predicate\Between;

class FormFormatter extends BaseFormatter
{
    protected ?int $minField = null;

    protected ?int $maxField = null;

    public function __construct()
    {
        $this->registerHandler([
            'type' => 'typeHandler',
            'group_id' => 'groupIdHandler',
            'parent' => 'parentHandler'
        ]);
    }

    protected function getForm()
    {
        return Laminas::$serviceManager->dictionaryForm;
    }

    protected function getFormField()
    {
        return Laminas::$serviceManager->dictionaryFormField;
    }

    protected function getFormFieldRadio()
    {
        return Laminas::$serviceManager->dictionaryFormFieldRadio;
    }

    protected function setFieldValue($itemId)
    {
        if (!$this->minField || !$this->maxField) {
            if ($itemId) {
                $allFormId = $this->getForm()->memoryCache()->fetchCol('id', ['item_id' => $itemId]);

                $fieldId = ArrayHelper::getColumn($this->getFormField()->memoryCache()->fetchAll([
                    'columns' => ['id'],
                    'where' => [
                        'form_id' => $allFormId
                    ]
                ]), 'id');
                sort($fieldId);
                $this->minField = reset($fieldId);
                $this->maxField = end($fieldId);
            }
        }
    }

    public function typeHandler($value): string
    {
        return $value == 1 ? '1对多' : '1对1';
    }

    public function groupIdHandler($value)
    {
        return Laminas::$serviceManager->dictionaryFormGroup->fetchOne([
            'where' => [
                'id' => $value
            ]
        ])['name'] ?? 'error';
    }

    public function parentHandler($value, $item)
    {
        $this->setFieldValue($item['item_id']);
        $condition = [
//                'field_id' => $id,
            'relation_classification' => 1,
            new \Laminas\Db\Sql\Predicate\Expression("FIND_IN_SET($value, relation_information)")
        ];

        if ($this->minField) {
            $condition[] = new Between('field_id', $this->minField, $this->maxField);
        }
        $formId =  array_unique(ArrayHelper::getColumn($this->getFormFieldRadio()->fetchAll([
            'columns' => ['form_id'],
            'where' => $condition
        ]), 'form_id'));

        return call_user_func(function () use ($formId) {
            $res = [];
            foreach ($formId as $k => $item) {
                $label = $this->getForm()->fetchOne(['where' => ['id' => $item, 'is_del' => 0]])['name'] ?? '';

                if ($label) {
                    $res[$k] = [
                        'id' => $item,
                        'label' => $label,
                    ];
                }
            }

            return $res;
        });
    }
}
