<?php

namespace Application\Form;


use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Laminas;
use Laminas\Db\Sql\Predicate\Expression;
use Laminas\Http\Request;
use Laminas\Json\Json;
use Laminas\Stdlib\ArrayUtils;
use phpDocumentor\Reflection\Types\Mixed;

class CommonModel
{
    /**
     * 检查日期
     * @var string
     */
    private string $collectDate = '';

    private string $note = '';

    public function render(string $component,$dateType=1): array
    {
        if ($component === 'TableButton') {
            $dateType = !empty($dateType) ? $dateType : 1;
            $return_data = [
                'data' => $this->renderTableButton(),
                'collect_date' => $this->collectDate != '' ? $this->collectDate : '',
                'note' => $this->note,
                'table' => [
                    ['type' => 'Text', 'label' => '检查项', 'prop' => 'check_item'],
                    ['type' => 'Input', 'label' => '结果', 'prop' => 'result'],
                    ['type' => 'Input', 'label' => '单位', 'prop' => 'unit'],
                    ['type' => 'Input', 'label' => '最小值', 'prop' => 'min_val'],
                    ['type' => 'Input', 'label' => '最大值', 'prop' => 'max_val']
                ],
                'until' => [
                    'textarea' => call_user_func(function () {
                        $formData = Laminas::$serviceManager->itemForm->fetchOne(['where' => ['id' => $_POST['id']]]);
                        return (bool)Laminas::$serviceManager->dictionaryCheckcategory->fetchOne([
                                'where' => ['id' => $formData['checklist_id']]
                            ])['report_type'] ?? 0;
                    })
                ]
            ];

            unset($dateType);
            return $return_data;
        }

        return [];
    }


    private function renderTableButton(): array
    {
        $request = Laminas::$app->getMvcEvent()->getRequest();
        $formId = $request->getPost('id');
        $itemId = $request->getPost('item_id');
        $itemSigId = $request->getPost('itemsig_id');
        $formData = Laminas::$serviceManager->itemForm->fetchOne(['where' => ['id' => $formId]]);

        if (!$formId || !$formData || !$itemId) {
            throw new InvalidArgumentException("当前组件无法渲染, 因为你的参数不对呀~");
        }

        $checkNameData = Laminas::$serviceManager->itemCheckname->fetchAll([
            'order' => ['checkname_order'],
            'where' => [
                'item_id' => $itemId,
                'category_id' => $formData['checklist_id'],
                'is_del' => 0
            ]
        ]);
        $tableData = [];

        $imgTxtDiscernData = Laminas::$serviceManager->itemImgtxtdiscern->fetchOne([
            'where' => [
                'category_id' => $formData['checklist_id'],
                'item_sign_id' => $itemSigId,
                'is_del' => 0,
                'item_id' => $itemId
            ]
        ])['check_data'] ?? [];

        if ($imgTxtDiscernData) {
            if (!is_array($imgTxtDiscernData)) {
                $imgTxtDiscernData = Json::decode($imgTxtDiscernData, Json::TYPE_ARRAY);
            }
            $imgTxtDiscernData = ArrayHelper::index($imgTxtDiscernData, 'checkname_id');
        }
        foreach ($checkNameData as $k => $checkNameDatum) {
            $result = $this->getResult($checkNameDatum['id'], $request);

            $tableData[$k] = array_intersect_key($checkNameDatum, array_flip([
                'id', 'check_type', 'unit', 'max_val', 'min_val'
            ]));

            $tableData[$k]['check_item'] = $checkNameDatum['name'];
            $tableData[$k]['result'] = $result['result'] ?? '';

            if (!empty($imgTxtDiscernData[$checkNameDatum['checkname_id']])) {
                $tableData[$k]['max_val'] = $imgTxtDiscernData[$checkNameDatum['checkname_id']]['max_val'];
                $tableData[$k]['min_val'] = $imgTxtDiscernData[$checkNameDatum['checkname_id']]['min_val'];
                $tableData[$k]['unit'] = $imgTxtDiscernData[$checkNameDatum['checkname_id']]['change_unit'];
            }
            if(!empty($result)) {
                $tableData[$k]['max_val'] = $result['reference_range_max'];
                $tableData[$k]['min_val'] = $result['reference_range_min'];
                $tableData[$k]['unit'] = $result['unit'];
            }
            // 有手动填写的值就用手写的, 没有的话就用配置的
            /*$tableData[$k]['max_val'] = $this->handleVal($imgTxtDiscernData['change_name'], $result['reference_range_max'] ?: $checkNameDatum['max_val']);
            $tableData[$k]['min_val'] = $this->handleVal($imgTxtDiscernData['change_name'], $result['reference_range_min'] ?: $checkNameDatum['min_val']);*/
        }

        return $tableData;
    }

    private function handleVal($changeName, $val)
    {
        if ($changeName) {
            return (string)(floatval($changeName) * floatval($val));
        }

        return $val;
    }

    /**
     * 获取 [受试者工作附件表] 结果值
     * @param $checkNameId
     * @param Request $request
     * @return array
     */
    private function getResult($checkNameId, Request $request): array
    {
        $patientFormId = Laminas::$serviceManager->patientForm->fetchOne([
            'where' => [
                'patient_id' => $request->getPost('patient_id'),
                'item_id' => $request->getPost('item_id'),
                'itemsig_id' => $request->getPost('itemsig_id'),
                'checktime_id' => $request->getPost('checktime_id'),
                'form_id' => $request->getPost('id'),
            ]
        ])['id'] ?? 0;

        $where = [
//            'is_del' => 0,
            'item_checkname_id' => $checkNameId,
            'patient_id' => $request->getPost('patient_id'),
            'item_id' => $request->getPost('item_id'),
            'itemsig_id' => $request->getPost('itemsig_id'),
            'checktime_id' => $request->getPost('checktime_id'),
        ];
        if($request->getPost('patientformcontent_id') != 0){
            $where['patientformcontent_id'] = $request->getPost('patientformcontent_id');
        }else{
            $where['patient_form_id'] = $patientFormId;
        }

        $hasResult = Laminas::$serviceManager->itemIdentificationresultchange->fetchOne(['where'=>$where]);

        // 检查日期
        if (!$this->collectDate) {
            $this->collectDate = $hasResult['collect_date'] ?? '';
        }

        // 备注
        if (!$this->note) {
            $this->note = $hasResult['result'] ?? '';
        }

        return $hasResult ?: [];
    }
}
