<?php

namespace Application\Service\Extension\Logger;

use Application\Service\DB\Item\PatientFormContent;
use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Extension;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Params\Params;
use Application\Service\Extension\Store\Store;
use Application\Service\FormModels\FormEvent;

class FormContentLogger extends BaseLogger
{
    private ?int $__formContentPrimaryKey = null;

    public function setFormContentPrimaryKey(int $formContentPrimaryKey): FormContentLogger
    {
        $this->__formContentPrimaryKey = $formContentPrimaryKey;
        return $this;
    }

    public function flush()
    {
        if ($this->__formContentPrimaryKey === null) {
            throw new InvalidArgumentException('保存日志失败。请先设置formContentPrimaryKey属性。');
        }

        try {
            Laminas::$serviceManager->patientFormContentUpdatedLog->save($this->getFLushContent());
        } catch (\Exception $exception) {
            throw new \Exception('保存日志出错啦!!!!!' . $exception->getMessage());
        }
    }

    /**
     * 获取存储日志的内容
     * @param array $content
     * @return array
     * @throws \Exception
     */
    public function getFLushContent(array $content = []): array
    {
        $content = Laminas::$serviceManager->patientFormContent->store()->find($this->__formContentPrimaryKey);
        $changeData = $this->getChangeData();
        return [
            'item_id' => Params::app()->itemId,
            'patient_id' => Params::app()->patientId,
            'form_id' => Params::app()->formId,
            'sign_id' => Params::app()->signId,
            'checktime_id' => Params::app()->checkTimeId,
            'content_id' => $this->__formContentPrimaryKey,
            'data' => json_encode(Params::app()->getValuesToArray()), // 已经处理后的post数据
            'source' => Laminas::$serviceManager->identity->getPlatform() ?? 'SCRIPT',
            'event' => Store::app()->get('event'),
            'change_data' => $this->isChangeStr ? json_encode($changeData) : '[]',
            'change_data_str' => $this->isChangeStr ? $this->getChangeDataStr($changeData) : '[]',
            'json' => json_encode([
                'behavior' => SDMHelper::app()->log->getBehavior(),
                'post' => $this->postOriginData ?: [],
                'headers' => Laminas::$app->getRequest()->getHeaders()->toArray() ?? [],
                'identity' => Laminas::$serviceManager->identity->getIdentityData() ?? [],
                'attach' => LogHelper::$attach,
                'message' => $this->getMessage()
            ]),
        ];
    }

    private function getChangeData()
    {
        $postData = Params::app()->getValuesToArray();

        $lastPostData = Store::app()->toParams()->dbFind(PatientFormContent::class, $this->__formContentPrimaryKey)->toArray()->data;

        return $this->compareValue($lastPostData, $postData);
    }
}