<?php

namespace Application\Controller\item;

use Application\Common\StatusCode;
use Application\Form\item\patient\PatientFormModel;
use Application\Mvc\Controller\BasicController;
use Application\Service\DB\Db;
use Application\Service\DB\Dictionary\Form;
use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Formatter\Formatter;
use Application\Service\Extension\Formatter\QuestionFormatter;
use Application\Service\Extension\Helper\DataHelper;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Exception;
use Laminas\View\Model\JsonModel;

class QuestionController extends BasicController
{
    /**
     * @actionUrl /question/view
     * @return JsonModel
     * @throws Exception
     */
    public function questionViewAction(): JsonModel
    {
        $this->validator->attach(
            [['patient_id', 'form_id', 'checktime_id'], 'required']
        );
        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        // 一对多 表单 图片质疑，常规识别 的图片 独立入口，不在表单中，所以id = 0
        if (SDMHelper::app()->form->getGroupId($this->validator->attributes['form_id']) == FormGroup::NORMAL_OCR && SDMHelper::app()->form->getType($this->validator->attributes['form_id']) == Form::FORM_TYPE_MULTI) {
            $formId = 0;
        }else {
            $formId = Laminas::$serviceManager->patientFormContent->fetchOne(['where' => ['form_id' => $this->validator->attributes['form_id'], 'patient_id' => $this->validator->attributes['patient_id'], 'checktime_id' => $this->validator->attributes['checktime_id'], 'is_del' => 0]])['id'] ?? 0;
        }

        //        if (SDMHelper::app()->form->getGroupId($this->validator->attributes['form_id']) == FormGroup::NORMAL_OCR && SDMHelper::app()->form->getType($this->validator->attributes['form_id']) == Form::FORM_TYPE_MULTI) {
            return $this->RenderApiJson()->Success([
                'id' => $formId,
                SDMHelper::app()->form->getShareFormField($this->validator->attributes['form_id'])['id'] => SDMHelper::app()->form->getShareFormImages($this->validator->attributes['form_id'], $this->validator->attributes['patient_id'], $this->validator->attributes['checktime_id'])
//            'shareFormImages' => SDMHelper::app()->form->getShareFormImages($this->validator->attributes['form_id'], $this->validator->attributes['patient_id'], $this->validator->attributes['checktime_id'])
            ]);
//            return $this->RenderApiJson()->Success([
//                'id' => 0,
////                SDMHelper::app()->form->getShareFormField($this->validator->attributes['form_id'])['id'] => SDMHelper::app()->form->getShareFormImages($this->validator->attributes['form_id'], $this->validator->attributes['patient_id'], $this->validator->attributes['checktime_id'])
//            'shareFormImages' => SDMHelper::app()->form->getShareFormImages($this->validator->attributes['form_id'], $this->validator->attributes['patient_id'], $this->validator->attributes['checktime_id'])
//            ]);
//        }

        throw new InvalidArgumentException('表单类型有误。');

    }

    /**
     * 回复表单质疑
     * @url http://xxx.com/v1/item/question/replyQuestion
     * @return JsonModel
     * @throws Exception
     */
    public function replyQuestionAction(): JsonModel
    {
        // 改版了 `content` 现在没用了
        $this->validator->attach(
            [['question_id', 'content'], 'required']
        );

        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        Db::beginTransaction();
        $questionData = $this->LocalService()->itemQuestion->fetchOne([
            'where' => ['id' => $this->validator->attributes['question_id']]
        ]);

        // 新增回复历史
        $this->LocalService()->itemReply->insert([
            'question_id' => $this->validator->attributes['question_id'],
            'reply_status' => 0,
            'remarks' => json_encode([
                // 表单数据
                'formData' => call_user_func(function () use ($questionData) {
                    // 获取表单原始数据
                    if($questionData['content_id']) {
                        $model = new PatientFormModel();
                        $originData = $this->handleFormData($model->viewById($questionData['content_id']));

                    }else {
                        // 常规识别且一对多表单，只提取共享图片
                        $originData = [
                            SDMHelper::app()->form->getShareFormField($questionData['form_id'])['id'] => SDMHelper::app()->form->getShareFormImages($questionData['form_id'], $questionData['patient_id'], $questionData['checktime_id'])
                        ];
                    }

                    $postData = DataHelper::handleFormData($this->params()->fromPost(), $questionData['form_id']);

                    foreach ($postData as $postKey => &$postDatum) {
                        if ($postDatum === '[]') {
                            $postDatum = [];
                        }
                        if (is_numeric($postKey)) {
                            $originData[$postKey] = $postDatum;
                        }
                    }

                    return $originData;
                }),
                // 表单结构
                'form' => call_user_func(function () use ($questionData) {
                    return  $this->getQuestionTypeId(
                        $questionData['content_id'],
                        $questionData['form_id'],
                        $questionData['question_type_id']
                    );
                }),
                'remarks' => $this->validator->attributes['reply']
            ]),
            'annex_aligned' => '',
            'completed_id' => $this->LocalService()->identity->getId(),
            'completed_time' => time(),
            'completed_type' => 1,
            'is_del' => 0,
        ]);
        // 修改疑问状态
        // 提出疑问的content要变成上一次回复的数据
        $this->LocalService()->itemQuestion->update([
//            'content' => json_encode($this->formData), // $this->validator->attributes['content'],
            'question_status' => 1
        ], [
            'id' => $this->validator->attributes['question_id']
        ]);

        Db::commit();

        //异步处理访视进度情况信息
        
        $form_content_arr = !empty($questionData['content_id']) ? [$questionData['content_id']] : [];
        Laminas::$serviceManager->swTaskClient->send([
            'svName' => 'projectPatientworkbatch',
            'methodName' => 'multipleUpdateData',
            'params' => [
                'item_id' => $questionData['item_id'],
                'itemsig_id' => $questionData['item_sign_id'],
                'patient_id' => $questionData['patient_id'],
                'checktime_id' => $questionData['checktime_id'],
                'form_id' => $questionData['form_id'],
                'operate_type'=>11,
                'content_id'=>!empty($form_content_arr) ? $form_content_arr : [],
                'user_id' => Laminas::$serviceManager->identity->getId()
            ]
        ]);
        unset($form_content_arr);

        return $this->RenderApiJson()->Success();
    }

    private function handleFormData(array $formData): array
    {
        foreach ($formData as $k => $item) {
            if (stripos($k, '-') !== false) {
                $key = (explode('-', $k)[0]);
                $formData[$key] = $item;
                unset($formData[$k]);
            }
        }

        return $formData;
    }
    /**
     * @param int $contentId
     * @param int $formId
     * @param string $questionTypeId
     * @param string $originFormData
     * @return array
     */
    private function getQuestionTypeId(int $contentId, int $formId, string $questionTypeId): array
    {
        if (!$questionTypeId || !$formId) {
            return [];
        }

        $form = SDMHelper::app()->setAttributes([
            'formId' => $formId,
        ])->form;
        $isValidContentId = ! ( $form->getType() == Form::FORM_TYPE_MULTI && $form->getGroupId() == FormGroup::NORMAL_OCR );
        if($isValidContentId && !$contentId) {
            return [];
        }

        $data = explode(',', $questionTypeId);

        foreach ($data as $datum) {
            $formData = $this->LocalService()->itemFormVersion->getField(['form_id' => $formId], true);
            if (isset($formData[$datum])) {
                $res[] = $this->LocalService()->itemForm->buildConfig($formData[$datum]);
            }
        }

        return $res ?? [];
    }

    /**
     * @url http://xxx.com/v1/item/question/historyReply
     * @return JsonModel
     * @throws Exception
     */
    public function historyReplyAction(): JsonModel
    {
        $this->validator->attach(
            [['question_id', 'reply_id'], 'required']
        );

        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        $query = $this->LocalService()->itemReply->fetchOne([
            'where' => ['id' => $this->validator->attributes['reply_id']]
        ]) ?? [];

        Formatter::format($query, new QuestionFormatter());

        if (is_array($query['remarks']['formData'])) {
            foreach ($query['remarks']['formData'] as &$remark) {
//            ErrorHandler::log2txt($remark);
                if (is_numeric($remark)) {
                    continue;
                }

                $d = StringHelper::jsonDecode($remark, false);

                if ($d !== false) {
                    $remark = $d;
                }
            }
        }

        if (isset($query['remarks']['remarks'])) {
            array_unshift($query['remarks']['form'], [
                'label' => '回复内容',
                'prop' => 'reply',
                'type' => 'Text',
                'disabled' => true
            ]);

            $query['remarks']['formData']['reply'] = $query['remarks']['remarks'];
        }

        return $this->RenderApiJson()->Success($query);
    }
}
