<?php

namespace Application\Service\Extension\ArkSync;

use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\Extension\Helper\CurlHelper;
use Application\Service\Extension\Helper\LogHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Helper\SyncPatientHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Xml\FormContentXmlGenerator;
use Application\Service\Extension\Xml\XmlBuilder;

class ArkSyncApplication
{
    public int $patientId = 0;

    public string $itemSignId = '0';

    public int $itemId = 0;

    public int $formId = 0;

    public int $checkTimeId = 0;

    /**
     * 删除指定的表单id
     * 一对多才生效
     * @var int
     */
    public int $deleteMultiId = 0;

    public function execute(array $params = [])
    {
        // 初始化参数
        foreach ($params as $paramKey => $param) {
            if (property_exists($this, $paramKey)) {
                $this->{$paramKey} = $param;
            }
        }

        $startTime = microtime(true);

        $xmlGenerator = new FormContentXmlGenerator();
        $xmlGenerator->patientId = $this->patientId;
        $xmlGenerator->itemSignId = $this->itemSignId;
        $xmlGenerator->itemId = $this->itemId;
        $xmlGenerator->formId = $this->formId;
        $xmlGenerator->checkTimeId = $this->checkTimeId;

        if ($xmlGenerator->isSync() === false || $xmlGenerator->getFormContent('fetchOne', false) === false) {
            return;
        }

        $xmlGenerator->formContent = [];

        if ($this->deleteMultiId !== 0) {
            $xmlGenerator->deleteMultiId($this->deleteMultiId);
        }

        $xml = $xmlGenerator->generate();

        $builder = new XmlBuilder();

        $record = json_encode($builder->build($xml), JSON_UNESCAPED_SLASHES);

        $generateTime = microtime(true) - $startTime;

        $requestStartTime = microtime(true);

        $response = CurlHelper::syncArkEdc($record);

        $isJson = StringHelper::jsonDecode($response, false);

        // 对方没有给我返回一个JSON格式的数据
        if (!$isJson) {
            LogHelper::save([
                'msg' => '数据同步失败了, 好像那面报错了.',
                'ODMResponseData' => $isJson,
                'requestData' => $record,
            ], 'ERROR', 'syncODMPatient[ERROR]');
            return;
        }

        if ($isJson['statusCode'] != 200) {
            LogHelper::save([
                'msg' => '数据同步失败了, 返回不是200的状态码.',
                'ODMResponseData' => $isJson,
                'requestData' => $record,
            ], 'WARNING', 'syncODMPatient[WARNING]');
            return;
        }

        LogHelper::save([
            'msg' => '数据同步成功了.',
            'ODMResponseData' => $isJson,
            'requestData' => $record,
            'generateTime' => $generateTime,
            'requestTime' => microtime(true) - $requestStartTime,
        ], 'INFO', 'syncODMPatient');
//
//            // 记录受试者同步状态
        SyncPatientHelper::setIsSync($this->patientId);
//
        if ($xmlGenerator->getFormData()['group_id'] == FormGroup::CHECK_OCR) {
            $xmlGenerator->saveOcrRecord();
        }
//
        // 记录存储的字段
        $record = [
            'sync_type' => $xmlGenerator->getSyncType(),
            'patient_id' => $xmlGenerator->patientId,
            'item_id' => $xmlGenerator->itemId,
            'item_sign_id' => $xmlGenerator->itemSignId,
            'form_id' => $xmlGenerator->formId,
            'sync_field' => json_encode($xmlGenerator->getSyncField()),
            'is_del' => 0,
            'checktime_id' => $this->checkTimeId,
            'multi_id' => ''
        ];

        if ($xmlGenerator->recordId !== 0) {
            $record['id'] = $xmlGenerator->recordId;
        }

        if ($xmlGenerator->multiId) {
            foreach ($xmlGenerator->multiId as $value) {
                $record = [
                    'sync_type' => $xmlGenerator->getSyncType(),
                    'patient_id' => $xmlGenerator->patientId,
                    'item_id' => $xmlGenerator->itemId,
                    'item_sign_id' => $xmlGenerator->itemSignId,
                    'form_id' => $xmlGenerator->formId,
                    'sync_field' => json_encode($xmlGenerator->getSyncField()),
                    'is_del' => 0,
                    'checktime_id' => $this->checkTimeId,
                    'multi_id' => $value
                ];
                if ($has = Laminas::$serviceManager->odmSyncRecord->fetchOne(['columns' => ['id'], 'where' => $record])) {
                    $record['id'] = $has['id'];
                }
                Laminas::$serviceManager->odmSyncRecord->save($record);
            }
        } else {
            Laminas::$serviceManager->odmSyncRecord->save($record);
        }
    }
}