<?php

namespace Application\Form\item\patient;

use Application\Form\project\AeForm;
use Application\Service\DB\Dictionary\Form;
use Application\Service\DB\Dictionary\FormField;
use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\DataHelper;
use Application\Service\Extension\Helper\ExcelHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Validator\ValidatorApplication;
use Laminas\Db\Sql\Predicate\Expression;
use Laminas\Db\Sql\Where;
date_default_timezone_set('Asia/Shanghai');

class ImportForm
{
    /**
     * 当前执行的受试者id
     * @var int
     */
    private int $currentPatientId = 0;

    /**
     * 当前执行的受试者的随机号
     * @var int
     */
    private int $currentPatientRandomId = 0;

    /**
     * @var int
     */
    private int $currentItemId = 0;

    /**
     * 当前执行的项目父id
     * @var int
     */
    private int $currentItemFid = 0;

    /**
     * 当前执行项目的中心id
     * @var int
     */
    private int $currentSignId = 0;

    /**
     * 当前执行的检查点id
     * @var int
     */
    private int $currentCheckTimeId = 0;

    /**
     * 当前执行的阶段id
     * @var int
     */
    private int $currentStageId = 0;

    /**
     * 当前执行的excel sheet 索引
     * @var int|null
     */
    private ?int $currentSheetIndex = 0;

    /**
     * 当前执行的excel sheet 标题
     * @var string|null
     */
    private ?string $currentSheetIndexTitle = null;

    /**
     * 当前执行的行数
     * @var int|null
     */
    private ?int $currentRowLine = 1;

    /**
     * 当前执行的表单id
     * @var int
     */
    private int $currentFormId = 0;

    /**
     * 当前执行表单的类型
     * @var int
     */
    private int $currentFormType = 0;

    /**
     * 表单类
     * @var int
     */
    private int $currentFormGroupId = 0;

    /**
     * 表单渲染缓存
     * @var array
     */
    private array $previewConfig = [];

    /** @var array 表单首层渲染缓存 */
    private array $previewConfigFirstLevel = [];

    /**
     * version数据缓存
     * @var array
     */
    private array $versionData = [];

    /**
     * field字段缓存
     * @var array
     */
    private array $field = [];

    /**
     * field字段数据缓存
     * @var array
     */
    private array $fieldInfo = [];

    /**
     * 表单flowCat字段缓存
     * @var array
     */
    private array $flowCat = [];

    /**
     * 追加的随机号
     * @var array|null
     */
    private ?array $appendFieldRandom = null;

    /**
     * 追加的分值
     * @var int|null
     */
    private ?int $appendFieldScore = null;

    /**
     * 追加的分值str
     * @var array|null
     */
    private ?array $appendFieldScoreStr = null;

    /**
     * 运行错误
     * @var array
     */
    private array $errorMessage = [];

    private array $isDeleteMultiData = [];

    /**
     * 是否是ae表单
     * @var bool
     */
    private bool $isAeForm = false;

    /**
     * 缓存key
     * @var array
     */
    public static array $dataCache = [];

    /**
     * 层级数据缓存
     * @var array
     */
    static array $level = [];

    /**
     * 导入的最大数量
     * @var int
     */
    public int $importMaxCount = 2000;

    public array $error = [];

    const DEFAULT_COLUMNS = [
        'INVSITE',
        'PT',
        'SUBNAM',
        'CPEVENT',
        'FORM_SEQ'
    ];

    //化验单时间格式
    public $dateFormat = '';

    public $improtExecuteKey = 'task:improtExecute';

    public $importProcessKey = 'task:importProcess';

    public $filePath = '';

    public $itemsig_id = '';

    public function __construct($item_id)
    {
        $this->improtExecuteKey.= ':'.$item_id;
        $this->importProcessKey.= ':'.$item_id;
        $this->dateFormat = Laminas::$serviceManager->itemCheckdate->getDateType($item_id);
        $this->filePath = APP_PATH.'/data/import'.$item_id.'txt';
    }

    //设置文件路径
//    public function setFilePath($item_id)
//    {
//        $this->filePath = APP_PATH.'/data/import'.$item_id.'txt';
//    }

    //错误数据
    public function getErrorMessage()
    {
        return $this->errorMessage;
    }

    //获取化验单时间格式
//    public function getDateFormat($item_id)
//    {
//        return $this->dateFormat = Laminas::$serviceManager->itemCheckdate->getDateType($item_id);
//    }

    //获取检查项
    public function getChecknameData($item_id)
    {
        //获取所有的检查分类以及检查项
        $checknameDatas = Laminas::$serviceManager->itemCheckname->fetchAll([
            'where'=>['is_del'=>0,'item_id'=>$item_id],
            'columns'=>['id','name','unit','max_val','min_val','check_type','category_id'],
            'order'=>'checkname_order'
        ]);
        $checkname = $categoryDatas = [];
        if(!empty($checknameDatas)){
            $categoryID = array_column($checknameDatas,'category_id');

            $categoryDatas = Laminas::$serviceManager->dictionaryCheckcategory->fetchCol('category_name',['id'=>$categoryID]);

            foreach ($checknameDatas as $info){
                $checkname[$categoryDatas[$info['category_id']]][] = $info;
            }
            unset($categoryID);
        }
        return [$checkname,$categoryDatas];
    }

    //表单
    public function import($tmpFile)
    {
        $exportData = (ExcelHelper::importForm($tmpFile['tmp_name'], 1));
        $totalCount = 0;
        $maxCount = $this->importMaxCount;
        foreach ($exportData as $datum) {
            $totalCount += count($datum) - 2;
        }

        // 限制最大导入数量
        if ($totalCount > $maxCount) {
            throw new InvalidArgumentException("导入总数不能大于 {$maxCount}。");
        }

        // 用来存储当前sheet的变量名
        $sheetCache = $isFetch = $contentList = [];
        foreach ($exportData as $sheetTitle => $allRowData) {
            // 清理表单version数据缓存

            foreach ($allRowData as $row => $rowData) {

                try {
                    // 第一行是变量名
                    if ($row == 1) {
                        $sheetCache[$sheetTitle] = $rowData;
                        try {
                            $this->checkTemplate($rowData);
                        } catch (\Throwable $e) {
                            $this->errorMessage[] = $e->getMessage() . "。表格: {$sheetTitle}。";
                            break;
                        }
                        continue;
                    } elseif ($row == 2) { // 第二行没用
                        continue;
                    }

                    $export = function () use ($allRowData, $sheetTitle, $sheetCache, $rowData, $row, $isFetch) {
                        $this->currentRowLine = $row;
                        $this->currentSheetIndexTitle = $sheetTitle;
                        // 重置数据
                        $this->resetExecuteInfo();
                        $submitData = [];

                        // 当前导入的表单数据是否什么都没写
                        $isEmptyData = true;

                        // 当前行数据
                        foreach ($rowData as $k => $v) {
                            if ($k == 0 && !$v) {
                                return;
                            }
                            if ($sheetCache[$sheetTitle][$k] === 'INVSITE') { // 项目id
                                $submitData['item_id'] = $this->getItemId($v);
                                $submitData['form_id'] = $this->getFormId($sheetTitle);
                            } elseif ($sheetCache[$sheetTitle][$k] === 'PT') {// 中心
                                $submitData['itemsig_id'] = $this->getItemSigId($v);
                            } elseif ($sheetCache[$sheetTitle][$k] === 'SUBNAM') { // 筛选号
                                $submitData['patient_id'] = $this->getPatientId($v, $rowData[$k + 1]);
                            } elseif ($sheetCache[$sheetTitle][$k] === 'CPEVENT') { // 姓名
                                continue;
                            } elseif ($sheetCache[$sheetTitle][$k] === 'FORM_SEQ') { // 检查点z
                                $submitData['checktime_id'] = $this->getCheckTimeId($v);
                            } elseif (!in_array($sheetCache[$sheetTitle][$k], self::DEFAULT_COLUMNS) && $sheetCache[$sheetTitle][$k]) { // 如果当前变量名不在默认列里 并且这个列有变量名

                                // 生成对应的字段id, 因为有可能是关联的字段
                                $generateFieldId = $this->getGenerateFieldId($sheetCache[$sheetTitle][$k]);
                                if ($generateFieldId !== false && $this->getIsValidField($submitData, $generateFieldId)) {

                                    // 表单字段值
                                    $submitVal = $this->handleValue($v, $generateFieldId);

                                    $submitData[$generateFieldId] = $submitVal;

                                    if ($submitVal !== '') {
                                        $isEmptyData = false;
                                    }

                                    // 加入层级的数据, 因为导入关联字段是不分层级的。需要自己处理哪些字段是关联的
                                    if (isset(self::$level[$generateFieldId])) {
                                        self::$level[$generateFieldId] = $v;
                                    }
                                }
                            }
                        }

                        // 空数据不导入
                        if ($isEmptyData === true) {
                            return;
                        }
                        $this->appendField($submitData);



                        // 一对多的表单, 要把旧数据全部删除
//                        if ($this->currentFormType == Form::FORM_TYPE_MULTI && !isset($this->isDeleteMultiData[$this->currentPatientId])) {
//                            $this->flush();
//                        } else {
//                            if (!isset($isFetch[$this->currentItemId])) {
//                                $allContent = Laminas::$serviceManager->patientFormContent->memoryCache()->fetchAll([
//                                    'columns' => ['id', 'patient_id', 'item_id', 'checktime_id', 'form_id', 'is_del'],
//                                    'where' => [
//                                        'item_id' => $this->currentItemId,
////                                        'patient_id'=>$submitData['patient_id'],
//                                        'is_del' => 0
//                                    ]
//                                ]);
//
//                                $isFetch[$this->currentItemId] = true;
//                                $contentList = [];
//                                foreach ($allContent as &$content) {
//                                    $key = "{$content['patient_id']}{$content['item_id']}{$content['checktime_id']}{$content['form_id']}";
//                                    $contentList[$key] = $content['id'];
//                                }
//                            }
//
//                            $key = "{$this->currentPatientId}{$this->currentItemId}{$this->currentCheckTimeId}{$this->currentFormId}";
//                            $has['id'] = $contentList[$key] ?? null;
//                        }

                        if ($this->isAeForm === true) {
                            $v = new ValidatorApplication($submitData);
                            $model = new AeForm($v);
                            $model->createNewAeV2();
                        } else {

                            $submitData['id'] = $has['id'] ?? false;
                            $v = new ValidatorApplication($submitData);
                            $model = new PatientFormModel($v);
                            $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                            $model->validator->attributes['is_import'] = 1;
                            if ($this->currentFormType == Form::FORM_TYPE_MULTI) {
                                $model->createForm($submitData);
                            } else {
                                if (isset($has['id'])) {
                                    $model->editForm($submitData);
                                } else {
                                    unset($submitData['id']);
                                    $model->createForm($submitData);
                                }
                            }
                        }
                    };
                    $export();
                } catch (\Throwable $e) {
                    $this->errorMessage[] = $e->getMessage() . "。表格: {$this->currentSheetIndexTitle}。行数: {$this->currentRowLine}。";
                }
            }
            $this->currentSheetIndex++;
            $this->isDeleteMultiData = [];
        }
    }

    //化验单
    public function importCheckForm($tmpFile,$item_id,$itemsig_id)
    {
        $this->itemsig_id = $itemsig_id;
        //获取化验单时间类型
        $dateFormat = $this->dateFormat;

        //当前时间
        $time = time();

        //获取excel数据
        $exportData = (ExcelHelper::importForm($tmpFile['tmp_name'], 1));

        //获取表单数量
        $totalCount = 0;
        $maxCount = $this->importMaxCount;
        foreach ($exportData as $datum) {
            $totalCount += count($datum) - 2;
        }

        // 限制最大导入数量
        if ($totalCount > $maxCount) {
            throw new InvalidArgumentException("导入总数不能大于 {$maxCount}。");
        }

        //检查项
        list($checkname,$categoryDatas) = $this->getChecknameData($item_id);

        $form = Laminas::$serviceManager->itemForm->fetchAll(['where'=>['is_del'=>0,'item_id'=>$item_id,'group_id'=>7],'columns'=>['id','name','checklist_id']]);
        $formDatas = [];
        foreach($form as $formV){
            $formDatas[$formV['name']] = $formV['checklist_id'];
        }

        // 用来存储当前sheet的变量名
        $sheetCache = $isFetch = $contentList = [];

        foreach ($exportData as $sheetTitle => $allRowData) {
            //formGroup 当前表单状态 1表单 2化验单

            $submitData = [];
            //  表单
            if(empty($formDatas[$sheetTitle])){
                $formGroup = 1;
            }else{
                //化验单
                $formGroup = 2;

                $checkName = $categoryDatas[$formDatas[$sheetTitle]];

                // 清理表单version数据缓存
                $checknamesCount = count($checkname[$checkName]);

                $handleCount = 0;

                $collectDate = '';

                $content = [];
            }

            foreach ($allRowData as $row => $rowData) {
                try {
                    // 第一行是变量名
                    if ($row == 1) {
                        $sheetCache[$sheetTitle] = $rowData;
                        try {
                            $this->checkTemplate($rowData);
                        } catch (\Throwable $e) {
                            $this->errorMessage[] = $e->getMessage() . "。表格: {$sheetTitle}。";
                            break;
                        }
                        continue;
                    } elseif ($row == 2) { // 第二行没用
                        continue;
                    }

                    if($formGroup == 1){
                        $this->error = [];

                        $isEmptyData = true;

                        // 当前行数据
                        foreach ($rowData as $k => $v) {
                            if ($k == 0 && !$v) {
                                return;
                            }
                            if ($sheetCache[$sheetTitle][$k] === 'INVSITE') { // 项目id
                                $submitData['item_id'] = $this->getItemId($v);
                                $submitData['form_id'] = $this->getFormId($sheetTitle);
                            } elseif ($sheetCache[$sheetTitle][$k] === 'PT') {// 中心
                                $submitData['itemsig_id'] = $this->getItemSigId($v);
                            } elseif ($sheetCache[$sheetTitle][$k] === 'SUBNAM') { // 筛选号
                                $submitData['patient_id'] = $this->getPatientId($v, $rowData[$k + 1]);
                            } elseif ($sheetCache[$sheetTitle][$k] === 'CPEVENT') { // 姓名
                                continue;
                            } elseif ($sheetCache[$sheetTitle][$k] === 'FORM_SEQ') { // 检查点z
                                $submitData['checktime_id'] = $this->getCheckTimeId($v);
                            } elseif (!in_array($sheetCache[$sheetTitle][$k], self::DEFAULT_COLUMNS) && $sheetCache[$sheetTitle][$k]) { // 如果当前变量名不在默认列里 并且这个列有变量名
                                // 生成对应的字段id, 因为有可能是关联的字段
                                $generateFieldId = $this->getGenerateFieldId($sheetCache[$sheetTitle][$k]);

                                if ($generateFieldId !== false && $this->getIsValidField($submitData, $generateFieldId)) {

                                    // 表单字段值
                                    $submitVal = $this->handleValue($v, $generateFieldId);

                                    $submitData[$generateFieldId] = $submitVal;

                                    if ($submitVal !== '') {
                                        $isEmptyData = false;
                                    }

                                    // 加入层级的数据, 因为导入关联字段是不分层级的。需要自己处理哪些字段是关联的
                                    if (isset(self::$level[$generateFieldId])) {
                                        self::$level[$generateFieldId] = $v;
                                    }
                                }
                            }
                        }

                        // 空数据不导入
                        if ($isEmptyData === true) {
                            continue;
                        }
                        $this->appendField($submitData);

                        if ($this->currentFormType == 1) {
                            $v = new ValidatorApplication($submitData);
                            $model = new PatientFormModel($v);
                            $model->validator->attributes['is_import'] = 1;
                            $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                            $result = $model->createFormImport($submitData);
                        } else {
                            $contentId = Laminas::$serviceManager->patientFormContent->getOneFieldVal('id',[
                                'item_id' => $item_id,
                                'patient_id'=>$submitData['patient_id'],
                                'checktime_id'=>$submitData['checktime_id'],
                                'form_id'=>$submitData['form_id'],
                                'is_del' => 0
                            ]);

                            if ($contentId) {
                                $submitData['id'] = $contentId;
                                $v = new ValidatorApplication($submitData);
                                $model = new PatientFormModel($v);
                                $model->validator->attributes['is_import'] = 1;
                                $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                                $result = $model->editFormImport($submitData);
                            } else {
                                unset($submitData['id']);
                                $v = new ValidatorApplication($submitData);
                                $model = new PatientFormModel($v);
                                $model->validator->attributes['is_import'] = 1;
                                $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                                $result = $model->createFormImport($submitData);
                            }
                        }
                        if(!empty($result)){
                            foreach ($result as $errorV){
                                $this->error[] = $errorV;
                            }
                        }

                        $cache['formType'] = $this->currentFormType;
                        $cache['group_id'] = $this->currentFormGroupId;
                        if(empty($this->error)){
                            $cache['sourceData'] = $rowData;
                            $cache['data'] = $submitData;
                        }else{
                            $cache['error'] = $this->error;

                            $cache['sourceData'] = $rowData;

                            unset($submitData['sdtx']);

                            $cache['data'] = $submitData;
                        }
                        $hashValue = StringHelper::generateHashValue();
                        $fileContent = !empty(file_get_contents($this->filePath)) ? json_decode(file_get_contents($this->filePath),true) : [];

                        $fileContent[$hashValue] = json_encode($cache,true);

                        file_put_contents($this->filePath, json_encode($fileContent,true));


                        unset($cache);
                        if(empty($this->error)){
                            Laminas::$serviceManager->redisExtend->getRedisInstance()->hSet($this->improtExecuteKey,$hashValue,$hashValue);
                        }else{
                            Laminas::$serviceManager->redisExtend->getRedisInstance()->hSet($this->importProcessKey,$hashValue,$hashValue);
                        }
                    }else{
                        //首次获取基础数据
                        if($handleCount == 0){
                            // 当前行数据
                            foreach ($rowData as $k => $v) {
                                if ($k == 0 && !$v) {
                                    return;
                                }
                                if ($sheetCache[$sheetTitle][$k] === 'INVSITE') { // 项目id
                                    $submitData['item_id'] = $this->getItemId($v);
                                    $submitData['form_id'] = $this->getFormId($sheetTitle);
                                    //表单结构
                                    if(!isset($rules[$submitData['form_id']])){
                                        $rules[$submitData['form_id']] = Laminas::$serviceManager->itemForm->getPreviewConfig($submitData['form_id'],true)['generateFields'];
                                    }
                                } elseif ($sheetCache[$sheetTitle][$k] === 'PT') {// 中心
                                    $submitData['itemsig_id'] = $this->getItemSigId($v);
                                } elseif ($sheetCache[$sheetTitle][$k] === 'SUBNAM') { // 筛选号
                                    $submitData['patient_id'] = $this->getPatientId($v, $rowData[$k + 1]);
                                } elseif ($sheetCache[$sheetTitle][$k] === 'CPEVENT') { // 姓名
                                    continue;
                                } elseif ($sheetCache[$sheetTitle][$k] === 'FORM_SEQ') { // 检查点z
                                    $submitData['checktime_id'] = $this->getCheckTimeId($v);
                                } elseif ($k == 6) { // 如果当前变量名不在默认列里 并且这个列有变量名
                                    // 1. 如果是纯数字且大于 25569（1970-01-01 的 Excel 序列号），说明是 Excel 日期
                                    if (is_numeric($v) && $v > 25569 && $v < 60000) { // 60000 ~ 2136 年

                                        $unixTimestamp = ($v - 25569) * 86400; // 转 Unix 时间戳

                                        $collectDate =  gmdate($dateFormat, $unixTimestamp);

                                        $formattedDate = strtotime($collectDate);

                                        if($formattedDate > $time){
                                            $this->error[] = '化验单采集日期不能大于当前时间';
                                        }
                                    }elseif (is_string($v) && strtotime($v) !== false) {

                                        if(strtotime($v) > $time){
                                            $this->error[] = '化验单采集日期不能大于当前时间';
                                        }
                                        $collectDate =  date($dateFormat, strtotime($v));
                                    }
                                    if(empty($collectDate)){
                                        $this->error[] = '采集日期不能为空';
                                    }
                                }
                            }
                        }

                        //截取  采集日期	指标名称	测量结果	计数单位	最小值
                        $check = array_slice($rowData, 7, 5);
                        $arr['id'] = $checkname[$checkName][$handleCount]['id'];
                        $arr['check_item'] = $check[0];
                        $arr['result'] = $check[1];
                        $arr['unit'] = $check[2];
                        $arr['min_val'] = $check[3];
                        $arr['max_val'] = $check[4];
                        $arr['check_type'] = $checkname[$checkName][$handleCount]['check_type'];

                        $content[] = $arr;

                        unset($arr);

                        ++$handleCount;

                        if($handleCount == $checknamesCount){

                            $submitData['sdtx'] = json_encode(['check_date'=>$collectDate,'content'=>$content]);

                            if(isset($rules[$submitData['form_id']])){
                                $submitData[$rules[$submitData['form_id']][0]] = "2";
                                $submitData[$rules[$submitData['form_id']][1]] = [];
                                $submitData[$rules[$submitData['form_id']][2]] = [];
                                $submitData[$rules[$submitData['form_id']][3]] = '';
                            }

                            $submitData['old_data_str'] = '';
                            $submitData['childData'] = '{}';

                            $this->appendField($submitData);

                            if ($this->currentFormType == 1) {
                                $v = new ValidatorApplication($submitData);
                                $model = new PatientFormModel($v);
                                $model->validator->attributes['is_import'] = 1;
                                $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                                $result = $model->createFormImport($submitData);
                            } else {
                                $contentId = Laminas::$serviceManager->patientFormContent->getOneFieldVal('id',[
                                    'item_id' => $item_id,
                                    'patient_id'=>$submitData['patient_id'],
                                    'checktime_id'=>$submitData['checktime_id'],
                                    'form_id'=>$submitData['form_id'],
                                    'is_del' => 0
                                ]);
                                if ($contentId) {
                                    $submitData['id'] = $contentId;
                                    $v = new ValidatorApplication($submitData);
                                    $model = new PatientFormModel($v);
                                    $model->validator->attributes['is_import'] = 1;
                                    $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                                    $result = $model->editFormImport($submitData);
                                } else {
                                    unset($submitData['id']);
                                    $v = new ValidatorApplication($submitData);
                                    $model = new PatientFormModel($v);
                                    $model->validator->attributes['is_import'] = 1;
                                    $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                                    $result = $model->createFormImport($submitData);
                                }
                            }
                            if(!empty($result)){
                                foreach ($result as $errorV){
                                    $this->error[] = $errorV;
                                }
                            }

                            $changeDatas = Laminas::$serviceManager->itemIdentificationresultchange->fetchOne([
                                'where'=>['is_del'=>0,'patient_id'=>$submitData['patient_id'],'form_id'=>$submitData['form_id'],
                                    'checktime_id'=>$submitData['checktime_id'],'lock_state'=>1],
                                'columns'=>['id']
                            ]);

                            //化验单已锁定，进行提示
                            if(!empty($changeDatas)){
                                $this->error[] = '此化验单已锁定，不可做数据导入';
                            }

                            $checkGroup = array_slice($allRowData, $row-$checknamesCount, $checknamesCount);
                            foreach($checkGroup as &$value){
                                $value[6] = $collectDate;
                            }

                            $cache['formType'] = $this->currentFormType;
                            $cache['group_id'] = $this->currentFormGroupId;
                            if(empty($this->error)){
                                $cache['sourceData'] = $checkGroup;
                                $cache['data'] = $submitData;
                            }else{
                                $cache['error'] = $this->error;
                                $cache['sourceData'] = $checkGroup;
                                unset($submitData['sdtx']);
                                $cache['data'] = $submitData;
                            }

                            $hashValue = StringHelper::generateHashValue();
                            $fileContent = !empty(file_get_contents($this->filePath)) ? json_decode(file_get_contents($this->filePath),true) : [];

                            $fileContent[$hashValue] = json_encode($cache,true);

                            file_put_contents($this->filePath, json_encode($fileContent,true));

                            if(empty($this->error)){
                                Laminas::$serviceManager->redisExtend->getRedisInstance()->hSet($this->improtExecuteKey,$hashValue,$hashValue);   //一小时
                            }else{
                                Laminas::$serviceManager->redisExtend->getRedisInstance()->hSet($this->importProcessKey,$hashValue,$hashValue);   //一小时
                            }
                            unset($cache);

                            // 一对多的表单, 要把旧数据全部删除
//                        if ($this->currentFormType == Form::FORM_TYPE_MULTI && !isset($this->isDeleteMultiData[$this->currentPatientId])) {
//                            $this->flush(1);
//                        } else {
//                            if (!isset($isFetch[$this->currentItemId])) {
//                                $allContent = Laminas::$serviceManager->patientFormContent->memoryCache()->fetchAll([
//                                    'columns' => ['id', 'patient_id', 'item_id', 'checktime_id', 'form_id', 'is_del'],
//                                    'where' => [
//                                        'item_id' => $this->currentItemId,
//                                        'is_del' => 0
//                                    ]
//                                ]);
//
//                                $isFetch[$this->currentItemId] = true;
//                                $contentList = [];
//                                foreach ($allContent as &$content) {
//                                    $key = "{$content['patient_id']}{$content['item_id']}{$content['checktime_id']}{$content['form_id']}";
//                                    $contentList[$key] = $content['id'];
//                                }
//                            }
//
//                            $key = "{$this->currentPatientId}{$this->currentItemId}{$this->currentCheckTimeId}{$this->currentFormId}";
//                            $has['id'] = $contentList[$key] ?? null;
//                        }
//                        $submitData['id'] = $has['id'] ?? false

//                        $v = new ValidatorApplication($submitData);
//                        $model = new PatientFormModel($v);
//                        $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
//                        $model->validator->attributes['is_import'] = 1;
//
//                        //一对多表单新增，普通表单查看是否有填写过，填写过-》编辑，未填写-》新增
//                        if ($this->currentFormType == Form::FORM_TYPE_MULTI) {
//                            $insertId = $model->createForm($submitData);
//                        } else {
//                            if (isset($has['id'])) {
//                                $model->editForm($submitData);
//                                $insertId = $has['id'];
//                            } else {
//                                unset($submitData['id']);
//                                $insertId = $model->createForm($submitData);
//                            }
//                        }
                            //化验单中间表
//                        Laminas::$serviceManager->swTaskClient->send([
//                            'svName' => 'projectPatientwork',
//                            'methodName' => 'updatePatientworkData',
//                            'params' => [
//                                'item_id' => $submitData['item_id'],
//                                'itemsig_id' => $submitData['itemsig_id'],
//                                'patient_id' => $submitData['patient_id'],
//                                'checktime_id' => $submitData['checktime_id'],
//                                'form_id' => $submitData['form_id'],
//                                'user_id' => Laminas::$serviceManager->identity->getId(),
//                                'content_id' => $insertId
//                            ]
//                        ]);
                            //已处理完一组，重置数据
                            $handleCount = 0;

                            $collectDate = '';

                            $content = [];

                            $submitData = [];

                            $this->resetExecuteInfo();

                            $this->error = [];

                            unset($submitData);
                        }
                    }
//                    $export = function () use ($allRowData, $sheetTitle, $sheetCache, $rowData, $row, $isFetch,$checkname) {
//                        $this->currentRowLine = $row;
//                        $this->currentSheetIndexTitle = $sheetTitle;
//                        // 重置数据
//                        $this->resetExecuteInfo();
//                        $submitData = [];
//
//                        // 当前导入的表单数据是否什么都没写
//                        $isEmptyData = true;
//
//                        // 当前行数据
//                        foreach ($rowData as $k => $v) {
//                            if ($k == 0 && !$v) {
//                                return;
//                            }
//                            if ($sheetCache[$sheetTitle][$k] === 'INVSITE') { // 项目id
//                                $submitData['item_id'] = $this->getItemId($v);
//                                $submitData['form_id'] = $this->getFormId($sheetTitle);
//                                if(!isset($rules[$submitData['form_id']])){
//                                    $rules[$submitData['form_id']] = Laminas::$serviceManager->itemForm->getPreviewConfig($submitData['form_id'],true)['generateFields'];
//                                }
//
//                            } elseif ($sheetCache[$sheetTitle][$k] === 'PT') {// 中心
//                                $submitData['itemsig_id'] = $this->getItemSigId($v);
//                            } elseif ($sheetCache[$sheetTitle][$k] === 'SUBNAM') { // 筛选号
//                                $submitData['patient_id'] = $this->getPatientId($v, $rowData[$k + 1]);
//                            } elseif ($sheetCache[$sheetTitle][$k] === 'CPEVENT') { // 姓名
//                                continue;
//                            } elseif ($sheetCache[$sheetTitle][$k] === 'FORM_SEQ') { // 检查点z
//                                $submitData['checktime_id'] = $this->getCheckTimeId($v);
//                            } elseif ($k == 6) { // 如果当前变量名不在默认列里 并且这个列有变量名
//                                // 1. 如果是纯数字且大于 25569（1970-01-01 的 Excel 序列号），说明是 Excel 日期
//                                if (is_numeric($v) && $v > 25569 && $v < 60000) { // 60000 ~ 2136 年
//                                    $unixTimestamp = ($v - 25569) * 86400; // 转 Unix 时间戳
//                                    $collect_data =  gmdate('Y-m-d', $unixTimestamp);
//                                }elseif (is_string($v) && strtotime($v) !== false) {
//                                    $collect_data =  date('Y-m-d', strtotime($v));
//                                }
//
//                                if(empty($collect_data)){
//                                    return;
//                                }
//                            }
//                        }
//
//                        //根据化验单检查项设置进行处理数据
//
//                        $content = [];
//
//                        foreach($checkname[$sheetTitle] as $k=>$v){
//                            $check = array_slice($rowData, ($k*4)+7, 4);
//                            $arr['id'] = $v['id'];
//                            $arr['result'] = $check[0];
//                            $arr['unit'] = $check[1];
//                            $arr['min_val'] = $check[2];
//                            $arr['max_val'] = $check[3];
//                            $arr['check_type'] = $v['check_type'];
//                            $arr['check_item'] = $v['name'];
//                            $content[] = $arr;
//                        }
//
//                        $submitData['sdtx'] = json_encode(['check_date'=>$collect_data,'content'=>$content]);
//
//                        if(isset($rules[$submitData['form_id']])){
//                            $submitData[$rules[$submitData['form_id']][0]] = "2";
//                            $submitData[$rules[$submitData['form_id']][1]] = [];
//                            $submitData[$rules[$submitData['form_id']][2]] = [];
//                            $submitData[$rules[$submitData['form_id']][3]] = '';
//                        }
//
//                        $submitData['old_data_str'] = '';
//                        $submitData['childData'] = '{}';
//
//                        $this->appendField($submitData);
//
//                        $changeDatas = Laminas::$serviceManager->itemIdentificationresultchange->fetchOne([
//                            'where'=>['is_del'=>0,'patient_id'=>$submitData['patient_id'],'form_id'=>$submitData['form_id'],
//                                'checktime_id'=>$submitData['checktime_id'],'lock_state'=>1],
//                            'columns'=>['id']
//                        ]);
//                        if(!empty($changeDatas)){
//                            throw new \Exception("此化验单已锁定，不可做数据导入");
//                        }
//
//                        // 一对多的表单, 要把旧数据全部删除
//                        if ($this->currentFormType == Form::FORM_TYPE_MULTI && !isset($this->isDeleteMultiData[$this->currentPatientId])) {
//                            $this->flush();
//                        } else {
//                            if (!isset($isFetch[$this->currentItemId])) {
//                                $allContent = Laminas::$serviceManager->patientFormContent->memoryCache()->fetchAll([
//                                    'columns' => ['id', 'patient_id', 'item_id', 'checktime_id', 'form_id', 'is_del'],
//                                    'where' => [
//                                        'item_id' => $this->currentItemId,
////                                        'patient_id'=>$submitData['patient_id'],
//                                        'is_del' => 0
//                                    ]
//                                ]);
//
//                                $isFetch[$this->currentItemId] = true;
//                                $contentList = [];
//                                foreach ($allContent as &$content) {
//                                    $key = "{$content['patient_id']}{$content['item_id']}{$content['checktime_id']}{$content['form_id']}";
//                                    $contentList[$key] = $content['id'];
//                                }
//                            }
//
//                            $key = "{$this->currentPatientId}{$this->currentItemId}{$this->currentCheckTimeId}{$this->currentFormId}";
//                            $has['id'] = $contentList[$key] ?? null;
//                        }
//
//                        $submitData['id'] = $has['id'] ?? false;
//
//                        $v = new ValidatorApplication($submitData);
//                        $model = new PatientFormModel($v);
//                        $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
//
//                        if ($this->currentFormType == Form::FORM_TYPE_MULTI) {
//                            $insertId = $model->createForm($submitData);
//                        } else {
//                            if (isset($has['id'])) {
//                                $model->validator->attributes['is_import'] = 1;
//                                $model->editForm($submitData);
//                                $insertId = $has['id'];
//                            } else {
//                                unset($submitData['id']);
//                                $model->validator->attributes['is_import'] = 1;
//                                $insertId = $model->createForm($submitData);
//                            }
//                        }
//                        Laminas::$serviceManager->swTaskClient->send([
//                            'svName' => 'projectPatientwork',
//                            'methodName' => 'updatePatientworkData',
//                            'params' => [
//                                'item_id' => $submitData['item_id'],
//                                'itemsig_id' => $submitData['itemsig_id'],
//                                'patient_id' => $submitData['patient_id'],
//                                'checktime_id' => $submitData['checktime_id'],
//                                'form_id' => $submitData['form_id'],
//                                'user_id' => Laminas::$serviceManager->identity->getId(),
//                                'content_id' => $insertId
//                            ]
//                        ]);
//
//                    };
//                    $time = microtime(true);
//                    $export();
                } catch (\Throwable $e) {
                    $this->errorMessage[] = $e->getMessage();
                }
            }
            $this->currentSheetIndex++;
            $this->isDeleteMultiData = [];
        }
    }

    /**
     * @param $item_id
     * @param $page
     * @return array
     * 获取待处理数据
     */
    public function getErrorDatas($item_id,$page)
    {
//        $this->setFilePath($item_id);
        //获取中心
        $itemsignatoryDatas = Laminas::$serviceManager->itemSignatory->itemSigninfo(0, $item_id, 0);
        $itemsignatoryDatas = ArrayHelper::index($itemsignatoryDatas,'value');

        //获取检查点
        $checktimeDats = Laminas::$serviceManager->itemExport->getItemchecktime($item_id);

        //获取表单
        $formDatas = Laminas::$serviceManager->itemExport->getform($item_id,'');

        list($result,$count) = $this->hGetPage(Laminas::$serviceManager->redisExtend->getRedisInstance(6), $this->importProcessKey, $page, 10);

        $back = [];
        if(!empty($result)){
            foreach ($result as $v){
                $info = json_decode($this->getLineByNumber($this->filePath, $v),true);

                //中心
                $arr['itemsig_name'] = isset($itemsignatoryDatas[$info['data']['itemsig_id']]) ? $itemsignatoryDatas[$info['data']['itemsig_id']]['label'] : '';
                //受试者
                $arr['patient_number'] = Laminas::$serviceManager->patient->getOneFieldVal('patient_number',['id'=>$info['data']['patient_id']]);
                //检查点
                $arr['checktime_name'] = isset($checktimeDats[$info['data']['checktime_id']]) ? $checktimeDats[$info['data']['checktime_id']]['check_name'] : '';
                //表单
                $arr['form_name'] = isset($formDatas[$info['data']['form_id']]) ? $formDatas[$info['data']['form_id']]['name'] : '';
                //行号
                $arr['line'] = $v;

                $back[] = $arr;
            }
        }
        return [$back,$count];
    }

    /**
     * @return void
     * 获取待处理数据详情
     */
    public function geterrorInfo($item_id,$line)
    {
        $info = json_decode($this->getLineByNumber($this->filePath, $line),true);

        if(!isset($info['is_first'])){
            $sourceData = [];
            foreach ($info['sourceData'] as $k=>$v){

                if($info['group_id'] == 7){
                    $arr= [];
                    foreach ($v as $key=>$value){
                        $arr['infos-'.$key] = $value;
                    }
                    $sourceData[] = $arr;
                }else{
                    $arr['infos-'.$k] = $v;
                }
            }
            if($info['group_id'] != 7) $sourceData[] = $arr;

            $info['sourceData'] = $sourceData;
        }

        $error = [];
        foreach ($info['error'] as $v){
            $errorArr['error_info'] = $v;
            $error[] = $errorArr;
        }
        $info['error'] = $error;

        $header = Laminas::$serviceManager->itemExport->getHeader($info['group_id'],$item_id,$info['data']['form_id'])[1];

        $fieldDatas = [];

        foreach($header as $k => $v){
            $headerArr['label'] = $v;
            $headerArr['prop'] = 'infos-'.$k;
            $headerArr['type'] = 'Input';
            $headerArr['width']= '150';
            $fieldDatas[] = $headerArr;
        }
        return [$info,$fieldDatas];
    }

    public function delErrorInfo($item_id,$line)
    {
        $this->delCache($this->importProcessKey,$item_id,$line);
    }

    /**
     * @param $item_id
     * @param $line
     * @return void
     * @throws \RedisException
     * 数据录入
     */
    public function importDataExecute($item_id,$line)
    {
        $info = json_decode($this->getLineByNumber($this->filePath, $line),true);

        $submitData = $info['data'];

        $this->delCache($this->improtExecuteKey,$item_id,$line);
        try {
            if ($info['formType'] == 1) {
                $v = new ValidatorApplication($submitData);
                $model = new PatientFormModel($v);
                $model->validator->attributes['is_import'] = 1;
                $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                $insertId = $model->createForm($submitData);
            } else {
                $contentId = Laminas::$serviceManager->patientFormContent->getOneFieldVal('id',[
                    'item_id' => $item_id,
                    'patient_id'=>$submitData['patient_id'],
                    'checktime_id'=>$submitData['checktime_id'],
                    'form_id'=>$submitData['form_id'],
                    'is_del' => 0
                ]);
                if ($contentId) {
                    $submitData['id'] = $contentId;
                    $v = new ValidatorApplication($submitData);
                    $model = new PatientFormModel($v);
                    $model->validator->attributes['is_import'] = 1;
                    $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                    $model->editForm($submitData);
                    $insertId = $contentId;
                } else {
                    unset($submitData['id']);
                    $v = new ValidatorApplication($submitData);
                    $model = new PatientFormModel($v);
                    $model->validator->attributes['is_import'] = 1;
                    $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                    $insertId = $model->createForm($submitData);
                }
            }
            if($info['group_id'] == 7){
                Laminas::$serviceManager->swTaskClient->send([
                    'svName' => 'projectPatientwork',
                    'methodName' => 'updatePatientworkData',
                    'params' => [
                        'item_id' => $submitData['item_id'],
                        'itemsig_id' => $submitData['itemsig_id'],
                        'patient_id' => $submitData['patient_id'],
                        'checktime_id' => $submitData['checktime_id'],
                        'form_id' => $submitData['form_id'],
                        'user_id' => Laminas::$serviceManager->identity->getId(),
                        'content_id' => $insertId
                    ]
                ]);
            }
        }catch (\Throwable $e) {
            $cache['error'] = $e->getMessage();

            $cache['sourceData'] = $info['sourceData'];

            if(isset($submitData['sdtx'])){
                unset($submitData['sdtx']);
            }

            $cache['data'] = $submitData;

            $cache['is_first'] = false;

            $hashValue = StringHelper::generateHashValue();
            $fileContent = !empty(file_get_contents($this->filePath)) ? json_decode(file_get_contents($this->filePath),true) : [];

            $fileContent[$hashValue] = json_encode($cache,true);

            file_put_contents($this->filePath, json_encode($fileContent,true));

            Laminas::$serviceManager->redisExtend->getRedisInstance()->hSet($this->importProcessKey,$hashValue,$hashValue);

            unset($cache);
        }
    }

    /**
     * @param $item_id
     * @param $line
     * @return void
     * 错误数据二次提交验证
     */
    public function importDataSave($item_id, $info, $line)
    {
        $form_id = $info['data']['form_id'];

        $formType = Laminas::$serviceManager->itemForm->getOneFieldVal('type',"id = $form_id");

        $formGroupId = Laminas::$serviceManager->itemForm->getOneFieldVal('group_id',"id = $form_id");

        $sourceData = [];
        foreach ($info['sourceData'] as $k=>$v){
            $arr = [];
            foreach ($v as $key=>$value){
                $arr[] = $value;
            }
            $sourceData[] = $arr;
        }

        $header = Laminas::$serviceManager->itemExport->getHeader($formGroupId,$item_id,$form_id);

        $data = array_merge($header,$sourceData);

        $sheetCache = [];

        $time = time();

        //检查项
        list($checkname,$categoryDatas) = $this->getChecknameData($item_id);

        $form = Laminas::$serviceManager->itemForm->fetchAll(['where'=>['is_del'=>0,'item_id'=>$item_id,'group_id'=>7],'columns'=>['id','name','checklist_id']]);
        $formDatas = [];
        foreach($form as $formV){
            $formDatas[$formV['id']] = $formV['checklist_id'];
        }

        $formName = Laminas::$serviceManager->itemForm->getOneFieldVal('name',"id = $form_id");

        $checkName = $categoryDatas[$formDatas[$form_id]];

        $submitData = [];
        //  表单
        if(empty($formDatas[$form_id])){
            $formGroup = 1;
        }else{
            //化验单
            $formGroup = 2;

            $checkName = $categoryDatas[$formDatas[$form_id]];

            // 清理表单version数据缓存
            $checknamesCount = count($checkname[$checkName]);

            $handleCount = 0;

            $collectDate = '';

            $content = [];
        }

        //获取化验单时间类型
        $dateFormat = $this->dateFormat;
        foreach ($data as $row => $rowData) {
            try {
                // 第一行是变量名
                if ($row == 0) {
                    $sheetCache = $rowData;
                    try {
                        $this->checkTemplate($rowData);
                    } catch (\Throwable $e) {
                        $this->errorMessage[] = $e->getMessage();
                        break;
                    }
                    continue;
                } elseif ($row == 1) { // 第二行没用
                    continue;
                }

                if($formGroup == 1){
                    $isEmptyData = true;
                    // 当前行数据
                    foreach ($rowData as $k => $v) {
                        if ($k == 0 && !$v) {
                            return;
                        }
                        if ($sheetCache[$k] === 'INVSITE') { // 项目id
                            $submitData['item_id'] = $this->getItemId($v);
                            $submitData['form_id'] = $this->getFormId($formName);
//                            $submitData['form_id'] = $form_id;
                            //表单结构
                            if(!isset($rules[$submitData['form_id']])){
                                $rules[$submitData['form_id']] = Laminas::$serviceManager->itemForm->getPreviewConfig($form_id,true)['generateFields'];
                            }
                        } elseif ($sheetCache[$k] === 'PT') {// 中心
                            $submitData['itemsig_id'] = $this->getItemSigId($v);
                        } elseif ($sheetCache[$k] === 'SUBNAM') { // 筛选号
                            $submitData['patient_id'] = $this->getPatientId($v, $rowData[$k + 1]);
                        } elseif ($sheetCache[$k] === 'CPEVENT') { // 姓名
                            continue;
                        } elseif ($sheetCache[$k] === 'FORM_SEQ') { // 检查点z
                            $submitData['checktime_id'] = $this->getCheckTimeId($v);
                        } elseif (!in_array($sheetCache[$k], self::DEFAULT_COLUMNS) && $sheetCache[$k]) { // 如果当前变量名不在默认列里 并且这个列有变量名

                            // 生成对应的字段id, 因为有可能是关联的字段
                            $generateFieldId = $this->getGenerateFieldId($sheetCache[$k]);

                            if ($generateFieldId !== false && $this->getIsValidField($submitData, $generateFieldId)) {

                                // 表单字段值
                                $submitVal = $this->handleValue($v, $generateFieldId);

                                $submitData[$generateFieldId] = $submitVal;

                                if ($submitVal !== '') {
                                    $isEmptyData = false;
                                }

                                // 加入层级的数据, 因为导入关联字段是不分层级的。需要自己处理哪些字段是关联的
                                if (isset(self::$level[$generateFieldId])) {
                                    self::$level[$generateFieldId] = $v;
                                }
                            }
                        }
                    }

                    // 空数据不导入
                    if ($isEmptyData === true) {
                        continue;
                    }
                    $this->appendField($submitData);



                    if ($this->currentFormType == 1) {
                        $v = new ValidatorApplication($submitData);
                        $model = new PatientFormModel($v);
                        $model->validator->attributes['is_import'] = 1;
                        $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                        $result = $model->createFormImport($submitData);
                    } else {
                        $contentId = Laminas::$serviceManager->patientFormContent->getOneFieldVal('id',[
                            'item_id' => $item_id,
                            'patient_id'=>$submitData['patient_id'],
                            'checktime_id'=>$submitData['checktime_id'],
                            'form_id'=>$submitData['form_id'],
                            'is_del' => 0
                        ]);
                        if ($contentId) {
                            $submitData['id'] = $contentId;
                            $v = new ValidatorApplication($submitData);
                            $model = new PatientFormModel($v);
                            $model->validator->attributes['is_import'] = 1;
                            $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                            $result = $model->editFormImport($submitData);
                        } else {
                            unset($submitData['id']);
                            $v = new ValidatorApplication($submitData);
                            $model = new PatientFormModel($v);
                            $model->validator->attributes['is_import'] = 1;
                            $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                            $result = $model->createFormImport($submitData);
                        }
                    }
                    if(!empty($result)){
                        foreach ($result as $errorV){
                            $this->error[] = $errorV;
                        }
                    }

                    $cache['formType'] = $formType;
                    $cache['group_id'] = $formGroupId;
                    if(empty($this->error)){
                        $cache['sourceData'] = $rowData;
                        $cache['data'] = $submitData;
                    }else{
                        $cache['error'] = $this->error;

                        $cache['sourceData'] = $rowData;

                        unset($submitData['sdtx']);

                        $cache['data'] = $submitData;
                    }
                    $hashValue = StringHelper::generateHashValue();
                    $fileContent = !empty(file_get_contents($this->filePath)) ? json_decode(file_get_contents($this->filePath),true) : [];

                    $fileContent[$hashValue] = json_encode($cache,true);

                    file_put_contents($this->filePath, json_encode($fileContent,true));

                    unset($cache);
                    if(empty($this->error)){
                        Laminas::$serviceManager->redisExtend->getRedisInstance()->hSet($this->improtExecuteKey,$hashValue,$hashValue);
                    }else{
                        Laminas::$serviceManager->redisExtend->getRedisInstance()->hSet($this->importProcessKey,$hashValue,$hashValue);
                    }

                    //删除redis缓存 以及文件缓存
                    $this->delCache($this->importProcessKey,$item_id,$line);
                }else{
                    //首次获取基础数据
                    if(empty($submitData)){

                        // 当前行数据
                        foreach ($rowData as $k => $v) {
                            if ($k == 0 && !$v) {
                                return;
                            }

                            if ($sheetCache[$k] === 'INVSITE') { // 项目id
                                $submitData['item_id'] = $this->getItemId($v);
                                $submitData['form_id'] = $form_id;
                                //表单结构
                                if(!isset($rules[$submitData['form_id']])){
                                    $rules[$submitData['form_id']] = Laminas::$serviceManager->itemForm->getPreviewConfig($form_id,true)['generateFields'];
                                }
                            } elseif ($sheetCache[$k] === 'PT') {// 中心
                                $submitData['itemsig_id'] = $this->getItemSigId($v);
                            } elseif ($sheetCache[$k] === 'SUBNAM') { // 筛选号
                                $submitData['patient_id'] = $this->getPatientId($v, $rowData[$k + 1]);
                            } elseif ($sheetCache[$k] === 'CPEVENT') { // 姓名
                                continue;
                            } elseif ($sheetCache[$k] === 'FORM_SEQ') { // 检查点z
                                $submitData['checktime_id'] = $this->getCheckTimeId($v);
                            } elseif ($k == 6) { // 如果当前变量名不在默认列里 并且这个列有变量名
                                // 1. 如果是纯数字且大于 25569（1970-01-01 的 Excel 序列号），说明是 Excel 日期
                                if (is_numeric($v) && $v > 25569 && $v < 60000) { // 60000 ~ 2136 年
                                    $unixTimestamp = ($v - 25569) * 86400; // 转 Unix 时间戳
                                    if($unixTimestamp > $time){
                                        $error[] = '化验单采集日期不能大于当前时间';
                                    }
                                    $collectDate =  gmdate($dateFormat, $unixTimestamp);
                                }elseif (is_string($v) && strtotime($v) !== false) {
                                    if(strtotime($v) > $time){
                                        $error[] = '化验单采集日期不能大于当前时间';
                                    }
                                    $collectDate =  date($dateFormat, strtotime($v));
                                }
                                if(empty($collectDate)){
                                    $error[] = '采集日期不能为空';
                                }
                            }
                        }
                    }

                    //截取  采集日期	指标名称	测量结果	计数单位	最小值
                    $check = array_slice($rowData, 7, 5);
                    $arr['id'] = $checkname[$checkName][$handleCount]['id'];
                    $arr['check_item'] = $check[0];
                    $arr['result'] = $check[1];
                    $arr['unit'] = $check[2];
                    $arr['min_val'] = $check[3];
                    $arr['max_val'] = $check[4];
                    $arr['check_type'] = $checkname[$checkName][$handleCount]['check_type'];

                    $content[] = $arr;

                    unset($arr);

                    ++$handleCount;

                    if($handleCount == $checknamesCount){

                        $submitData['sdtx'] = json_encode(['check_date'=>$collectDate,'content'=>$content]);

                        if(isset($rules[$submitData['form_id']])){
                            $submitData[$rules[$submitData['form_id']][0]] = "2";
                            $submitData[$rules[$submitData['form_id']][1]] = [];
                            $submitData[$rules[$submitData['form_id']][2]] = [];
                            $submitData[$rules[$submitData['form_id']][3]] = '';
                        }

                        $submitData['old_data_str'] = '';
                        $submitData['childData'] = '{}';

                        $this->appendField($submitData);

                        if ($this->currentFormType == 1) {
                            $v = new ValidatorApplication($submitData);
                            $model = new PatientFormModel($v);
                            $model->validator->attributes['is_import'] = 1;
                            $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                            $result = $model->createFormImport($submitData);
                        } else {
                            $contentId = Laminas::$serviceManager->patientFormContent->getOneFieldVal('id',[
                                'item_id' => $item_id,
                                'patient_id'=>$submitData['patient_id'],
                                'checktime_id'=>$submitData['checktime_id'],
                                'form_id'=>$submitData['form_id'],
                                'is_del' => 0
                            ]);
                            if ($contentId) {
                                $submitData['id'] = $contentId;
                                $v = new ValidatorApplication($submitData);
                                $model = new PatientFormModel($v);
                                $model->validator->attributes['is_import'] = 1;
                                $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                                $result = $model->editFormImport($submitData);
                            } else {
                                unset($submitData['id']);
                                $v = new ValidatorApplication($submitData);
                                $model = new PatientFormModel($v);
                                $model->validator->attributes['is_import'] = 1;
                                $model->setScenario($model::SCENARIO_EXCEL_IMPORT);
                                $result = $model->createFormImport($submitData);
                            }
                        }
                        if(!empty($result)){
                            foreach ($result as $errorV){
                                $this->error[] = $errorV;
                            }
                        }

                        $changeDatas = Laminas::$serviceManager->itemIdentificationresultchange->fetchOne([
                            'where'=>['is_del'=>0,'patient_id'=>$submitData['patient_id'],'form_id'=>$submitData['form_id'],
                                'checktime_id'=>$submitData['checktime_id'],'lock_state'=>1],
                            'columns'=>['id']
                        ]);

                        //化验单已锁定，进行提示
                        if(!empty($changeDatas)){
                            $this->error[] = '此化验单已锁定，不可做数据导入';
                        }

                        $cache['formType'] = $formType;
                        $cache['group_id'] = $formGroupId;
                        if(empty($error)){
                            $cache['sourceData'] = $info['sourceData'];
                            $cache['data'] = $submitData;
                        }else{
                            $cache['error'] = $error;

                            $cache['sourceData'] = $info['sourceData'];

                            unset($submitData['sdtx']);

                            $cache['data'] = $submitData;
                        }

                        $hashValue = StringHelper::generateHashValue();
                        $fileContent = !empty(file_get_contents($this->filePath)) ? json_decode(file_get_contents($this->filePath),true) : [];

                        $fileContent[$hashValue] = json_encode($cache,true);

                        file_put_contents($this->filePath, json_encode($fileContent,true));

//                    $lineNumber = $this->appendLineReturnLineNumber(APP_PATH.'/data/import.txt',json_encode($cache));

                        if(empty($this->error)){
                            Laminas::$serviceManager->redisExtend->getRedisInstance()->hSet($this->improtExecuteKey,$hashValue,$hashValue);   //一小时
                        }else{
                            Laminas::$serviceManager->redisExtend->getRedisInstance()->hSet($this->importProcessKey,$hashValue,$hashValue);   //一小时
                        }
                        unset($cache);

                        unset($submitData);

                        //删除redis缓存 以及文件缓存
                        $this->delCache($this->importProcessKey,$item_id,$line);
                    }
                }

            } catch (\Throwable $e) {
                $this->errorMessage[] = $e->getMessage() . "。表格: {$this->currentSheetIndexTitle}。行数: {$this->currentRowLine}。";
            }
        }
    }


    public function delCache(string $key,int $item_id,string $line) :bool
    {
        //删除redis、文件数据
        Laminas::$serviceManager->redisExtend->getRedisInstance(6)->hDel($key, $line);

        $this->deleteLineFromFile($this->filePath,$line);

        return true;
    }

    /**
     * @param \Redis $redis
     * @param string $key
     * @param int $page
     * @param int $pageSize
     * @return array
     * @throws \RedisException
     * redis分页
     */
    public function hGetPage(\Redis $redis, string $key, int $page, int $pageSize): array
    {
        // 获取所有 field
        $fields = $redis->hKeys($key);
        $count = count($fields);

        // 计算分页位置
        $offset = ($page - 1) * $pageSize;
        $pageFields = array_slice($fields, $offset, $pageSize);

        if (empty($pageFields)) {
            return [];
        }

        // 批量获取对应值
        $values = $redis->hMGet($key, $pageFields);

        // 返回 field => value
        return [array_combine($pageFields, $values),$count];
    }


    /**
     * @param string $file
     * @param int $lineNumber
     * @return string|null
     * 通过行号读取数据
     */
    public function getLineByNumber(string $file, string $lineNumber): ?string
    {
        if (!file_exists($file)) {
            return null;
        }

        $fileContent = json_decode(file_get_contents($this->filePath),true);

        if(empty($fileContent)){
            return null;
        }

        return $fileContent[$lineNumber];
    }


    /**
     * @param string $file
     * @param int $lineNo
     * @return bool
     * 通过行号删除数据
     */
    public function deleteLineFromFile(string $file, string $lineNo): bool
    {
        if (!file_exists($file)) {
            return false;
        }

        $fileContent = file_get_contents($this->filePath);

        if(empty($fileContent)){
            return false;
        }

        $data = json_decode($fileContent,true);

        unset($data[$lineNo]);

        file_put_contents($file, json_encode($data,true));

        return true;
    }

    private function flush($is_check = 0)
    {
        // 清理表单数据
        Laminas::$serviceManager->patientFormContent->update(['is_del' => 1], [
            'patient_id' => $this->currentPatientId,
            'form_id' => $this->currentFormId
        ]);
        Laminas::$serviceManager->patientForm->update(['is_del' => 1], [
            'patient_id' => $this->currentPatientId,
            'form_id' => $this->currentFormId,
            'checktime_id' => $this->currentFormGroupId == FormGroup::THROUGH_PROCESS ? 0 : $this->currentCheckTimeId
        ]);
        if($is_check == 1){
            Laminas::$serviceManager->itemIdentificationresultchange->update(['is_del' => 1], [
                'patient_id' => $this->currentPatientId,
                'form_id' => $this->currentFormId,
                'checktime_id' => $this->currentFormGroupId == FormGroup::THROUGH_PROCESS ? 0 : $this->currentCheckTimeId
            ]);
            Laminas::$serviceManager->projectPatientwork->update(['is_del'=>1],[
                'patient_id' => $this->currentPatientId,
                'form_ids' => $this->currentFormId,
                'checktime_id' => $this->currentFormGroupId == FormGroup::THROUGH_PROCESS ? 0 : $this->currentCheckTimeId
            ]);
        }
        $this->isDeleteMultiData[$this->currentPatientId] = 1;
    }

    private function checkTemplate($rowData)
    {
        if (!in_array('INVSITE', $rowData)) {
            throw new \Exception("导入模板有误。未发现列: 项目ID(INVSITE)`");
        }
        if (!in_array('PT', $rowData)) {
            throw new \Exception("导入模板有误。未发现列: 中心编号(PT)`");
        }
        if (!in_array('SUBNAM', $rowData) && !in_array('CPEVENT', $rowData)) {
            throw new \Exception("导入模板有误。未发现列: 受试者筛选号/编号/姓名`");
        }
        if (!in_array('FORM_SEQ', $rowData)) {
            throw new \Exception("导入模板有误。未发现列: 访视名称(FORM_SEQ)`");
        }
    }

    private function getItemId(string $itemNumber)
    {
        $tableName = Laminas::$serviceManager->itemInfo->getTableName();
        if (!isset(self::$dataCache[$tableName][$itemNumber])) {
            self::$dataCache[$tableName][$itemNumber] = Laminas::$serviceManager->itemInfo->fetchAll([
                'columns' => ['id', 'fid'],
                'where' => ['number' => $itemNumber, 'is_mainitem' => 0,'is_del'=>0]
            ]);

            if (count(self::$dataCache[$tableName][$itemNumber]) > 1) {
                $this->error[] = "项目ID `{$itemNumber}` 重复";
//                throw new \Exception("项目ID `{$itemNumber}` 重复");
            }
        }

        if (!self::$dataCache[$tableName][$itemNumber]) {
            $this->error[] = "项目 `{$itemNumber}]` 不存在";
//            throw new \Exception("项目 `{$itemNumber}]` 不存在");
        }

        $this->currentItemId = current(self::$dataCache[$tableName][$itemNumber])['id'];
        $this->currentItemFid = current(self::$dataCache[$tableName][$itemNumber])['fid'];
        return $this->currentItemId;
    }

    private function getItemSigId(string $signNumber)
    {
        $db = Laminas::$serviceManager->itemSignatory;
        $tableName = $db->getTableName();
        if (!isset(self::$dataCache[$tableName][$signNumber])) {
            self::$dataCache[$tableName][$signNumber] = $db->fetchOne([
                'where' => ['number' => $signNumber, 'item_id' => $this->currentItemFid]
            ])['id'];
        }

        if (!self::$dataCache[$tableName][$signNumber]) {
//            throw new \Exception("中心编号 `{$signNumber}` 不存在");
            $this->error[] = "中心编号 `{$signNumber}` 不存在";
        }

        $this->currentSignId = self::$dataCache[$tableName][$signNumber];

        if($this->itemsig_id != $this->currentSignId){
            $this->error[] = "当前受试者非本中心人员,请确认!";
        }

        return $this->currentSignId;
    }

    private function getPatientId($patientNumber, $patientName)
    {
        $db = Laminas::$serviceManager->patient;

        $tableName = $db->getTableName();
        if (!isset(self::$dataCache[$tableName][$patientNumber . $patientName])) {
            $where = (new Where())->equalTo('item_id', $this->currentItemId)->equalTo('is_del', 0);
            if(!empty($this->itemsig_id)) $where->equalTo('itemsig_id',$this->itemsig_id);
            if ($patientNumber) {
                $where->equalTo('patient_number', $patientNumber);
            }

            if ($patientName) {
                $where->equalTo(new Expression("AES_DECRYPT(UNHEX(`patient_name`), 'ykeEdc')"), $patientName);
            }

            self::$dataCache[$tableName][$patientNumber . $patientName] = $db->fetchOne([
                'where' => $where
            ]);
        }


        if (!isset(self::$dataCache[$tableName][$patientNumber . $patientName]['id'])) {
//            throw new \Exception("受试者`{$patientNumber}[{$patientName}]`不存在");
            $this->error[] = "受试者`{$patientNumber}[{$patientName}]`不存在";
        }
        list($this->currentPatientId, $this->currentPatientRandomId) = [self::$dataCache[$tableName][$patientNumber . $patientName]['id'] ?: 0, self::$dataCache[$tableName][$patientNumber . $patientName]['random_id'] ?: 0];
        return $this->currentPatientId;
    }

    private function getCheckTimeId(string $checkTimeName)
    {
        if ($this->isAeForm === true) {
            return 99;
        }

        if (!$checkTimeName) {
//            throw new \Exception('检查点数据不能为空');
            $this->error[] = '检查点数据不能为空';
        }

        $db = Laminas::$serviceManager->itemChecktime;
        $tableName = $db->getTableName();
        $checkTimeNameKey = $this->currentPatientRandomId . $checkTimeName;
        if (!isset(self::$dataCache[$tableName][$checkTimeNameKey])) {
            $condition = [
                'columns' => ['id', 'stage_id'],
                'where' => [
                    'check_name' => $checkTimeName,
                    'item_id' => $this->currentItemId,
                    'is_del' => 0
                ]
            ];

            if ($this->currentPatientRandomId && $this->getIsFlowCat($checkTimeName)) {
                $condition['where']['random_id'] = $this->currentPatientRandomId;
            }

            self::$dataCache[$tableName][$checkTimeName] = ($db->memoryCache()->fetchOne($condition));
        }

        if (!isset(self::$dataCache[$tableName][$checkTimeName]['id'])) {
//            throw new \Exception('访视名称有误');
            $this->error[] = '访视名称有误';
        }

        list($this->currentCheckTimeId, $this->currentStageId) = [self::$dataCache[$tableName][$checkTimeName]['id'], self::$dataCache[$tableName][$checkTimeName]['stage_id']];
        return $this->currentCheckTimeId;
    }


    private function getIsFlowCat(string $checkTimeName): bool
    {
        if (!isset($this->flowCat[$checkTimeName])) {
            $this->flowCat = Laminas::$serviceManager->itemChecktime->fetchOne([
                    'where' => ['check_name' => $checkTimeName, 'item_id' => $this->currentItemId, 'flowcat_id' => 0]
                ]) ?? [];
        }
        return !isset($this->flowCat[$checkTimeName]['flowcat_id']) && $this->flowCat[$checkTimeName]['flowcat_id'] != 0;
    }

    private function getFormId(string $formName)
    {
        $db = Laminas::$serviceManager->itemForm;
        $tableName = $db->getTableName();
        if (!isset(self::$dataCache[$tableName][$formName])) {
            self::$dataCache[$tableName][$formName] = $db->fetchOne([
                'where' => ['name' => $formName, 'item_id' => $this->currentItemId, 'is_del' => 0]
            ]);
        }

        if (self::$dataCache[$tableName][$formName] === null) {
//            throw new \Exception("`{$formName}` 这个表单不存在!!");
            $this->error[] = "`{$formName}` 这个表单不存在!!";
        }

        $this->currentFormId = self::$dataCache[$tableName][$formName]['id'];
        $this->currentFormType = self::$dataCache[$tableName][$formName]['type'];
        $this->currentFormGroupId = self::$dataCache[$tableName][$formName]['group_id'];
        if ($this->currentFormGroupId == FormGroup::AE) {
            $this->isAeForm = true;
        }
        return $this->currentFormId;
    }

    private function getPatientCheckTimeId()
    {
        if($this->currentPatientId == 0) return 0;
        $q = Laminas::$serviceManager->itemPatientchecktime->memoryCache()->fetchOne([
            'columns' => ['id'],
            'where' => [
                'item_id' => $this->currentItemId,
                'patient_id' => $this->currentPatientId,
                'checktime_id' => $this->currentCheckTimeId
            ]
        ]);

        if (!isset($q['id'])) {
//            throw new \Exception('当前受试者有这个检查点吗????');
            $this->error[] = '检查点不存在';
        }

        return $q['id'];
    }

    private function getPreviewConfig()
    {
        if (!$this->previewConfig) {
            $this->previewConfig = Laminas::$serviceManager->itemForm->setRequestParams([
                'item_id' => $this->currentItemId,
                'itemsig_id' => $this->currentSignId,
                'patient_id' => $this->currentPatientId
            ])->getPreviewConfig($this->currentFormId, true);
        }

        return $this->previewConfig;
    }

    /**
     * 获取首层展示数据, 也就是表单什么都不写展示的数据
     * @return array
     */
    private function getPreviewConfigFirstLevel(): array
    {
        $config = $this->getPreviewConfig();
        $firstLevel = $config['config']['form'];

        if (!$this->previewConfigFirstLevel) {
            $this->previewConfigFirstLevel = ArrayHelper::getColumn($firstLevel, 'var_name');
        }

        return $this->previewConfigFirstLevel;
    }

    private function getVersionData(int $formId = 0)
    {
        if (!$this->versionData[$formId]) {
            $this->versionData[$formId] = Laminas::$serviceManager->itemFormVersion->getField(['form_id' => $formId], true);
        }
        return $this->versionData[$formId];
    }

    /**
     * @throws \Exception
     */
    private function getGenerateFieldId(string $varName)
    {
        $config = $this->getPreviewConfig();
        $firstLevel = $this->getPreviewConfigFirstLevel();
        $fieldId = false;

        if (in_array($varName, $firstLevel)) {
            self::$level = [];
        }

        $varNameFieldId = $this->getFieldId($varName);
        foreach ($config['generateFields'] as $field) {
            // 首层
            if (count(self::$level) == 0) {
                if ($field == $varNameFieldId) {
                    $fieldId = $field;
                }
            } else {
                $containsFieldId = self::$level;
                end($containsFieldId);
                $key = $varNameFieldId . '-' . key($containsFieldId) . '-' . current($containsFieldId);

                if (stripos($field, $key) !== false) {
                    $fieldId = $field;
                }
            }
        }

        if ($fieldId && $this->getHasChild($config['generateFields'], $fieldId) === true) {
            // 说明是首层的变量, 后面的变量一定是关联出来的
            self::$level[$fieldId] = '';
        }

        return $fieldId;
    }

    private function getHasChild(&$array, $parentFieldId): bool
    {
        foreach ($array as $value) {
            if ($value !== $parentFieldId && stripos($value, $parentFieldId) !== false) {
                return true;
            }
        }

        return false;
    }

    /**
     * 通过变量名来获取字段ID
     * @throws \Exception
     */
    private function getFieldId(string $varName)
    {
        if (!isset($this->field[$this->currentItemId][$this->currentFormId][$varName])) {
            $this->field[$this->currentItemId][$this->currentFormId][$varName] = Laminas::$serviceManager->itemFormField->fetchOne([
                    'where' => ['item_id' => $this->currentItemId, 'form_id' => $this->currentFormId, 'var_name' => $varName, 'is_del' => 0]
                ]);
        }

        if (!isset($this->field[$this->currentItemId][$this->currentFormId][$varName]['id'])) {
//            throw new \Exception("变量名为 `$varName` 的变量不存在。请确认。");
            $error[] = '"变量名为 `$varName` 的变量不存在。请确认。"';
        }

        return $this->field[$this->currentItemId][$this->currentFormId][$varName]['id'];
    }

    private function resetExecuteInfo()
    {
        $this->currentPatientId = 0;
        $this->currentItemId = 0;
        $this->currentSignId = 0;
        $this->currentCheckTimeId = 0;
        $this->currentFormId = 0;
        $this->appendFieldScore = null;
        $this->previewConfig = [];
        $this->previewConfigFirstLevel = [];
        $this->isAeForm = false;
    }

    /**
     * 验证是否是合法的字段。因为表格所有的字段都导出来了。但是有的不一定需要。可能会导致表单颜色展示不对。
     * @param $submitData
     * @param $currentField
     * @return bool
     */
    private function getIsValidField($submitData, $currentField): bool
    {
        $versionData = $this->getVersionData($this->currentFormId);
        if (stripos($currentField, '-') !== false) {
            $formatVal = $this->formatText($currentField);
            $level = count($formatVal);
            foreach ($formatVal as $formatValItem) {
                // 判断提交过来的数据
                foreach ($submitData as $k => $v) {
                    $field = DataHelper::getFieldId($k);
                    // 一对多
                    if (isset($versionData[$field]) && $versionData[$field]['type'] == FormField::FORM_FIELD_TYPE_CHECKBOX) {
                        if (DataHelper::getFieldId($k) == $formatValItem[0] && in_array($formatValItem[1], explode(',', $v))) {
                            $level--;
                        }
                    } elseif (DataHelper::getFieldId($k) == $formatValItem[0] && $v == $formatValItem[1]) {
                        $level--;
                    }
                }
            }

            if ($level !== 0) {
                return false;
            }
        }

        return true;
    }

    private function formatText($text): array
    {
        $data = explode('-', $text);
        array_shift($data);
        $length = count($data);
        $result = [];
        for ($i = 0; $i < $length / 2; $i++) {
            $first = array_shift($data);
            $last = array_pop($data);
            $result[] = [$first, $last];
        }
        return $result;
    }


    private function getFieldInfo(int $fieldId)
    {
        if (!isset($this->fieldInfo[$fieldId])) {
            if (isset($this->getVersionData($this->currentFormId)[$fieldId])) {
                $this->fieldInfo[$fieldId] = $this->getVersionData($this->currentFormId)[$fieldId];
            } else {
                $this->fieldInfo[$fieldId] = Laminas::$serviceManager->itemFormField->fetchOne([
                    'where' => ['id' => $fieldId]
                ]);
            }
        }

        return $this->fieldInfo[$fieldId];
    }
    private function handleValue($val, $fieldId)
    {
        if ($val === '') {
            return $val;
        }
        $v = $this->getVersionData($this->currentFormId);

        $field = DataHelper::getFieldId($fieldId);
        $fieldInfo = $this->getFieldInfo($field);
        if (in_array($fieldInfo['type'], [FormField::FORM_FIELD_TYPE_CHECKBOX, FormField::FORM_FIELD_TYPE_RADIO])) {
            // 一对多
            if (stripos($val, ',') !== false) {
                $val = explode(',', $val);
                $c = ArrayHelper::index($v[$field]['children'], 'value');
                $res = $scoreTmp = [];
                foreach ($val as $item) {
                    if (!isset($c[$item])) {
//                        throw new \Exception("选项值 `{$item}` 有误~");
                        $error[] = "选项值 `{$item}` 有误~";
                    }
                    // 处理分值
                    if ($c[$item]['is_score'] == 1) {
                        $score = intval($c[$item]['score']);
                        $this->appendFieldScore += $score;
                        $scoreTmp[strval($fieldId)][] = $score;
                    }

                    $res[] = $c[$item]['value'];
                }

                foreach ($scoreTmp as $tmpItem) {
                    $this->appendFieldScoreStr[] = ['prop' => strval($fieldId), 'score' => array_sum($tmpItem), 'is_score' => true];
                }

                $val = implode(',', $res);
            } else {
                $c = ArrayHelper::index($v[$field]['children'], 'value');
                if (!isset($c[$val])) {
//                    throw new \Exception("{$v[$field]['name']}选项值 `{$val}` 有误!");
                    $error[] = "{$v[$field]['name']}选项值 `{$val}` 有误!";
                }
                // 处理分值
                if ($c[$val]['is_score'] == 1) {
                    $score = intval($c[$val]['score']);
                    $this->appendFieldScore += $score;
                    $this->appendFieldScoreStr[] = ['prop' => strval($fieldId), 'score' => $score, 'is_score' => true];
                }

                return $c[$val]['value'];
            }
        } elseif (in_array($fieldInfo['type'], [FormField::FORM_FIELD_TYPE_DROPDOWN])) {
            if (in_array($fieldInfo['var_name'], ['RANDOM_GROUP_SYSTEM', 'RANGCA'])) { // 随机分组 自动取号
                if ($this->currentItemId && $this->currentSignId && $this->currentPatientId) {
                    $getRandomNumber = Laminas::$serviceManager->itemRandomdetails->getRandomdetailsNumberPop(
                        $this->currentItemId,
                        $this->currentSignId,
                        $this->currentPatientId
                    );

                    if (!$getRandomNumber) {
//                        throw new \Exception('随机号导入失败');
                        $error[] = '随机号导入失败';
                    }

                    $randomId = current($getRandomNumber)['id'];
                    $this->appendFieldRandom["{$randomId}-{$fieldId}-{$randomId}"] = current($getRandomNumber)['rand_number']['id'];
                }
            }
        }
        elseif(in_array($fieldInfo['type'], [FormField::FORM_FIELD_TYPE_DATE,FormField::FORM_FIELD_TYPE_DATETIME])){
            if($fieldInfo['type'] == 3){
                $type = 'Y-m-d';
            }else{
                $type = 'Y-m-d H:i';
            }
            if (is_numeric($val) && $val > 25569 && $val < 60000) { // 60000 ~ 2136 年
                $unixTimestamp = ($val - 25569) * 86400; // 转 Unix 时间戳
                $val =  gmdate($type, $unixTimestamp);
            }elseif (is_string($val) && strtotime($val) !== false) {
                $val =  date($type, strtotime($val));
            }
        }

        return $val;
    }

    private function appendField(array &$submitData = [])
    {
        if ($this->appendFieldScore !== null) {
            $submitData['score'] = $this->appendFieldScore;
        }

        if ($this->appendFieldScoreStr !== null) {
            $submitData['scoreStr'] = $this->appendFieldScoreStr;
        }

        if ($this->appendFieldRandom !== null) {
            $submitData[key($this->appendFieldRandom)] = current($this->appendFieldRandom);
        }

        if ($this->isAeForm === true) {
            $submitData['csae_id'] = 0;
            $submitData['ae_type'] = 0;
            $submitData['new_ae_list'] = 0;
            unset($submitData['checktime_id']);
        } else {
            $submitData['stage_id'] = $this->currentStageId;
            $submitData['is_copy'] = 0;
            $submitData['patientchecktime_id'] = $this->getPatientCheckTimeId();
        }
    }
}