<?php

namespace Application\Service\Extension\Params;

use Application\Service\DB\Dictionary\FormField;
use Application\Service\Extension\Helper\DataHelper;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Helper\StringHelper;
use Exception;

/**
 */
class ParamSet
{
    protected $_value = null;
    protected $_key = null;

    public function __construct($key, $value)
    {
        $this->_key = $key;
        $this->_value = $value;
    }

    public function toArray()
    {
        return StringHelper::jsonDecode($this->_value);
    }

    public function value()
    {
        return $this->_value;
    }

    /**
     * 如果是字段的话, 是什么类型的
     */
    public function formatValue()
    {
        if ($this->type() == FormField::FORM_FIELD_TYPE_CHECKBOX && !is_array($this->value())) {
            $val = explode(',', $this->value());
            sort($val);
            return $val;
        }

        return $this->value();
    }

    public function key(): ?string
    {
        return $this->_key;
    }

    /**
     * 检查是否是锚点时间
     *
     * @return bool 如果当前版本的表单被设置为锚点时间，则返回true；否则返回false
     * @throws Exception 如果无法获取表单ID，则抛出异常
     */
    public function isAnchorTime(): bool
    {
        $version = SDMHelper::app()->form->getVersionData(Params::app()->must()->formId);

        return isset($version[$this->key()]['is_anchor']) && $version[$this->key()]['is_anchor'] == 1;
    }

    public function isBookedTime(int $formId = null): bool
    {
        $version = SDMHelper::app()->form->getVersionData(Params::app()->must()->formId);
        return isset($version[$this->key()]) && $version[$this->key()]['is_booked_time'] == 1;
    }

    public function isField()
    {
        return DataHelper::isField($this->key());
    }

    /**
     * 获取字段ID.
     * 主要获取被关联的字段的字段id。
     * `123-456` => `123`
     *
     * @return mixed 返回字段ID，具体类型取决于DataHelper::getFieldId方法的返回值
     */
    public function fieldId()
    {
        return DataHelper::getFieldId($this->key());
    }

    /**
     * 是否有关联的子表单
     */
    public function isParentForm(): bool
    {
        $version = SDMHelper::app()->form->getVersionData(Params::app()->formId);

        return isset($version[$this->fieldId()]) || !isset($version[$this->fieldId()]['children']);
    }

    public function type()
    {
        $version = SDMHelper::app()->form->getVersionData(Params::app()->formId);

        if (!$this->isField()) {
            return false;
        }

        return $version[$this->fieldId()]['type'] ?? false;
    }
}