<?php

namespace Application\Service\Extension\Middleware\components;

use Application\Form\item\patient\PatientFormModel;
use Application\Service\DB\Dictionary\Form;
use Application\Service\DB\Dictionary\FormField;
use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\DB\Item\PatientFormContentImg;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\DataHelper;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Middleware\BaseMiddlewareComponent;
use Application\Common\EventEnumV2;

/**
 * 处理表单图片。
 * 存到对应的图片中间表。
 */
class HandleFormImages extends BaseMiddlewareComponent
{
    /** @var PatientFormModel */
    public $owner;

    private array $versionData = [];

    function execute()
    {
        $this->versionData = $this->h()->form->getVersionData($this->owner->formId);
        $indexVersionData = [];
        $isDelete = $shareIsDelete = $isProcessDO = false;
 
        if (SDMHelper::app()->form->getGroupId($this->owner->formId) == FormGroup::NORMAL_OCR && SDMHelper::app()->form->getType($this->owner->formId) == Form::FORM_TYPE_MULTI) {
            return;
        }

        // 先清理掉所有图片
        $this->flushAllImages();
        foreach ($this->owner->postData as $field => $item) {
            $fieldId = DataHelper::getFieldId($field);
            if (isset($this->versionData[$fieldId])) {
                if (in_array($this->versionData[$fieldId]['type'], [FormField::FORM_FIELD_TYPE_UPLOAD_IMAGE, FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE])) {
                    $this->handleImg($this->versionData[$fieldId]['type'], $fieldId, $item);
                }
            }
        }
    }

    protected function flushAllImages()
    {
        if(in_array($this->owner->event, [
            EventEnumV2::getVal(EventEnumV2::EVENT_FORM_CONTENT_EDIT_BY_LOGIC_REPLY)
        ])) return ;

        $con = [];

        // 把所有图片先都删掉
        if (isset(ArrayHelper::index($this->versionData, 'type')[FormField::FORM_FIELD_TYPE_UPLOAD_IMAGE])) {
            // 把所有图片先都删掉
            $con = [
                'item_id' => $this->owner->validator->attributes['item_id'],
                'itemsig_id' => $this->owner->validator->attributes['itemsig_id'],
                'patient_id' => $this->owner->validator->attributes['patient_id'],
                'form_id' => $this->owner->validator->attributes['form_id'],
                'checktime_id' => $this->owner->validator->attributes['checktime_id'], // 贯穿全程
                'content_id' => $this->owner->contentPrimaryKey,
            ];

            if ($this->h()->form->getIsProcess($this->owner->formId)) {
                unset($con['content_id']);
                unset($con['checktime_id']);
            }

        }

        // 常规识别
        if (SDMHelper::app()->form->getGroupId($this->owner->formId) == FormGroup::NORMAL_OCR) {
            // 把所有图片先都删掉
            $con = [
                'item_id' => $this->owner->validator->attributes['item_id'],
                'itemsig_id' => $this->owner->validator->attributes['itemsig_id'],
                'patient_id' => $this->owner->validator->attributes['patient_id'],
                'form_id' => ArrayHelper::getColumn(SDMHelper::app()->form->getGcoGroupForm($this->owner->validator->attributes['form_id']), 'id'),
                'checktime_id' => $this->owner->validator->attributes['checktime_id'],
            ];
        }

        if ($this->h()->form->getIsProcess($this->owner->formId)) {
            unset($con['content_id']);
            unset($con['checktime_id']);
        }

        if ($con) {
            // 把所有旧数据都清理掉
            $effect = Laminas::$serviceManager->patientFormContentImg->update(['is_del' => 1], $con);
        }
    }

    protected function handleImg(int $type, int $fieldId, $imagesValue)
    {
        $imageType = PatientFormContentImg::IMG_TYPE_NORMAL;
        if ($this->h()->form->getGroupId($this->owner->formId) == FormGroup::CHECK_OCR) {
            $imageType = $this->owner->getFieldType($this->versionData[$fieldId]);
        }

        if (is_array($imagesValue)) {
            $images = $imagesValue;
        } else {
            // 可能没用了
            $images = StringHelper::jsonDecode($imagesValue) ?: [];
        }

        // 重新写入图片
        foreach ($images as $image) {
            $condition = $this->getCondition($type, $fieldId, $image, $imageType);

            $hasImg = Laminas::$serviceManager->patientFormContentImg->fetchOne([
                'where' => $condition
            ]);

            $this->save($hasImg, $condition);
        }
    }

    protected function getCondition(int $fieldType, int $fieldId , array $image, int $imageType): array
    {
        $src = DataHelper::handleImageSrc($image['url']);

        if ($fieldType == FormField::FORM_FIELD_TYPE_UPLOAD_IMAGE) {
            $condition = [
                'item_id' => $this->owner->validator->attributes['item_id'],
                'itemsig_id' => $this->owner->validator->attributes['itemsig_id'],
                'patient_id' => $this->owner->validator->attributes['patient_id'],
                'form_id' => $this->owner->validator->attributes['form_id'],
                'checktime_id' => $this->owner->validator->attributes['checktime_id'],
                'img_src' => $src,
                'img_name' => $image['name'] ?? '',
                'img_type' => $imageType,
                'content_id' => $this->owner->contentPrimaryKey,
                'field_id' => $fieldId
            ];
        }

        if ($fieldType == FormField::FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE) {
            $condition = [
                'item_id' => $this->owner->validator->attributes['item_id'],
                'itemsig_id' => $this->owner->validator->attributes['itemsig_id'],
                'patient_id' => $this->owner->validator->attributes['patient_id'],
                'form_id' => $this->owner->validator->attributes['form_id'],
                'checktime_id' => $this->owner->validator->attributes['checktime_id'],
                'img_src' => $src,
                'img_type' => PatientFormContentImg::IMG_TYPE_NORMAL,
                'is_form_ocr' => 1,
                'field_id' => $fieldId,
                'is_ocr' => 0,
                'content_id' => $this->owner->contentPrimaryKey,
                'gco_pool' => SDMHelper::app()->form->getGcoPool($this->owner->formId),
                'info_collect_type' => SDMHelper::app()->form->getInfoCollectType($this->owner->formId),
                'is_lock' => SDMHelper::app()->formContent->getIsLock($this->owner->contentPrimaryKey)
            ];
            //增加病例库附件ID
            if(isset($image['collect_annex_id']) && !empty($image['collect_annex_id'])){
                $condition['collect_annex_id'] = $image['collect_annex_id'];
            }
            //增加附件名称
            if(isset($image['name']) && $image['name'] != ''){
                $condition['img_name'] = $image['name'];
            }
        }

        if (SDMHelper::app()->form->getIsProcess($this->owner->formId)) {
            unset($condition['checktime_id']);
            unset($condition['content_id']);
        }

        return $condition;
    }

    protected function save($hasImg, $condition)
    {
        // 没有就insert, 有就把is_del 改成0
        if (!$hasImg) {
            Laminas::$serviceManager->patientFormContentImg->save($condition);
        } else {
            Laminas::$serviceManager->patientFormContentImg->update(['is_del' => 0], ['id' => $hasImg['id']]);
        }
    }
}