<?php

namespace Application\Service\Extension\Formatter;


use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Laminas;
use Laminas\Db\ResultSet\ResultSet;
use Laminas\Db\Sql\Expression;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Db\Sql\Sql;

class FormViewFormatter extends BaseFormatter
{
    public function __construct()
    {
        $this->registerHandler([
            'reference_file' => 'referenceFileHandler',
            'except_checktime' => 'exceptCheckTimeHandler',
            'ds_stage' => 'dsStageHandler',
        ]);
    }

    public function referenceFileHandler($value)
    {
        $value = json_decode($value ?: '[]', true);
        Formatter::formatUploadFile($value);
        return $value;
    }

    public function exceptCheckTimeHandler($value)
    {
        $itemId = $_POST['item_id'];

        $allCheckTime = Laminas::$serviceManager->itemChecktime->fetchAll([
            'columns' => ['id'],
            'where' => ['item_id' => $itemId]
        ]);

        $exceptCheckTime = explode(',', $value);

        if (!$exceptCheckTime) {
            return ArrayHelper::getColumn($allCheckTime, 'id');
        }

        foreach ($allCheckTime as $key => $item) {
            if (in_array($item['id'], $exceptCheckTime)) {
                unset($allCheckTime[$key]);
            }
        }

        return ArrayHelper::getColumn(array_values($allCheckTime), 'id');
    }

    public function dsStageHandler($value)
    {
        return explode(',', $value);
    }
}