<?php

namespace Application\Service\Extension\Expression;

use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;

class FormDataProvider
{
    public static ?FormDataProvider $instance = null;

    public static array $dataContainer = [];

    public static function get(string $path)
    {
        if (!self::$instance) {
            self::$instance = new self();
        }
        self::_initializeDataContainer($path);
        return ArrayHelper::getValue(self::$dataContainer, $path);
    }

    private static function _initializeDataContainer(string $path)
    {
        $ex = explode('.', $path);
        if (count($ex) < 2) {
            return;
        }

        list($checkTimeVar, $formVar) = explode('.', $path);
        if (!isset(self::$dataContainer[$checkTimeVar][$formVar])) {
            self::$dataContainer[$checkTimeVar][$formVar] = self::$instance->getContent($checkTimeVar, $formVar);
        }
    }

    public function getContent(string $checkTimeVar, string $formVar)
    {
        $data = [];
        $fetchData = Laminas::$serviceManager->patientFormContent->fetchOne([
            'where' => [
                'form_id' => self::$instance->getFormId($formVar),
                'checktime_id' => self::$instance->getCheckTimeId($checkTimeVar),
                'is_del' => 0,
                'patient_id' => Laminas::$serviceManager->request->getPost('patient_id'),
            ]
        ]);
        if ($fetchData) {
            $data = StringHelper::jsonDecode($fetchData['data']);
        }

        return new \ArrayObject($data, \ArrayObject::ARRAY_AS_PROPS);
    }

    public function getCheckTimeId(string $checkTimeVar)
    {
        $id = Laminas::$serviceManager->itemChecktime->fetchOne([
            'where' => ['var_name' => $checkTimeVar, 'item_id' => Laminas::$serviceManager->request->getPost('item_id')]
        ])['id'] ?? false;
        if (!$id) {
            throw new \Exception("$checkTimeVar 不对把..");
        }

        return $id;
    }

    public function getFormId(string $formVar)
    {
        $id = Laminas::$serviceManager->itemForm->fetchOne([
                'where' => ['var_name' => $formVar, 'item_id' => Laminas::$serviceManager->request->getPost('item_id')]
            ])['id'] ?? false;
        if (!$id) {
            throw new \Exception("$formVar 不对把..");
        }

        return $id;
    }
}