<?php

namespace Application\Form\item;


use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Laminas;

class ItemFormModel extends FormForm
{
    public function getOutFormPreview($version = 'v1')
    {
        $method = ($version == 'v1' ? 'getOutForm' : 'getOutFormV2');
        $outFormData = Laminas::$serviceManager->itemForm->{$method}($this->validator->attributes['item_id'], $this->validator->attributes['patient_status']);

        if (!$outFormData) {
            throw new InvalidArgumentException('暂无需填写表单！');
        }

        $checkTimeId = Laminas::$serviceManager->itemChecktime->getOutCheckTimeId($this->validator->attributes['item_id']);
        if ($version == 'v2') {
            $res = [];
            foreach ($outFormData as $formItem) {
                // 是否已经填写
                $isWrite = (bool)Laminas::$serviceManager->patientFormContent->fetchOne([
                    'where' => [
                        'is_del' => 0,
                        'patient_id' => $this->validator->attributes['patient_id'],
                        'form_id' => $formItem['id'],
                        'checktime_id' => $checkTimeId]
                ]);

                // 完成状态
                $isComplete = $isWrite === false ? 0 : $this->getIsComplete($formItem['id'], $checkTimeId);

                $res[] = ArrayHelper::merge(Laminas::$serviceManager->itemForm->getPreviewConfig($formItem['id']), [
                        'type' => $formItem['type'],
                        'show_type' => $formItem['show_type'] ?: 'right',
                        'title' => $formItem['name'],
                        'form_id' => $formItem['id'],
                        'is_write' => $isWrite,
                        'is_complete' => intval($isComplete),
                        // 1 完成  3 未完成 2 未填写
                        'status_color' =>  $isWrite === false ? 2 : (intval($isComplete) ? 1 : 3)
                    ]);
            }

            return $res;
        }

        return ArrayHelper::merge(
            Laminas::$serviceManager->itemForm->getPreviewConfig($outFormData['id']),
            [
                'type' => $outFormData['type'],
                'show_type' => $outFormData['show_type'] ?: 'right',
            ]
        );
    }


    public function getIsComplete($form_id, $checkTimeId = false)
    {
        return Laminas::$serviceManager->patientForm->fetchOne([
                'where' => [
                    'form_id' => $form_id,
                    'patient_id' => $this->validator->attributes['patient_id'],
                    'is_del' => 0,
                    'checktime_id' => $checkTimeId ?: $this->validator->attributes['patient_id']
                ]
            ])['is_complete'] ?? 0;
    }
}
