<?php

namespace Application\Service\Extension\CheckLogic;

use Application\Service\DB\AbstractDb;
use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\Extension\Helper\DataHelper;
use Application\Service\Extension\Laminas;

class FormContentProvider extends BaseContentProvider
{
    public function get()
    {
        // OCR 类型检查日期
        if ($this->getFormGroupId() == FormGroup::CHECK_OCR && $this->fieldVarName == 'OCR_CHECK_TIME') {
            $hasResult = Laminas::$serviceManager->itemIdentificationresultchange->fetchOne([
                'columns' => ['collect_date'],
                'where' => [
                    'is_del' => 0,
                    'patient_id' => $this->getPatientId(),
                    'item_id' => $this->getItemId(),
                    'checktime_id' => $this->checkTimeId,
                ]
            ]);

            // 没有图片, 或者是还没识别??
            if (!$hasResult) {
                throw new NotWriteCheckTimeException('当前化验单暂未发现识别结果');
            }
            $val = CheckLogicApplication::formatVal(-1, $hasResult['collect_date']);
            CheckLogicApplication::debugPrint("字段名称: 检查日期");
            CheckLogicApplication::debugPrint("字段类型: 2");
            CheckLogicApplication::debugPrint("原始数据: {$hasResult['collect_date']}");
        } else {
            // 如果是一对多的, 需要指定id
            if ($this->getMultiId() && $GLOBALS['generator']->multiFormId == $this->getFormId()) {
                $condition = [
                    'id' => $this->getMultiId(),
                    'is_del' => 0
                ];
            } else {
                $condition = [
                    'form_id' => $this->getFormId(),
                    'patient_id' => $this->getPatientId(),
                    'checktime_id' => $this->checkTimeId,
                    'is_del' => 0
                ];
            }

            // 贯穿全程
            if ($this->checkTimeId === 0) {
                unset($condition['checktime_id']);
            }

            $contentData = $this->getContent('patientFormContent', $condition);

            $val = CheckLogicApplication::formatVal($this->getFieldType(), $this->getVal($contentData, $this->getFieldId()));
            CheckLogicApplication::debugPrint("字段名称: {$this->getFieldData()['name']}");
            CheckLogicApplication::debugPrint("字段类型: {$this->getFieldType()}");
            CheckLogicApplication::debugPrint("原始数据: {$this->getVal($contentData, $this->getFieldId())}");
        }
        CheckLogicApplication::debugPrint("转换后数据: {$val}");

        // 填写了表单, 但是是空值, 并且不跳过空值的异常处理
        if ($val === '' ) {
            if ($this->isSkipEmptyException === true) {
                return true;
            }

            if ($this->isSkipEmptyException === false) {
                throw new NotWriteCheckTimeException('表单填写了, 但值为空。');
            }
        }

        return $val;
    }
}