<?php

//declare(strict_types=1);

namespace Application\Controller;

use Application\Common\Container;
use Application\Form\ExportModel;
use Application\Mvc\Controller\Plugins\RenderApiJson;
use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\Extension\Helper\ExcelHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Queue\jobs\SyncPatientFormJob;
use Application\Service\Extension\Queue\QueueApplication;
use Application\Service\Extension\Xml\LaboratoryXmlGenerator;
use Laminas\ApiTools\Admin\Module as AdminModule;
use Laminas\Http\Response;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;
use function class_exists;

/**
 *
 * @package Application\Controller
 *
 * @method RenderApiJson RenderApiJson()
 * @method Container LocalService()
 */
class IndexController extends AbstractActionController
{

    const Genercsetinfotype='Genercsetinfotype';//字典项分类-1
    const Genercsetinfo='Genercsetinfo';//字典项通用名
    /**
     * @return Response|ViewModel
     */


    public static function yieldFuc($num)
    {
        
        $oper_type = [0,1,2];
        $log_type = [0,1,3];
        $formData = include $_SERVER['DOCUMENT_ROOT'].'/../formData/formMap.php';
        for($i = 0; $i < $num; $i++){
            $logData = [
                'user_id' => 1,
                'event_from' => array_rand($formData),
                'event_id' => $i,
                'create_time' => time(),
                'log_ip' => '127.0.0.1',
                'oper_type' => array_rand($oper_type),
                'log_type' => array_rand($log_type),
                'change_data' => '测试'
            ];

            yield $logData;
        }
    }

    public function indexAction()
    {
        set_time_limit(0);
        $datas = self::yieldFuc(10000);
        foreach($datas as $data){
            $this->LocalService()->adminLog->save($data);
        }
        exit('finish');

        echo "<pre>";print_r($this->LocalService()->identity->getIdentityData());exit;
        for($i = 19728; $i <= 19830; $i++){
            echo $i.' ';
        }
        exit;
        $formFieldData = $this->Introduce(self::Genercsetinfotype);
        $formFieldData = empty($formFieldData) ? [] : array_values($formFieldData);
        $formValData = 1 ? $this->LocalService()->dictionaryGenercsetinfotype->fetchOne(['where' => 'id = 1']) : [];

        return $this->RenderApiJson()->Success($formValData, '', ['formFieldData' => $formFieldData]);



        $maxId = $this->LocalService()->adminUser->getOneFieldVal('id', 'status = 1', 'id desc');
        $maxOrder = $this->LocalService()->adminUser->getMaxOrder('id', 'status = 1');
        echo 'maxId：'.$maxId.'   </br>';
        echo 'maxOrder：'.$maxOrder.'   </br>';exit;
        $this->LocalService()->adminUser->check_field_repeat('mobile', '15001062410', ['field' => 'is_del', 'value' => 1]);


        // 操作前数据
        $oprt_pre = [
            'id' => 1,
            'name' => '张三',
            'status' => 0,
            'mobile' => '12345678901',
            'role_id' => 1
        ];

        // 操作后数据
        $oprt_last = [
            'id' => 1,
            'name' => '张山',
            'status' => 0,
            'mobile' => '01234567890',
            'role_id' => '1,2,3,4,5'
        ];

        //日志文件数据
        $logData = [
            'event' => 'AdminUser',
            'ip' => '127.0.0.1',
            'user_id' => 1,
            'user_name' => '超级管理员',
            'time' => time(),
            'oprt_pre' => $oprt_pre,
            'oprt_last' => $oprt_last
        ];
        // 获取修改的字段
        $changeData = array_diff_assoc($logData['oprt_last'], $logData['oprt_pre']);
        if(!empty($changeData)){
            $formMapData = include $_SERVER['DOCUMENT_ROOT'].'/../data/FormData/formMap.php';
            $form_col_desc_data = include $_SERVER['DOCUMENT_ROOT'].'/../data/FormData/'.$logData['event'].'Data.php';
            $event_name = $formMapData[$logData['event']];
            foreach($changeData as $changeKey => &$changeVal){
                if(isset($form_col_desc_data[$changeKey]['val_source']) and is_callable($form_col_desc_data[$changeKey]['val_source'])){
                    $changeVal = $form_col_desc_data[$changeKey]['val_source']($this->LocalService(), $changeVal);
                }
                $desc_data[] = $form_col_desc_data[$changeKey]['title'].'：'.$changeVal;
            }
        }
        echo "<pre>";print_r($changeData);
        echo $logData['user_name'].' 修改了：</br></br>'.implode('</br>', $desc_data);
        echo "<pre>";print_r($logData);exit;
        if (class_exists(AdminModule::class, false)) {
            return $this->redirect()->toRoute('api-tools/ui');
        }
        return new ViewModel();
    }

    protected int $contentId = 0;
    protected string $prop = '';
    public function testAction()
    {
        $model = new ExportModel();
//        $model->exportLogicError();
        //2267; // pumch - 1101
        ExcelHelper::exportExcel($model->exportLogicError(1101), [
            [
                ['项目ID', 'item_id', 'text'],
                ['中心编号', 'sign_id', 'text'],
                ['筛选号', 'patient_id', 'text'],
                ['访视名称', 'checktime_id', 'text'],
                ['表单名称', 'form_id', 'text'],
                ['字段名称', 'prop', 'text'],
                ['原来值', 'origin_value', 'text'],
                ['更正值', 'value', 'text'],
//                ['更正原因', 'note', 'text'],
                ['质疑内容', 'expression_note', 'text'],
                ['质疑时间', 'create_time', 'text'],
                ['质疑发出人员/角色', 'create_user_id', 'text'],
                ['质疑回复内容', 'reply_content', 'text'],
                ['质疑回复时间', 'replay_time', 'text'],
                ['质疑回复人员/角色', 'replay_user_id', 'text'],
                ['质疑关闭时间', 'is_closed', 'text'],
                ['质疑关闭人员/角色', 'closed_user_id', 'text'],
            ]
            ], time(), 'xlsx', '', ['质疑数据']);
        die;
//        $a = new App();
//        $a->itemId = 1084;
//        $a->signId = 1248;
//        $a->menuId = App::MODULE_CS;
//        $a->push([37]);
//        die('123123');
//        var_dump(Laminas::$serviceManager->itemForm->getPreviewConfig(518, true));die;
//        $model = new SyncPatientFormJob();
//            $model = new FormContentXmlGenerator();
//        $model->patientId = 4134;
//        $model->itemSignId = 272;
//        $model->itemId = 101;
//        $model->formId = 947; // 3917 //747 717;
//        $model->checkTimeId = 566; //747 717;
//            $xmlModel = new XmlBuilder();
//                $data = $xmlModel->build($model->generate());
//                echo $data;die;
////                echo json_encode($data, JSON_UNESCAPED_SLASHES);die;
//////            $model->run();
//        echo QueueApplication::push($model);die;
//        die;

        $model = new LaboratoryXmlGenerator();
//        $model->setHeader([
//            [
//                'key' => 'TEST',
//                'value' => '是',
//                'transactionType' => 'Insert',
//            ],
//            [
//                'key' => 'DATE',
//                'value' => '2022-1-1',
//                'transactionType' => 'Update',
//            ]
//        ]);
//        $model->setContent(
//            [
//               [
//                   ['itemOID' => 'INDICATORS', 'transactionType' => 'Insert', 'value' => '白细胞'], // 指标
//                   ['itemOID' => 'UNIT', 'transactionType' => 'Insert', 'value' => '10^9/L'], // 单位
//               ],
//               [
//                   ['itemOID' => 'INDICATORS', 'transactionType' => 'Insert', 'value' => '中性粒细胞绝对值'], // 指标
//                   ['itemOID' => 'UNIT', 'transactionType' => 'Insert', 'value' => '10^9/L'], // 单位
////                   ['itemOID' => 'RESULT', 'transactionType' => 'Insert', 'value' => '4.05'], // 结果
////                   ['itemOID' => 'RANGE', 'transactionType' => 'Insert', 'value' => '1.8-6.3'], // 范围
////                   ['itemOID' => 'NORMAL', 'transactionType' => 'Insert', 'value' => 'true'], // 正常
//               ]
//            ]
//        );
//        $model->setFormId(3946);
//        $model->setPatientId(1992);
//        $model->generate();
//        $builder = new XmlBuilder();
//
//        echo $builder->build($model->generate());die;
        $query = Laminas::$serviceManager->patient->fetchAll([
//            'where' => ['item_id' => 1084, 'itemsig_id' => 1344, 'is_del' => 0]
            'where' =>
                [
//                'id' => [2032, 2069, 2640, 4134, 4557, 5015, 5358, 5488, 5531, 5599, 5659, 5769, 6083]
//                'id' => [4814, 4813, 2032, 2069, 2640, 4134, 4557, 5015, 5358, 5488, 5531, 5599, 5659, 5769, 6083]//[2032, 2069, 2640, 4134, 4557, 5015, 5358, 5488, 5531, 5599, 5659, 5769, 6083],
//                'id' => [2069, 2640, 4134, 4557, 5015, 5358, 5488, 5531, 5599, 5659, 5769, 6083],
                'id' => [5651, 5652, 5878, 6127, 6146],
//                'id' => [2367, 2368, 2369, 2370, 2539, 2540, 2541, 4813, 2863, 2864, 2865, 2866, 4814, 4584, 4585, 5651, 5652, 5669, 5670, 5878, 5879, 5941, 6127, 6146]
            ] // 1043
//            'where' => ['id' => [2367, 2368, 2369, 2370, 2539, 2540, 2541, 2863, 2864, 2865, 2866, 4584, 4585]]  // 2368, 2369, 2370, 2539, 2540, 2541, 2863, 2864, 2865, 2866, 4584, 4585
//            'where' => ['id' => 2069] // 1043
        ]);
//
//        $model = new SyncPatientFormJob();
////                    $model = new FormContentXmlGenerator();
//            $model->patientId = intval($query[0]['id']);
//            $model->itemSignId = $query[0]['itemsig_id'];
//            $model->itemId = intval($query[0]['item_id']);
//            $model->formId = 3921; //747 717;
//            $model->checkTimeId = intval(563); //747 717;
////            $xmlModel = new XmlBuilder();
////            $data = $xmlModel->build($model->generate());
////                echo $data;die;
//        $model->run();
//        die;
//////         新增 一个受试者

//        die;

//        var_dump($query);die;
        // 处理 ae
        foreach ($query as $item) {
//            $model = new SyncPatientJob();
//////            $model = new PatientXmlGenerator();
//            $model->patientId = intval($item['id']); // 受试者id
//            $model->itemSignId = $item['itemsig_id']; // 中心id
////            $xmlModel = new XmlBuilder();
////            $data = $xmlModel->build($model->generate());
////            echo $data;die;
////            $model->run();
//            echo QueueApplication::push($model);
//            // 1406, 1407, 1409, 1410, 1411, 1412, 1408, 1413, 1414, 99
//
////            foreach ([560, 561, 562, 575, 563, 564, 565, 566, 570, 567, 571, 569, 572, 573, 99] as $v) {
//            foreach ([1409] as $v) {
//                $model = new SyncPatientFormJob();
////                $model = new FormContentXmlGenerator();
//                $model->patientId = intval($item['id']);
//                $model->itemSignId = 1344; //$item['itemsig_id'];
//                $model->itemId = 1084; // intval($item['item_id']);
//                $model->formId = 4602; //82841, 2841;
//                $model->checkTimeId = intval($v); //747 717;
////                $model->isSync = true;
////                $xmlModel = new XmlBuilder();
////                $data = $xmlModel->build($model->generate());
////                echo json_encode($data, JSON_UNESCAPED_SLASHES);die;
//                echo QueueApplication::push($model);
////                $model->isSync = false;
////                echo QueueApplication::push($model);
//            }
//die;
//            $model = new SyncPatientFormJob();
//            $model = new FormContentXmlGenerator();
//            $model->patientId = intval($item['id']);
//            $model->itemSignId = 272; //$item['itemsig_id'];
//            $model->itemId = 101; // intval($item['item_id']);
//            $model->formId = 3918; //747 717;
//            $model->checkTimeId = intval(1412); //747 717;
////            $model->isDeleteItemData = true;
////            echo QueueApplication::push($model);die;
//            $xmlModel = new XmlBuilder();
//            $data = $xmlModel->build($model->generate());
//            echo json_encode($data, JSON_UNESCAPED_SLASHES);die;
            $this->syncPatientForm($item);
        }
        die;
    }

    private function syncPatientForm(array $query)
    {
        $allCheckTime = Laminas::$serviceManager->itemPatientchecktime->fetchAll([
            'columns' => ['checktime_id'],
            'where' => [
                'patient_id' => $query['id']
            ]
        ]);

        $allCheckTime[] = [
            'checktime_id' => 99
        ];

        foreach ($allCheckTime as $checkTime) {
            if ($checkTime['checktime_id'] == 99) {
                $allFormId = Laminas::$serviceManager->itemForm->fetchCol('id', [
                    'item_id' => $query['item_id'],
                    'group_id' => [FormGroup::SAE, FormGroup::AE, FormGroup::THROUGH_PROCESS, FormGroup::TEST_SUMMARY],
                    'is_del' => 0
                ]);
            } else {
                $allFormId = Laminas::$serviceManager->patientForm->fetchCol('form_id', ['patient_id' => $query['id'], 'is_del' => 0, 'checktime_id' => $checkTime['checktime_id']]);
            }

            $allFormId = array_unique(array_values($allFormId));

            foreach ($allFormId as $formId) {
//                var_dump($formId);
//                $formId = intval($formId['form_id']);

                $form = Laminas::$serviceManager->itemForm->fetchOne([
                    'where' => ['id' => $formId]
                ]);

                if ($form['group_id'] != FormGroup::CHECK_OCR) {
                    continue;
                }

                if ($checkTime['checktime_id'] != 99) {
                    if (in_array($form['group_id'], [FormGroup::SAE, FormGroup::AE, FormGroup::THROUGH_PROCESS, FormGroup::TEST_SUMMARY])) {
                        continue;
                    }
                }
                $model = new SyncPatientFormJob();
//            $model = new FormContentXmlGenerator();
                $model->patientId = intval($query['id']);
                $model->itemSignId = $query['itemsig_id'];
                $model->itemId = intval($query['item_id']);
                $model->formId = $formId; //747 717;
                $model->checkTimeId = intval($checkTime['checktime_id']); //747 717;
                // 有数据说明写了
//                if ($model->isSync() === false || $model->getFormContent('fetchOne', false) === false || $model->getIsProcessSync() === true) {
//                    continue;
//                }
//                $model->formContent = [];
//            $xmlModel = new XmlBuilder();
//                $data = $xmlModel->build($model->generate());
//                echo $data;
//            $model->run();
                echo "受试者: [{$query['id']}]. 检查点: [{$checkTime['checktime_id']}]. 表单 [{$formId}]. " . PHP_EOL;
                QueueApplication::push($model);
            }
        }
    }
}
