<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/5/9 12:25
 * @Description：
 *
 */

namespace Application\Command;

use Application\Common\Container;
use Application\Common\EventEnum;
use Application\Form\ExportModel;
use Application\Form\FieldForm;
use Application\Form\item\ItemFieldForm;
use Application\Form\item\patient\NormalOCRFormModel;
use Application\Form\item\patient\PatientFormModel;
use Application\Service\DB\Db;
use Application\Service\DB\Dictionary\Form;
use Application\Service\DB\Dictionary\FormField;
use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\DB\Item\PatientFormContentImg;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\DataHelper;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Middleware\components\FlushFormContentLog;
use Application\Service\Extension\Middleware\Middleware;
use Application\Service\Extension\Validator\ValidatorApplication;
use ApplicationTest\PatientFormTest;
use GuzzleHttp\Client;
use Laminas\Db\Sql\Predicate\Between;
use Laminas\Db\Sql\Predicate\Like;
use Laminas\Db\Sql\Predicate\Operator;
use Swoole\Process;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class TestCommand extends BasicCommand
{
    public $migrateData;

    private $formId;
    private $mainId = 0;
    private $branchMap = [];

    /**
     * 字段类型映射
     */
    public const CONTENT_MAP = [
        '1' => FormField::FORM_FIELD_TYPE_TEXT,
        '4' => FormField::FORM_FIELD_TYPE_DATE_UK,
        '2' => FormField::FORM_FIELD_TYPE_DATE,
        '3' => FormField::FORM_FIELD_TYPE_DATE_SECOND,
        '13' => FormField::FORM_FIELD_TYPE_DATE_SECOND,
        '5' => FormField::FORM_FIELD_TYPE_INTEGER,
        '6' => FormField::FORM_FIELD_TYPE_FLOAT_1,
        '7' => FormField::FORM_FIELD_TYPE_FLOAT_2,
        '8' => FormField::FORM_FIELD_TYPE_RADIO,
        '9' => FormField::FORM_FIELD_TYPE_RADIO,
        '10' => FormField::FORM_FIELD_TYPE_CHECKBOX,
        '11' => FormField::FORM_FIELD_TYPE_CHECKBOX,
        '12' => FormField::FORM_FIELD_TYPE_DROPDOWN,

    ];

    public function contab(){
//        $iteminfoData = $this->patientattrUpdate($item=107);
        $limit = $_POST['limit'] ?: '5000';
        $page = $_POST['page'] ?: '1';
        $smallItemId = ['105','103','72','74','77'];
            $iteminfoData = $this->newLockItemPatientWorkannex(105,$page,$limit);

        echo '成功';die;
        return true;

    }


    public function newLockItemPatientWorkannex($smallItemId,$page,$limit,$type=1){
        ini_set('memory_limit', -1);
        try {
            $i = 0;
            $j = '';

            if (empty($type)){
                $this->is_print_sql = true;
                $offset = intval(($page - 1) * $limit);
                $whereItemIdentificationresultchange['where'] = 'is_del=0  and lock_state=1  and collect_date !=0 and item_id='.$smallItemId;//and patientworkannex_id !=" "
                $whereItemIdentificationresultchange['columns'] =['id','collect_date','lock_state','patientworkannex_id','patient_id','checktime_id','form_id','patient_form_id'];
//        $whereItemIdentificationresultchange['group'] = ['patient_id','checktime_id','patient_form_id'];
                $whereItemIdentificationresultchange['group'] = ['checktime_id','patient_form_id'];
                $whereItemIdentificationresultchange['order'] = ['id desc'];
                $whereItemIdentificationresultchange['limit'] = $limit;
                $whereItemIdentificationresultchange['offset'] = $offset;
//        $itemIdentificationresultchangeCount = $this->LocalService()->itemIdentificationresultchange->getCount($whereItemIdentificationresultchange['where']);
                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);

                foreach ($itemIdentificationresultchangeData as $k => $itemIdentificationresultchangeDatum) {
                    echo "正在处理第{$k}个" . PHP_EOL;
                    $newWork['collect_date'] = $itemIdentificationresultchangeDatum['collect_date'] != '' ? strtotime($itemIdentificationresultchangeDatum['collect_date']) : '';
                    $newWork['change_type'] = 1;
                    $newWork['lock_state'] = 1;
                    if (empty($itemIdentificationresultchangeDatum['patient_form_id'])) {
                        echo '<pre>';print_r($itemIdentificationresultchangeDatum);die;
                    }
//            $where = "id in (".$itemIdentificationresultchangeDatum['patientworkannex_id'].")";
                    $where = 'is_del=0 and patient_id='.$itemIdentificationresultchangeDatum['patient_id'].' and checktime_id='.$itemIdentificationresultchangeDatum['patient_id'].' and patient_form_id='.$itemIdentificationresultchangeDatum['patient_form_id'];
                    $resultWork = $this->LocalService()->itemPatientworkannex->update($newWork,$where);
                    if ($resultWork) {
                        echo '更新成功' . PHP_EOL;
                    }
//                echo '<pre>';print_r($itemIdentificationresultchangeDatum);die;
                    $j .= '<pre>'.$page.'--'.$resultWork;
                    $i++;
                }

//                var_dump($this->LocalService()->itemPatientworkannex::getDbProfile());
                echo $i.$j;die;
            }else{
                $offset = intval(($page - 1) * $limit);
                //时间条件
                $time = ' and FROM_UNIXTIME(up_annex_date ,"%Y-%m-%d")="2022-09-17"';
//                $time = '';
                $whereItemPatientworkannex['where'] =  'is_del=0 and item_id =' . $smallItemId.'  and annex_type !=2  and lock_state=0'.$time;//annex_type !=3//只查手动写和图片上传的
                $whereItemPatientworkannex['group'] = ['checktime_id','patient_form_id','form_id'];
                $whereItemPatientworkannex['columns'] =['id','checktime_id','patient_form_id','form_id','patient_id','item_id'];
                $whereItemPatientworkannex['order'] = ['id desc'];
                $whereItemPatientworkannex['limit'] = $limit;
                $whereItemPatientworkannex['offset'] = $offset;
                $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);

                if (!empty($itemPatientworkannexData)){

                    foreach($itemPatientworkannexData as $itemPatientworkannexDataKey => $itemPatientworkannexDataValue){
                        echo "正在处理第{$itemPatientworkannexDataKey}个" . PHP_EOL;
//                        $where = 'is_del=0 and lock_state=1 and patientworkannex_id !="" and checktime_id ='.$itemPatientworkannexDataValue['checktime_id'].' and patient_form_id='.$itemPatientworkannexDataValue['patient_form_id'].' and item_id='.$smallItemId.' and patient_id='.$itemPatientworkannexDataValue['checktime_id'];
//                        and patientworkannex_id !=""
                        $where = 'is_del=0 and lock_state=1  and checktime_id ='.$itemPatientworkannexDataValue['checktime_id'].' and patient_form_id='.$itemPatientworkannexDataValue['patient_form_id'].' and item_id='.$smallItemId.' and patient_id='.$itemPatientworkannexDataValue['patient_id'];
                        $wheres['where'] = $where;
                        $wheres['columns'] = ['id','collect_date','checktime_id','patient_form_id','form_id','patient_id','item_id'];
                        $changeInfo = $this->LocalService()->itemIdentificationresultchange->fetchOne($wheres);
                        if (!empty($changeInfo)){
                            $newWork['collect_date'] = $changeInfo['collect_date'] != '' ? strtotime($changeInfo['collect_date']) :'';
//                            $newWork['change_type'] = 1;
                            $newWork['lock_state'] = 1;
                            $upWhere = 'is_del=0  and patient_id='.$changeInfo['patient_id'].' and item_id='.$changeInfo['item_id'].' and patient_form_id='.$changeInfo['patient_form_id'].' and checktime_id='.$changeInfo['checktime_id'];
                            $resultWork = $this->LocalService()->itemPatientworkannex->update($newWork,$upWhere);
                            if ($resultWork) {
                                echo '更新成功' . PHP_EOL;
                            }
                            $j .= '<pre>'.$page.'--'.$resultWork;
                        }
                        $i++;
                    }
                }
//                var_dump($this->LocalService()->itemPatientworkannex::getDbProfile());
//                echo $i.$j;die;


            }

        }catch (\Throwable $exception) {
            var_dump($exception->getMessage());die;
        }

    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {

        //
        $a = new ExportModel();
        $a->exportLogicError(['item_id' => 220]);
        var_dump($a);die;
        ;
        // 290950,291490,291491,291492,291493
        // 远大
        Laminas::$serviceManager->itemFormField->update(['is_del' => 1], ['id' => [290950,291490,291491,291492,291493]]);
        $v = $this->LocalService()->itemForm->buildFieldVersion(87277);
        $this->LocalService()->itemFormVersion->update(['field' => $v], ['form_id' => 87277]);
        die;




        die;
        $postValues = array (
        'INDYN' => '1',
        'DYN' => '',
        'PICT' =>
            array (
            ),
        'MCO' => '',
//        'DMSTDAT' => '2024-02-21',
        'INQU' => '30',
        'INDAT' => '2024-08-21',
    );

        $expression = SDMHelper::app()->expression->setValues($postValues)->setExpression("((210-INQU)/DATEDIF(INDAT,DMSTDAT,'D'))*1")->execute()->getExecuteCompile();

        var_dump($expression);die;
        $maxFieldId = 350000;
        $endTime = '2024-06-20';

        $handleCount = 200;
        for ($i = 1; $i <= $maxFieldId; $i  = $i + $handleCount) {
            $query = Laminas::$serviceManager->patientFormContentImg->fetchAll([
                'columns' => ['content_id', 'img_src', 'field_id', 'form_id'],
                'where' => [
//                    new Operator('create_time', Operator::OP_LTE, strtotime($endTime . ' 23:59:59')),
                    'is_del' => 0,
//                    'form_id' => 90712,
//                    'patient_id' => 2864,
//                    'checktime_id' => 1410,
                    new Between('form_id', $i + 1, $i + $handleCount),
                ]
            ]);

            if ($query) {

                $allImgData = ArrayHelper::index($query, null, [function($el) {
                    return $el['content_id'];
                }, 'field_id']);

                foreach ($allImgData as $contentId => $imgDataItem) {
                    if (!$contentId) {
                        continue;
                    }
                    $contentData = Laminas::$serviceManager->patientFormContent->fetchOne([
                        'where' => ['id' => $contentId, 'is_del' => 0]
                    ]) ?: false;

                    if (SDMHelper::app()->form->getGroupId($contentData['form_id']) == FormGroup::NORMAL_OCR) {
                        continue;
                    }

                    if ($contentData === false) {
                        echo '数据被删除了, 图片没被删????' . PHP_EOL;
                    }
                    $fix = false;
                    foreach ($imgDataItem as $fieldId => $fieldIdItem) {

                        if (!$fieldId) {
                            continue;
                        }
//                        echo "正在处理 {$contentId} 的 {$fieldId}" . PHP_EOL;
                        $contentDataRow = StringHelper::jsonDecode($contentData['data']);
                        $has = false;
                        $isDelete = false;
                        foreach ($contentDataRow as $key => $row) {
                            if (DataHelper::getFieldId($key) == $fieldId) {
                                $has = true;
                                $rowImg = StringHelper::jsonDecode($row);
                                if (count($rowImg) !== count($fieldIdItem)) {
                                    $con = [
                                        'item_id' => $contentDataRow['item_id'],
                                        'itemsig_id' => $contentDataRow['itemsig_id'],
                                        'patient_id' => $contentDataRow['patient_id'],
                                        'form_id' => $contentDataRow['form_id'],
                                        'checktime_id' => $contentDataRow['checktime_id'], // 贯穿全程
                                        'content_id' => $contentData['id'],
//                                        'field_id' => $fieldId
                                    ];

                                    if (SDMHelper::app()->form->getIsProcess($contentDataRow['form_id'])) {
                                        unset($con['content_id']);
                                        unset($con['checktime_id']);
                                    }

                                    if ($isDelete === false) {
                                        // 把所有旧数据都清理掉
                                        Laminas::$serviceManager->patientFormContentImg->update(['is_del' => 1], $con);
                                        $isDelete = true;
                                    }

                                    foreach ($rowImg as $image) {
                                        $src = DataHelper::handleImageSrc($image['url']);
                                        $condition = array_filter([
                                            'item_id' => $contentDataRow['item_id'],
                                            'itemsig_id' => $contentDataRow['itemsig_id'],
                                            'patient_id' => $contentDataRow['patient_id'],
                                            'form_id' => $contentDataRow['form_id'],
                                            'checktime_id' => $contentDataRow['checktime_id'],
                                            'img_src' => $src,
                                            'img_name' => $image['name'],
//                                            'img_type' => PatientFormContentImg::IMG_TYPE_NORMAL,
                                            'content_id' => $contentData['id'],
//                                            'field_id' => $fieldId
                                        ]);

                                        $hasImg = Laminas::$serviceManager->patientFormContentImg->fetchOne([
                                            'where' => $condition
                                        ]);

                                        $getType = function ($versionField) use ($contentDataRow) {
                                            if ($versionField['type'] != FormField::FORM_FIELD_TYPE_UPLOAD_IMAGE) {
                                                return 0;
                                            }

                                            if ($versionField['var_name'] == 'CHECKIMG') {
                                                if (SDMHelper::app()->form->getGroupId($contentDataRow['form_id']) == FormGroup::CHECK_DO) {
                                                    return PatientFormModel::ANNEX_TYPE_DO;
                                                }
                                                return 1;
                                            } elseif (in_array($versionField['var_name'], ['OUTPLANCHECK', 'OPCH'])) {
                                                return 2;
                                            }

                                            return 0;
                                        };
                                        // 没有就insert, 有就把is_del 改成0
                                        if (!$hasImg) {
                                            $versionData = SDMHelper::app()->form->getVersionData($contentDataRow['form_id']);
                                            $type = $getType($versionData[$fieldId]);
                                            Laminas::$serviceManager->patientFormContentImg->save(ArrayHelper::merge($condition, [
                                                'img_type' => $type == 0 ? PatientFormContentImg::IMG_TYPE_NORMAL : $type,
                                                'field_id' => $fieldId,
                                                'create_time' => time()
                                            ]));
                                        } else {
                                            Laminas::$serviceManager->patientFormContentImg->update([
                                                'is_del' => 0,
                                                'field_id' => $fieldId,
                                            ], ['id' => $hasImg['id']]);
                                        }
                                    }



//                                    var_dump($fieldId);
                                    echo "正在处理 {$contentId} 的 {$fieldId}" . PHP_EOL;
                                    var_dump($rowImg);
                                    var_dump($imgDataItem);
                                    $fix = true;
                                    echo '图片数量不符' . PHP_EOL;
                                }
                            }
                        }

                        if ($has === false) {
                            Laminas::$serviceManager->patientFormContentImg->update(['is_del' => 1], [
                                'content_id' => $contentId
                            ]);
                        }
                    }
//                   if ($fix === true) {
//                       echo '图片数量不符' . PHP_EOL;
//                   }
                }
            }




//
//            var_dump($query);die;
        }


die;
            echo "已处理 $id , 共计 $maxCount 条" . PHP_EOL;
            foreach ($query as $item) {
                $newData = $item['new_data'] ? unserialize($item['new_data']) : '';
                $oldData = $item['old_data'] ? unserialize($item['old_data']) : '';
                $note = $item['change_data'];
//                if (!$oldData && stripos(explode(':', $note)[0], '新增') !== false) {
////                    echo '新增';
//                } elseif ($newData && $oldData && stripos(explode(':', $note)[0], '修改') !== false) {
////                    echo '编辑';
//                }

                $helper = SDMHelper::app()->setAttributes(['content_id' => $item['event_id']])->formContent;

                if (Laminas::$serviceManager->patientFormContentUpdatedLog->fetchOne([
                    'where' => ['create_time' => $item['create_time'], 'content_id' => $item['event_id']]
                ])) {
                    echo "跳过 content_id {$item['event_id']}" . PHP_EOL;
                    continue;
                }
                $contentLog = [
                    'item_id' => $helper->getItemId(),
                    'patient_id' => $helper->getPatientId(),
                    'form_id' => $helper->getFormId(),
                    'checktime_id' => $helper->getCheckTimeId(),
                    'content_id' => $helper->getContentId(),
                    'data' => json_encode($newData),
                    'source' => 'HISTORY',
                    'create_time' => $item['create_time'],
                    'create_user_id' => $item['user_id']
                ];

//                var_dump($contentLog);
                Laminas::$serviceManager->patientFormContentUpdatedLog->isSetInfo(false)->save($contentLog);
            }

        die('处理完了');


        $forms = ArrayHelper::getColumn(Laminas::$serviceManager->itemForm->fetchAll([
            'where' => [
                'type' => Form::FORM_TYPE_SINGLE,
                'is_del' => 0
            ]
        ]), 'id');

        $arr = [];

        $query = Laminas::$serviceManager->patientFormContent->fetchAll([
            'where' => ['form_id' => $forms]
        ]);

        foreach ($query as $item) {
            $arr[$item['patient_id']][$item['form_id']][] = $item;
        }


        foreach ($arr as $patientId => $arrItem) {
            foreach ($arrItem as $formId => $v) {
                if (count($v) > 1) {
                    $lock = $unlock = [];
                    $lockOperate = Laminas::$serviceManager->patientFormContentUpdatedLog->fetchOne([
                        'where' => ['event' => 'LOCK_SHARE_FORM_CONTENT', 'form_id' => $formId, 'checktime_id' => 2, 'patient_id' => $patientId]
                    ]);
                    foreach ($v as $row) {
                        if (abs($lockOperate['create_time'] - $row['create_time']) < 1000) {
                            $lock[] = $row['id'];
                        } else {
                            $unlock[] = $row['id'];
                        }
                    }
var_dump('lockEvent', $lockOperate['create_time']);
var_dump('锁定', $lock);
var_dump('未锁定', $unlock);
                    Laminas::$serviceManager->patientFormContent->update([
                        'is_del' => 1
                    ], ['id' => $unlock]);

                    Laminas::$serviceManager->patientFormContent->update([
                        'is_del' => 0,
                        'is_lock' => 1
                    ], ['id' => $lock]);
                }
            }
        }
        die;
//        $this->LocalService()->itemFormFieldRadio->update([
//            'relation_information' => '301136'
//        ], ['field_id' => 277216]);

// relation_classification: 2
//relation_type: 1
//relation_information: 277219
//        $this->LocalService()->itemFormFieldRadio->update([
//            'relation_information' => '277219',
//            'relation_type' => '1',
//            'relation_classification' => '2',
//        ], ['field_id' => 277217,]);

        $forms = $this->LocalService()->itemForm->fetchAll([
            'where' => [
                'id' => 4,
                'is_del' => 0
            ]
        ]);

        foreach ($forms as $formId) {
            $this->LocalService()->itemFormFieldRadio->update([
                'is_check' => 0,
            ], ['form_id' => $formId['id']]);

            $v = $this->LocalService()->itemForm->buildFieldVersion($formId['id']);

            $this->LocalService()->itemFormVersion->update(['field' => $v], ['form_id' => $formId['id']]);
        }
        die;

        die;
        $query = Laminas::$serviceManager->patientFormContent->fetchAll([
            'where' => [
//                    new Between('id', $id, $id + 200)
//                    'id' => 239432
//                'itemsig_id' => 377
            ]
        ]);

        foreach ($query as $item) {
            $generateFields = Laminas::$serviceManager->itemForm->getPreviewConfig($item['form_id'], true)['generateFields'];
            $score = false;
            $scoreStr = [];
            $data = StringHelper::jsonDecode($item['data']);
            $versionData = Laminas::$serviceManager->itemFormVersion->getField(['form_id' => $item['form_id']], true);

            foreach ($data as $k => &$datum) {
                $field = stripos($k, '-') !== false ? explode('-', $k)[0] : $k;
                // 有分的先不处理
//                    if (isset($data['score'])) {
//                        continue;
//                    }
                if (isset($versionData[$field]) && $versionData[$field]['type'] == 10) {
                    $child = ArrayHelper::index($versionData[$field]['children'] ?? [], 'value');

                    if ($child && is_array($child) && isset($child[$datum]) && $child[$datum]['is_score'] == 1 && in_array($k, $generateFields)) {
                        if ($score === false) {
                            $score = 0;
                        }
                        $score += $child[$datum]['score'];
                        $scoreStr[] = ['prop' => strval($k), 'score' => intval($child[$datum]['score']), 'is_score' => true];
                    }
                }
            }

            if ($score !== false) {
                $data['score'] = strval($score);
                $data['scoreStr'] = $scoreStr;
                echo "contentId {$item['id']} 分值为 {$score} 分 patient: {$data['patient_id']} checktime_id: {$data['checktime_id']} formId: {$data['form_id']}" . PHP_EOL;
                Laminas::$serviceManager->patientFormContent->isSetInfo(false)->update(['data' => json_encode($data), 'update_time' => $item['update_time']], ['id' => $item['id']]);
            }
        }
//            die;
//            var_dump(memory_get_usage());
//        }

        die;


        Laminas::$serviceManager->redisExtend->setDatabase(13)->getRedisInstance()->set('1234', 1234);
        Laminas::$serviceManager->redisExtend->setDatabase(13)->getRedisInstance()->set('@@@@', 1234);
        Laminas::$serviceManager->redisExtend->getRedisInstance()->set('AAA', 1234);
        Laminas::$serviceManager->redisExtend->getRedisInstance()->set('BBBB', 1234);
        die;

        $a = new PatientFormModel();
        $a->setPostValues([
            'form_id' => 90694,
            'patient_id' => 9010,
        ]);
        $val = $a->view();
        var_dump($val);die;
        // 305557,305556, 305555, 305563, 305558, 305559, 305560, 305561, 305562, 305541, 305542, 305543

        Laminas::$serviceManager->itemFormField->update(['is_del' => 1], ['id' => [305557,305556, 305555]]);
        $v = $this->LocalService()->itemForm->buildFieldVersion(90699);
        $this->LocalService()->itemFormVersion->update(['field' => $v], ['form_id' => 90699]);
        die;
//        $ocrData = '{"85209": [{"263962": {"id": "263962", "name": "CASS位置", "value": "-7", "ocr_name": "CASS位置", "var_name": "CASS"}, "263970": {"id": "263970", "name": "描述", "value": "B1型病变", "ocr_name": "描述", "var_name": "OTH"}, "263972": {"id": "263972", "name": "狭窄程度", "value": "75%", "ocr_name": "狭窄程度", "var_name": "XZ"}, "263973": {"id": "263973", "name": "病变形态", "value": "节段、偏心、累及分支", "ocr_name": "病变形态", "var_name": "PAMO"}, "263975": {"id": "263975", "name": "病变部位", "value": "1前降支中段", "ocr_name": "介入部位名称", "var_name": "NAME"}}], "85210": [{"263977": {"id": "263977", "name": "支架名称", "value": "药物洗脱冠脉支架系统RSINT", "ocr_name": "支架装置名称", "var_name": "ZNAM"}, "263978": {"id": "263978", "name": "直径", "value": "3.0", "ocr_name": "直径", "var_name": "DIAM"}, "263979": {"id": "263979", "name": "长度", "value": "30", "ocr_name": "长度", "var_name": "LEN"}, "263980": {"id": "263980", "name": "置入部位", "value": "LAD病变处", "ocr_name": "置入/扩张部位", "var_name": "POS"}}], "85211": [{"263982": {"id": "263982", "name": "球囊名称", "value": "一次性使用血管内球囊扩张导管WOTE", "ocr_name": "球囊装置名称", "var_name": "QNAM"}, "263983": {"id": "263983", "name": "直径", "value": "2.0", "ocr_name": "直径", "var_name": "QDIA"}, "263984": {"id": "263984", "name": "长度", "value": "20", "ocr_name": "长度", "var_name": "QLEN"}, "263985": {"id": "263985", "name": "扩张部位", "value": "LAD病变处", "ocr_name": "置入/扩张部位", "var_name": "EXS"}}, {"263982": {"id": "263982", "name": "球囊名称", "value": "冠脉球囊导管Quantum", "ocr_name": "球囊装置名称", "var_name": "QNAM"}, "263983": {"id": "263983", "name": "直径", "value": "3.25", "ocr_name": "直径", "var_name": "QDIA"}, "263984": {"id": "263984", "name": "长度", "value": "15", "ocr_name": "长度", "var_name": "QLEN"}, "263985": {"id": "263985", "name": "扩张部位", "value": "LAD支架内", "ocr_name": "置入/扩张部位", "var_name": "EXS"}}, {"263982": {"id": "263982", "name": "球囊名称", "value": "冠脉球囊导管Quantum", "ocr_name": "球囊装置名称", "var_name": "QNAM"}, "263983": {"id": "263983", "name": "直径", "value": "3.75", "ocr_name": "直径", "var_name": "QDIA"}, "263984": {"id": "263984", "name": "长度", "value": "12", "ocr_name": "长度", "var_name": "QLEN"}, "263985": {"id": "263985", "name": "扩张部位", "value": "LAD支架内", "ocr_name": "置入/扩张部位", "var_name": "EXS"}}]}';
//        $params = [
//            'patient_id' => 9316,
//            'form_id' => 90689,
//            'checktime_id' => 202402,
//        ];
        $model = new \Application\Form\item\patient\NormalOCRFormModel();
        $model->importMultiRow(82016);
        die;
        $handleCount = 200;
        $maxCount = Laminas::$serviceManager->patientFormContentUpdatedLog->fetchOne([
            'order' => 'id DESC',
        ])['id'];


        for ($id = 0; $id < $maxCount; $id  = $id + $handleCount) {
            $query = Laminas::$serviceManager->patientFormContentUpdatedLog->fetchAll([
                'where' => [
                    new Between('id', $id + 1, $id + $handleCount),
                ]
            ]);

            echo "已处理 $id , 共计 $maxCount 条" . PHP_EOL;
            $container = [];
            foreach ($query as $item) {
                if (!isset($container[$item['patient_id']])) {
                    $container[$item['patient_id']] = Laminas::$serviceManager->patient->fetchOne([
                        'where' => [
                            'id' => $item['patient_id'],
                            'is_del' => 0
                        ]
                    ])['itemsig_id'] ?? false;

                    if ($container[$item['patient_id']] === false) {
                        echo '受试者' . $item['patient_id'] . '有问题??' . PHP_EOL;
                        continue;
                    }
                }

                Laminas::$serviceManager->patientFormContentUpdatedLog->isSetInfo(false)->update([
                    'sign_id' => $container[$item['patient_id']]
                ], ['id' => $item['id']]);
            }
        }

        die('处理完了');
        return 0;
        die;
        Laminas::$serviceManager->itemFormField->update(['type' => FormField::FORM_FIELD_TYPE_DATE_UK], ['id' => 301227]);
        $v = $this->LocalService()->itemForm->buildFieldVersion(90373);
        $this->LocalService()->itemFormVersion->update(['field' => $v], ['form_id' => 90373]);

die;
        $query = Laminas::$serviceManager->itemPatientAeContent->fetchAll([
            'where' => [
                'ae_type' => 6,
                'is_del' => 0
            ]
        ]);

        foreach ($query as $v) {
            $has = Laminas::$serviceManager->itemCsaeRelation->fetchAll([
                'where' => [
                    'csae_id' => $v['csae_id'],
                    'new_ae_list_id' => 0,
                    'content_id' => $v['id'],
                    'patient_id' => $v['patient_id'],
                    'branch' => $v['branch']
                ]
            ]);

            if (!$has) {
                var_dump($v);
            }
        }

        var_dump('ok');die;
        $handleCount = 200;
        $maxCount = Laminas::$serviceManager->adminLog->fetchOne([
            'order' => 'id DESC',
        ])['id'];


        for ($id = 0; $id < $maxCount; $id  = $id + $handleCount) {
            $query = Laminas::$serviceManager->adminLog->fetchAll([
                'where' => [
                    new Between('id', $id + 1, $id + $handleCount),
                    'log_url' => '/patient/form/create',
//                    'id' => 81566
                ]
            ]);

            echo "已处理 $id , 共计 $maxCount 条" . PHP_EOL;
            foreach ($query as $item) {
                $newData = $item['new_data'] ? unserialize($item['new_data']) : '';
                $oldData = $item['old_data'] ? unserialize($item['old_data']) : '';
                $note = $item['change_data'];
//                if (!$oldData && stripos(explode(':', $note)[0], '新增') !== false) {
////                    echo '新增';
//                } elseif ($newData && $oldData && stripos(explode(':', $note)[0], '修改') !== false) {
////                    echo '编辑';
//                }

                $helper = SDMHelper::app()->setAttributes(['content_id' => $item['event_id']])->formContent;

                if (Laminas::$serviceManager->patientFormContentUpdatedLog->fetchOne([
                    'where' => ['create_time' => $item['create_time'], 'content_id' => $item['event_id']]
                ])) {
                    echo "跳过 content_id {$item['event_id']}" . PHP_EOL;
                    continue;
                }
                $contentLog = [
                    'item_id' => $helper->getItemId(),
                    'patient_id' => $helper->getPatientId(),
                    'form_id' => $helper->getFormId(),
                    'checktime_id' => $helper->getCheckTimeId(),
                    'content_id' => $helper->getContentId(),
                    'data' => json_encode($newData),
                    'source' => 'HISTORY',
                    'create_time' => $item['create_time'],
                    'create_user_id' => $item['user_id']
                ];

//                var_dump($contentLog);
                Laminas::$serviceManager->patientFormContentUpdatedLog->isSetInfo(false)->save($contentLog);
            }
        }
        die('处理完了');
        return 0;
    }

    private function handleChild($child, $fieldId = null)
    {
        echo 'FIELD_ID -> ' . $fieldId . PHP_EOL;
//        if (isset($child['children'])) {
//            $this->handleChild($child['children']);
//        }

        $itemData = [];
        $formType = 'TEXT';
        foreach ($child['relation'] ?? $child['children'] as $k => $item) {
            if ($item['info_from'] == 0) {
                $k = $item['info_id'];
                if (!$this->migrateData['batchContents']['content'][$k]) {
                    if ($item['p']) {
                        $k = "{$item['info_id']}-{$item['p']}";
                        if (!$this->migrateData['batchContents']['content'][$k]) {
                            throw new \Exception("not found info id!!!!{$item['info_id']}-{$item['p']}");
                        }
                    }
                }
                $itemData['parent'] = $item['parent_id'];

                $itemData = $this->migrateData['batchContents']['content'][$k];
            } elseif ($item['info_from'] == 1) {
                $formType = 'RADIO';
                if (!$this->migrateData['batchContents']['options'][$item['info_id']]) {
                    throw new \Exception("not found info id{$item['info_id']}");
                }


                $itemData = $this->migrateData['batchContents']['options'][$item['info_id']];
                $itemData['parent'] = $item['parent_id'];
            } elseif ($item['info_from'] == 2) {
                if (!$this->migrateData['batchContents']['content']['info_id']) {
                    throw new \Exception("not found info id###");
                }

                $itemData = $this->migrateData['content']['info_id'];
            }


            $itemData['form_id'] = $this->formId;
            $itemData['name'] = $itemData['tips'];
            unset($itemData['tips']);
            if (!$itemData['name']) {
                if ($item['info_from'] != 3) {
                    $itemData['name'] = $itemData['form_option'] ?? '??????????';
                } else {
                    $itemData['name'] = '5555555';
                }
            }

            $itemData['type'] = self::CONTENT_MAP[$itemData['content_type']] ?? 0;
            $itemData['parent'] = $this->branchMap[$itemData['parent']] ?? 0;
            $itemData['form_type'] = $formType;
            $itemData['value'] = $k;
            $itemData['relation_classification'] = 2;
            $itemData['relation_type'] = 1;

            $itemData['relation_information'] = $itemData['parent'];
            $itemData['is_list'] = 0;
            $itemData['is_anchor'] = $itemData['content_type'] == 13 ? 1 : 0;
            $itemData['is_booked_time'] = 0;
            $itemData['item_id'] = 2;
            $itemData['origin_form_id'] = $itemData['form_id'];
            $v = new ValidatorApplication($itemData);
            $v->attach(
                [['form_id', 'item_id'], 'required'],
                [['form_type'], 'default', 'value' => FieldForm::FORM_CONFIG_TEXT],
                [['is_list', 'is_booked_time'], 'default', 'value' => 0]
            );
            $model = new ItemFieldForm($v);
            $fieldId = $model->createField();
            if ($itemData['type'] != 0) {
                if (isset($itemData['parent_id']) && isset($this->branchMap[$itemData['parent_id']])) {
                    $this->mainId = $this->branchMap[$itemData['parent_id']];
                } else {
                    $this->mainId = $fieldId;
                }
                $this->branchMap[$item['info_id']] = $fieldId;
            }

            if (isset($item['children'])) {
                if ($item['info_from'] == 3) {
                    $item['p'] = $item['info_id'];
                }
                $this->handleChild($item, $fieldId);
            }
        }
    }

}

