<?php

namespace Application\Service\DB\Project;

use Application\Common\StatusCode;
use Application\Service\DB\Db;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\LogicHelper;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\Between;
use Laminas\Db\Sql\Predicate\NotIn;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Stdlib\ArrayUtils;
use Laminas\Validator\Exception\InvalidArgumentException;
use Application\Service\Extension\Xml\XmlBuilder;
use Application\Service\Extension\Xml\LaboratoryXmlGenerator;
use Application\Common\Ocr;
use Application\Service\Extension\Uploader\adapter\Oss;
use Application\Service\Extension\Uploader\ImageUploader;
use Laminas\Db\Sql\Expression;
use PHP_CodeSniffer\Tokenizers\PHP;
use Application\Service\DB\Dictionary\ItemForm;
use Application\Service\DB\Dictionary\ItemFormField;
use Application\Service\DB\Item\PatientForm;
use Application\Service\DB\Project\Csae;
use Application\Common\Exportenum;



class Identificationresultchange extends \Application\Service\DB\AbstractDb {
    private $ossPath = 'http://yikeen.oss-cn-beijing.aliyuncs.com';
    protected $redisObj;
    public function __construct($dbAdapter, ContainerInterface $container) {
        $this->redisObj = Laminas::$serviceManager->redisExtend->setDatabase(6)->getRedisInstance();
        $this->tableName = 'yikeen_item_identificationresultchange';
        parent::__construct($dbAdapter, $container);
    }

    //按时间解锁
    public function unLockWorkAndChangeCs($useData=[]){
        //item_id:1085
        //form_id:4628,4630,4631,4637,4639
        //start_up_annex_date:2022-09-23
        //start_up_annex_date:2022-09-23
        if(empty($useData)){
            echo '参数为空';die;
        }
        $item_id = $useData['item_id'];
        $form_id = $useData['form_id'] ? $useData['form_id']:0;
        $category_id = $useData['category_id'] ? $useData['category_id']:0;
        $start_up_annex_date = $useData['start_up_annex_date'] ? strtotime($useData['start_up_annex_date']): 0;;
        $end_up_annex_date = $useData['end_up_annex_date'] ? strtotime($useData['end_up_annex_date']): 0;;
        $whereFormId = '';
        $whereFormNe = [];
        if (!empty($form_id)){
            $whereFormId = $form_id;
            $whereFormNe['form_id'] = explode(',', (string)$whereFormId);
        }
        if (!empty($form_id)){
            $whereFormNe['category_id']= explode(',', (string)$category_id);
        }
        if (!empty($start_up_annex_date) && !empty($end_up_annex_date)){
            $whereFormNe[] = new Between('up_annex_date', $start_up_annex_date, $end_up_annex_date);
        }else{
            if (!empty($start_up_annex_date)){
                $whereFormNe[] = new Operator('up_annnex_date', Operator::OP_GTE, $start_up_annex_date);
            }
            if (!empty($end_up_annex_date)){
                $whereFormNe[] = new Operator('up_annex_date', Operator::OP_LTE, $end_up_annex_date);
            }
        }

        $itemFormNameArr = $this->LocalService()->itemForm->fetchCol('name',[
            'is_del' => 0,
            'item_id' => $item_id,
            'id' => explode(',', (string)$whereFormId),
        ]);
        $whereItemPatientworkannex['where'] = ArrayUtils::merge([
            'is_del' => 0,
            'lock_state' => 1,
            'item_id' => $item_id,
            new Operator('annex_type', Operator::OP_NE, 2),
        ], $whereFormNe);

        $whereItemPatientworkannex['columns'] = ['id','checktime_id','patient_form_id','form_id','item_id','itemsig_id','patient_id','researchstage_id','category_id','update_user_id','update_time','is_unlock'];
        $whereItemPatientworkannex['order'] = ['id desc'];
        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);
        $notLockData = [];
        if (!empty($itemPatientworkannexData)){
            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>&$itemPatientworkannexDataValue){


                $itemPatientworkannexDataValue['form_name'] =isset($itemFormNameArr[$itemPatientworkannexDataValue['form_id']])?$itemFormNameArr[$itemPatientworkannexDataValue['form_id']]:'';
                $stage_name = $this->LocalService()->itemResearchstage->getOneFieldVal('stage_name','is_del=0 and id ='.$itemPatientworkannexDataValue['researchstage_id']);//
                $check_name = $this->LocalService()->itemChecktime->getOneFieldVal('check_name','is_del=0 and id ='.$itemPatientworkannexDataValue['checktime_id']);//
                $itemPatientworkannexDataValue['patient_name'] = $this->LocalService()->patient->getOneFieldVal('patient_name','is_del=0 and id ='.$itemPatientworkannexDataValue['patient_id']);//
                $itemPatientworkannexDataValue['check_stage_name'] = '['.$check_name.']'.$stage_name;
                $itemsig_nameS = $this->LocalService()->itemSignatory->itemSigninfo($itemPatientworkannexDataValue['itemsig_id'], $item_id,0);
                $itemPatientworkannexDataValue['itemsig_name'] = isset($itemsig_nameS[0]['label'])?$itemsig_nameS[0]['label']:'';



                $whereItemIdentificationresultchange['where'] = [
                    'is_del' => 0,
                    'lock_state' => 1,
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                    'item_id' => $item_id,
                ];
                $whereItemIdentificationresultchange['columns'] = ['id','item_checkname_id','item_name','category_id','report_type','is_normal_type','result','update_time','update_user_id'];
                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
                if (!empty($itemIdentificationresultchangeData)){
                    $itemPatientworkannexDataValue['change'] = $itemIdentificationresultchangeData;
                    $whereItemCsae['where'] = [
                        'is_del' => 0,
                        'ae_type' => [5, 6],
                        'patient_change_id' => array_column($itemIdentificationresultchangeData,'id'),
                        'item_id' => $item_id,
                    ];
                    $itemCsaeData = $this->LocalService()->itemCsae->fetchCol('patient_change_id',$whereItemCsae['where']);
                    if (!empty($itemCsaeData)){
                        $itemPatientworkannexDataValue['change'] = $itemCsaeData;
                        $notLockData[] = $itemPatientworkannexDataValue;
                        continue;
                    }
                    foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDatum) {
                        $upChangeArr = [
                            'lock_state' =>0,
                            'is_sure' =>0,
                            'update_time' =>$itemIdentificationresultchangeDatum['update_time'],
                            'id' =>$itemIdentificationresultchangeDatum['id'],
                            'update_user_id' =>$itemIdentificationresultchangeDatum['update_user_id'],

                        ];
                        $resultChange = $this->LocalService()->itemIdentificationresultchange->save($upChangeArr);
                        $resultCsae = $this->LocalService()->itemCsae->update(['is_del'=>1],[
                            'is_del' => 0,
                            'patient_change_id' => $itemIdentificationresultchangeDatum['id'],
                            'item_id' => $item_id
                        ]);
                    }

                }
                $upWorkArr = [
                    'lock_state' =>0,
                    'update_time' =>$itemPatientworkannexDataValue['update_time'],
                    'id' =>$itemPatientworkannexDataValue['id'],
                    'update_user_id' =>$itemPatientworkannexDataValue['update_user_id'],
                    'is_unlock' =>0,

                ];
                if (!empty($itemPatientworkannexDataValue['is_unlock'])){
                    $resultPatientFormUnlock = $this->LocalService()->patientFormUnlock->update(['is_del'=>1],[
                        'is_del' => 0,
                        'id' => $itemPatientworkannexDataValue['is_unlock']
                    ]);

                }
                $resultWork = $this->LocalService()->itemPatientworkannex->save($upWorkArr);
            }
        }
        echo '成功'.PHP_EOL;
        echo '有cs不能处理的数据<pre>';print_r($notLockData).PHP_EOL;
        echo '要处理的数据<pre>';print_r($itemPatientworkannexData).PHP_EOL;
    }

    //删除普通指标=新
    public function delChangeCS($item = []){
        if(empty($item) || empty($item['oldCategory_id']) || empty($item['item_id'])){
            echo '参数为空';die;
        }
        $wherePatientArr['where'] = [
            'is_del' => 0,
            'item_id' => $item['item_id'],
        ];
        $wherePatientArr['columns'] = ['id','patient_name','patient_number','item_id'];
        $patientData = $this->LocalService()->patient->fetchAll($wherePatientArr);//$item_id
        $patientNameArr = [];
        if(!empty($patientData)){
            foreach ($patientData as $patientDataKey=>$patientDataValue) {
                $patientNameArr[$patientDataValue['id']] = $patientDataValue;
            }
        }
        $formIdArr = [];
        $updateChangeArr = [];
        $whereItemPatientworkannex['where'] = [
            'is_del' => 0,
            'lock_state' => 1,
            new Operator('annex_type', Operator::OP_NE, 2),
            'category_id' => $item['oldCategory_id'],
            'item_id' => $item['item_id'],
        ];
        !empty($item['form_id']) && $whereItemPatientworkannex['where']['form_id'] = $item['form_id'];
        !empty($item['itemsig_id']) && $whereItemPatientworkannex['where']['itemsig_id'] = $item['itemsig_id'];
        !empty($item['work_id']) && $whereItemPatientworkannex['where']['id'] = explode(',', (string)$item['work_id']);
        $whereItemPatientworkannex['group'] = ['checktime_id','patient_form_id','form_id'];
        $whereItemPatientworkannex['columns'] = ['id','checktime_id','patient_form_id','form_id','itemsig_id','patient_id','category_id','item_id','researchstage_id','update_user_id','update_time'];
        $whereItemPatientworkannex['order'] = ['id desc'];
        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);
        $itemFormNameArr = $this->LocalService()->itemForm->fetchCol('name',[
            'is_del' => 0,
            'checklist_id' => $item['oldCategory_id'],
            'item_id' => explode(',', (string) $item['item_id'])
        ]);
        !empty($itemFormNameArr) && $formIdArr = array_keys($itemFormNameArr);
        if (!empty($itemPatientworkannexData)){
            echo "附件数据总：".count($itemPatientworkannexData) . PHP_EOL;

            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>&$itemPatientworkannexDataValue) {

                if (!empty($patientNameArr) && isset($patientNameArr[$itemPatientworkannexDataValue['patient_id']]) ){
                    $patient_name = $patientNameArr[$itemPatientworkannexDataValue['patient_id']]['patient_name'];
                    $patient_number = $patientNameArr[$itemPatientworkannexDataValue['patient_id']]['patient_number'];
                    $patientNameNumber = '';
                    if (!empty($patient_number)) $patientNameNumber = '【'.$patient_number.'】';
                    if (!empty($patient_name)) $patientNameNumber .= $patient_name;
                    $itemPatientworkannexDataValue['patient_name'] = $patientNameNumber;
                }

                $category_id = $this->LocalService()->itemForm->getOneFieldVal('checklist_id',[
                    'item_id' => $itemPatientworkannexDataValue['item_id'],
                    'is_del' => 0,
                    'id' => $itemPatientworkannexDataValue['form_id']
                ]);
                $itemPatientworkannexDataValue['form_name']  = $this->LocalService()->itemForm->getOneFieldVal('name',[
                    'item_id' => $itemPatientworkannexDataValue['item_id'],
                    'is_del' => 0,
                    'id' => $itemPatientworkannexDataValue['form_id']
                ]);
                $itemPatientworkannexDataValue['stage_name'] = $this->LocalService()->itemResearchstage->getOneFieldVal('stage_name',[
                    'is_del' => 0,
                    'id' => $itemPatientworkannexDataValue['researchstage_id']
                ]);//
                $itemPatientworkannexDataValue['check_name'] = $this->LocalService()->itemChecktime->getOneFieldVal('check_name',[
                    'is_del' => 0,
                    'id' => $itemPatientworkannexDataValue['checktime_id']
                ]);//


                $whereItemChecknameNew['where'] = [
                    'category_id' =>$category_id,
                    'is_del' => 0,
                    'item_id' => $itemPatientworkannexDataValue['item_id']
                ];
                $whereItemChecknameOld['where'] = [
                    'item_id' => $itemPatientworkannexDataValue['item_id'],
                    'is_del' => 0,
                    'category_id' => $item['oldCategory_id']
                ];
                $whereItemChecknameOld['columns'] = $whereItemChecknameNew['columns'] = ['id','item_id','category_id','name','checkname_id','variable'];
                $oldItemChecknameData = $this->LocalService()->itemCheckname->fetchAll($whereItemChecknameOld);
                $newItemChecknameData = $this->LocalService()->itemCheckname->fetchAll($whereItemChecknameNew);
                if (empty($newItemChecknameData) || empty($oldItemChecknameData)){
                    echo "当前老分类或新分类为空了==分类id：".$item['oldCategory_id'] . PHP_EOL;
                    continue;
                }
                $variableOld = array_column($oldItemChecknameData,'variable');
                $variableFilterOld = array_filter($variableOld);

                $variableNew = array_column($newItemChecknameData,'variable');
                $variableFilterNew = array_filter($variableNew);

                if(count($variableOld) != count($variableFilterOld)){
                    echo "当前老分类（变量名称）为空了==分类id：".$item['oldCategory_id'] . PHP_EOL;
                    continue;
                }
                if(count($variableNew) != count($variableFilterNew)){
                    echo "当前新分类（变量名称）为空了==分类id：".$category_id . PHP_EOL;
                    continue;
                }


                $oldItemChecknameDatas = array_column($oldItemChecknameData,null,'variable');
//                echo '<pre>';print_r($oldItemChecknameDatas);die;
                $newChecknameDatas = [];
                $oldChecknameDatas = [];
                foreach ($newItemChecknameData as $newItemChecknameDataKey=>&$newItemChecknameDataValue){
                    if (isset($oldItemChecknameDatas[$newItemChecknameDataValue['variable']])){
                        $newItemChecknameDataValue['newCategoryId'] = $newItemChecknameDataValue['category_id'];
                        $newItemChecknameDataValue['oldCategory_id'] = $item['oldCategory_id'];

                        $newItemChecknameDataValue['newCheckName'] = $newItemChecknameDataValue['name'];
                        $newItemChecknameDataValue['oldCheckName'] = $oldItemChecknameDatas[$newItemChecknameDataValue['variable']]['name'];

                        $newItemChecknameDataValue['newCheckId'] = $newItemChecknameDataValue['id'];
                        $newItemChecknameDataValue['oldCheckId'] = $oldItemChecknameDatas[$newItemChecknameDataValue['variable']]['id'];


                        $newItemChecknameDataValue['patient_form_id'] = $itemPatientworkannexDataValue['patient_form_id'];

                        $newItemChecknameDataValue['form_id'] = $itemPatientworkannexDataValue['form_id'];
                        $newItemChecknameDataValue['form_name'] = $itemPatientworkannexDataValue['form_name'];

                        $newItemChecknameDataValue['patient_id'] = $itemPatientworkannexDataValue['patient_id'];
                        $newItemChecknameDataValue['patient_name'] = $itemPatientworkannexDataValue['patient_name'];

                        $newItemChecknameDataValue['checktime_id'] = $itemPatientworkannexDataValue['checktime_id'];
                        $newItemChecknameDataValue['check_name'] = $itemPatientworkannexDataValue['check_name'];

                        $newItemChecknameDataValue['researchstage_id'] = $itemPatientworkannexDataValue['researchstage_id'];
                        $newItemChecknameDataValue['stage_name'] = $itemPatientworkannexDataValue['stage_name'];
                        $newChecknameDatas[$newItemChecknameDataValue['newCheckName']] = $oldChecknameDatas[$newItemChecknameDataValue['oldCheckName']] =  $newItemChecknameDataValue;

                    }
                }


                $whereItemIdentificationresultchange['where'] = [
                    'item_id' => $itemPatientworkannexDataValue['item_id'],
                    'is_del' => 0,
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                ];
                $whereItemIdentificationresultchange['columns'] = ['id','item_checkname_id','item_name','result','is_normal_type','update_user_id','update_time'];
                $itemIdentificationresultchangeDatas = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);

                //附件表单是否要解锁，0为要解锁，1为不用解锁
                $unLockFlag = 0;
                if(!empty($itemIdentificationresultchangeDatas)){
                    $oldCheckNamesArr = array_column($newChecknameDatas,'oldCheckName');
                    $oldCheckIdsArr = array_column($newChecknameDatas,'oldCheckId');

                    $itemPatientworkannexDataValue['itemCheckName'] = $newItemChecknameData;
                    $itemPatientworkannexDataValue['itemChangeCheckName'] = $itemIdentificationresultchangeDatas;

                    if($itemPatientworkannexDataValue['category_id'] == $category_id){
                        $unLockFlag = 1;
                        unset($itemPatientworkannexData[$itemPatientworkannexDataKey]);
                        continue;
                    }
                    $changeCSIdSaveArr = [];
                    $changeCount = count($itemIdentificationresultchangeDatas);
                    $changeIdArr = array_column($itemIdentificationresultchangeDatas,'id');
                    $patient_change_id = implode(', ', $changeIdArr);
                    echo 'change下的总数据：'.$changeCount.PHP_EOL;

                    if(!empty($patient_change_id)){
                        $whereItemCsae['where'] = [
                            'is_del' => 0,
                            'patient_change_id' => $changeIdArr
                        ];
                        $whereItemCsae['columns'] = ['id','item_checkname_id','item_name','result','is_normal_type','ae_type','update_user_id','update_time','patient_change_id'];
                        $itemCsaeData = $this->LocalService()->itemCsae->fetchAll($whereItemCsae);

                        if(!empty($itemCsaeData)){
                            $itemCsaeDatas = array_column($itemCsaeData,null,'patient_change_id');
                            foreach ($itemIdentificationresultchangeDatas as $itemIdentificationresultchangeDatasKey=>$itemIdentificationresultchangeDatasValue){

                                if(isset($oldChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]) || isset($newChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']])){
                                    echo 'change（changeAndCs）下有要调整的数据：'.count($changeCSIdSaveArr).PHP_EOL;

                                    $unLockFlag = 1;
                                    $changeCSIdSaveArr[] = $itemIdentificationresultchangeDatasValue['id'];
                                    if(isset($oldChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']])){
                                        $upChange['item_checkname_id'] = $oldChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['newCheckId'];
                                        $upChange['item_name'] = $oldChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['newCheckName'];
                                        $upChange['category_id'] = $oldChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['newCategoryId'];
                                        $upChange['checkname_id'] = $oldChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['checkname_id'];
                                        $upChange['update_user_id'] = $itemIdentificationresultchangeDatasValue['update_user_id']?:0;
                                        $upChange['update_time'] = $itemIdentificationresultchangeDatasValue['update_time']?:0;
                                        $upChange['lock_state'] = 1;
                                        $resultChange = $this->LocalService()->itemIdentificationresultchange->update($upChange,[
                                            'id' => $itemIdentificationresultchangeDatasValue['id']
                                        ]);
                                        if (isset($itemCsaeDatas[$itemIdentificationresultchangeDatasValue['id']])){
                                            $upChange['update_user_id'] = $itemCsaeDatas[$itemIdentificationresultchangeDatasValue['id']]['update_user_id']?:0;
                                            $upChange['update_time'] = $itemCsaeDatas[$itemIdentificationresultchangeDatasValue['id']]['update_time']?:0;
                                            $resultCsae = $this->LocalService()->itemCsae->update($upChange,[
                                                'patient_change_id' => $itemIdentificationresultchangeDatasValue['id']
                                            ]);

                                        }
                                        continue;
                                    }
                                    if(isset($newChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']])){
                                        $upChange['item_checkname_id'] = $newChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['newCheckId'];
                                        $upChange['item_name'] = $newChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['newCheckName'];
                                        $upChange['category_id'] = $newChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['newCategoryId'];
                                        $upChange['checkname_id'] = $newChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['checkname_id'];
                                        $upChange['update_user_id'] = $itemIdentificationresultchangeDatasValue['update_user_id'];
                                        $upChange['update_time'] = $itemIdentificationresultchangeDatasValue['update_time'];
                                        $upChange['lock_state'] = 1;
                                        $resultChange = $this->LocalService()->itemIdentificationresultchange->update($upChange,[
                                            'id' => $itemIdentificationresultchangeDatasValue['id']
                                        ]);
                                        if (isset($itemCsaeDatas[$itemIdentificationresultchangeDatasValue['id']])){
                                            $upChange['update_user_id'] = $itemCsaeDatas[$itemIdentificationresultchangeDatasValue['id']]['update_user_id']?:0;
                                            $upChange['update_time'] = $itemCsaeDatas[$itemIdentificationresultchangeDatasValue['id']]['update_time']?:0;
                                            $resultCsae = $this->LocalService()->itemCsae->update($upChange,[
                                                'patient_change_id' => $itemIdentificationresultchangeDatasValue['id']
                                            ]);

                                        }
                                        continue;
                                    }

                                }else{
                                    if (isset($itemCsaeDatas[$itemIdentificationresultchangeDatasValue['id']])){
                                        $aeType = $itemCsaeDatas[$itemIdentificationresultchangeDatasValue['id']]['ae_type'];
                                        if (in_array($aeType,[5,6])){
                                            echo 'cs（changeAndCs）下的总数据：'.count($changeCSIdSaveArr).PHP_EOL;
                                            $changeCSIdSaveArr[] = $itemIdentificationresultchangeDatasValue['id'];
                                        }
                                    }

                                }



                            }

                        }else{
                            foreach ($itemIdentificationresultchangeDatas as $itemIdentificationresultchangeDatasKey=>$itemIdentificationresultchangeDatasValue){
                                if(isset($oldChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]) || isset($newChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']])){
                                    echo 'change（只有change）下有要调整的数据：'.count($changeCSIdSaveArr).PHP_EOL;

                                    $unLockFlag = 1;
                                    $changeCSIdSaveArr[] = $itemIdentificationresultchangeDatasValue['id'];
                                    if(isset($oldChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']])){
                                        $upChange['item_checkname_id'] = $oldChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['newCheckId'];
                                        $upChange['item_name'] = $oldChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['newCheckName'];
                                        $upChange['category_id'] = $oldChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['newCategoryId'];
                                        $upChange['checkname_id'] = $oldChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['checkname_id'];
                                        $upChange['update_user_id'] = $itemIdentificationresultchangeDatasValue['update_user_id']?:0;
                                        $upChange['update_time'] = $itemIdentificationresultchangeDatasValue['update_time']?:0;
                                        $upChange['lock_state'] = 1;
                                        $resultChange = $this->LocalService()->itemIdentificationresultchange->update($upChange,[
                                            'id' => $itemIdentificationresultchangeDatasValue['id']
                                        ]);
                                        continue;
                                    }
                                    if(isset($newChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']])){
                                        $upChange['item_checkname_id'] = $newChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['newCheckId'];
                                        $upChange['item_name'] = $newChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['newCheckName'];
                                        $upChange['category_id'] = $newChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['newCategoryId'];
                                        $upChange['checkname_id'] = $newChecknameDatas[$itemIdentificationresultchangeDatasValue['item_name']]['checkname_id'];
                                        $upChange['update_user_id'] = $itemIdentificationresultchangeDatasValue['update_user_id'];
                                        $upChange['update_time'] = $itemIdentificationresultchangeDatasValue['update_time'];
                                        $upChange['lock_state'] = 1;
                                        $resultChange = $this->LocalService()->itemIdentificationresultchange->update($upChange,[
                                            'id' => $itemIdentificationresultchangeDatasValue['id']
                                        ]);
                                        continue;
                                    }
                                }else{
                                    if (isset($itemCsaeDatas[$itemIdentificationresultchangeDatasValue['id']])){
                                        $aeType = $itemCsaeDatas[$itemIdentificationresultchangeDatasValue['id']]['ae_type'];
                                        if (in_array($aeType,[5,6])){
                                            echo 'cs（只有change）下的总数据：'.count($changeCSIdSaveArr).PHP_EOL;
                                            $changeCSIdSaveArr[] = $itemIdentificationresultchangeDatasValue['id'];
                                        }
                                    }

                                }

                            }

                        }


                    }

                    $delChangeIds = implode(',',array_diff($changeIdArr,$changeCSIdSaveArr));
                    if (isset($delChangeIds) && !empty($delChangeIds)){
                        $delChangeIds = trim($delChangeIds,',');
                        $resultChange = $this->LocalService()->itemIdentificationresultchange->update(['is_del'=>1],[
                            'id' => explode(',', $delChangeIds)
                        ]);
                        $resultCsae = $this->LocalService()->itemCsae->update(['is_del'=>1],[
                            'patient_change_id' => explode(',', $delChangeIds)
                        ]);
                    }

                    //处理在当前指标里，但不在当前表单里的数据

                    if (!empty($formIdArr)){
                        $whereItemIdentificationresultchange['where'] = [
                            'is_del' => 0,
                            'form_id' => $formIdArr,
                            'item_id' => $itemPatientworkannexDataValue['item_id']
                        ];
                        $whereItemIdentificationresultchange['columns'] = ['id','checktime_id','patient_form_id','item_checkname_id','item_name','result','is_normal_type','update_user_id','update_time'];
                        $itemChangeFormDatas = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
                        if(!empty($itemChangeFormDatas)){
                            //change-id
                            $itemChangeFormIdArr = array_column($itemChangeFormDatas,'id');
                            $itemCsaeChangeIdArr = $this->LocalService()->itemCsae->fetchCol('patient_change_id',[
                                'is_del' => 0,
                                'ae_type' => [5,6],
                                'patient_change_id' => $itemChangeFormIdArr,
                            ]);

                            if  (!empty($itemCsaeChangeIdArr)){
                                $newItemChangeFormIdArr = array_diff($itemChangeFormIdArr,$itemCsaeChangeIdArr);
                            }else{
                                $newItemChangeFormIdArr = $itemChangeFormIdArr;
                            }

                            $newItemChangeFormDatas = [];
                            foreach ($itemChangeFormDatas as $itemChangeFormDatasKey=>&$itemChangeFormDatasValue){
                                if (in_array($itemChangeFormDatasValue['item_name'],$oldCheckNamesArr) || in_array($itemChangeFormDatasValue['item_checkname_id'],$oldCheckIdsArr)){
                                    if(in_array($itemChangeFormDatasValue['id'],$newItemChangeFormIdArr)){
                                        echo '(老分类里遗留指标删除）下有要调整的数据：'.PHP_EOL;
                                        $changeUP = [
                                            'is_del'=>1,
                                            'update_user_id'=>$itemChangeFormDatasValue['update_user_id']?:0,
                                            'update_time'=>$itemChangeFormDatasValue['update_time']?:0,
                                        ];
                                        $resultChange = $this->LocalService()->itemIdentificationresultchange->update($changeUP,[
                                            'id' => explode(',', (string)$itemChangeFormDatasValue['id'])
                                        ]);
                                        $resultCsae = $this->LocalService()->itemCsae->update(['is_del'=>1],[
                                            'patient_change_id' => explode(',', (string)$itemChangeFormDatasValue['id'])
                                        ]);
                                        $itemChangeFormDatasValue['flag'] = 0;
                                    }else{
                                        $itemChangeFormDatasValue['flag'] = 1;
                                    }
                                }else{
                                    $itemChangeFormDatasValue['flag'] = 1;
                                }
                                $newItemChangeFormDatas[$itemChangeFormDatasValue['checktime_id'].'-'.$itemChangeFormDatasValue['patient_form_id']][] = $itemChangeFormDatasValue;
                            }
                            foreach ($newItemChangeFormDatas as $newItemChangeFormDatasKey=>$newItemChangeFormDatasValue){
                                $flagArr = array_column($newItemChangeFormDatasValue,'flag');
                                if (!in_array(1,$flagArr)){
                                    echo '(老分类里遗留指标全部删除）解锁：'.PHP_EOL;
                                    $checkAndFormId = explode('-',$newItemChangeFormDatasKey);
                                    $whereWorkArr['where'] = $whereWork = [
                                        'is_del' => 0,
                                        'item_id' => $itemPatientworkannexDataValue['item_id'],
                                        'checktime_id' => $checkAndFormId[0],
                                        'patient_form_id' => $checkAndFormId[1]
                                    ];
                                    $whereWorkArr['order'] = ['update_time Desc'];
                                    $workInfo = $this->LocalService()->itemPatientworkannex->fetchOne($whereWorkArr);
                                    $upWorks = [
                                        'lock_state'=>0,
                                        'change_type'=>0,
                                        'update_user_id'=>$workInfo['update_user_id']?:0,
                                        'update_time'=>$workInfo['update_time']?:0,
                                    ];
                                    $resultWork = $this->LocalService()->itemPatientworkannex->update($upWorks,$whereWork);
                                }
                            }
                        }
                    }



                }

                $upWork = [
                    'category_id' => $category_id,
                    'update_user_id' => $itemPatientworkannexDataValue['update_user_id']?:0,
                    'update_time' => $itemPatientworkannexDataValue['update_time']?:0,
                ];
                $whereWork = [
                    'is_del' => 0,
                    'item_id' => $itemPatientworkannexDataValue['item_id'],
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                ];
                if(empty($unLockFlag)){
                    echo '(新分类里指标全部删除）解锁：'.PHP_EOL;
                    $upWork['lock_state'] = 0;
                    $upWork['change_type'] = 0;
                    $resultWork = $this->LocalService()->itemPatientworkannex->update($upWork,$whereWork);
                }else{
                    echo '(调整新分类的附件数据）'.PHP_EOL;
                    $resultWork = $this->LocalService()->itemPatientworkannex->update($upWork,$whereWork);
                }

            }
        }
        if (empty($itemPatientworkannexData)){
            echo '当前项目：'.$item['item_id'].'当前老分类下'.$item['oldCategory_id'].'附件没有数据';die;
        }
        echo '<pre>';print_r($itemPatientworkannexData);die;

    }

    //补附件数据
    public function insertWork($whereData = []){
        if (empty($whereData['item_id']) || empty($whereData['form_id']) || empty($whereData['oldCategory_id'])){
            echo '参数不正确';die;
        }
        $item_id = $whereData['item_id'];
        $form_id = $whereData['form_id'];
        $oldCategory_id = $whereData['oldCategory_id'];
        $whereItemIdentificationresultchange['where'] = [
            'is_del' => 0,
            'lock_state' => 1,
            'item_id' => $item_id,
            'form_id' => explode(',', (string)$form_id),
            'category_id' => $oldCategory_id,
        ];
        $whereItemIdentificationresultchange['group'] =	 ['checktime_id','patient_form_id'];

        $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
        echo '总条数：'.count($itemIdentificationresultchangeData).PHP_EOL;
        if (!empty($itemIdentificationresultchangeData)){
            foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataK=>$itemIdentificationresultchangeDataV){
                $itemPatientworkannexCount = $this->LocalService()->itemPatientworkannex->getCount( 'is_del=0 and checktime_id=' . $itemIdentificationresultchangeDataV['checktime_id'].' and patient_form_id ='.$itemIdentificationresultchangeDataV['patient_form_id'].' and item_id ='.$itemIdentificationresultchangeDataV['item_id']);
                if (empty($itemPatientworkannexCount)){
//                `is_check` tinyint NOT NULL DEFAULT '0' COMMENT '不检查且删除图片后为1，默认为0',


                    $insertData = [];

                    $insertData['update_user_id'] = 0;
                    $insertData['update_time'] = 0;
                    $insertData['lock_state'] = 1;
                    $insertData['ocr_state'] = 1;
                    $insertData['confirm_state'] = 1;
                    $insertData['annex_path'] = '';
//                    $insertData['annex_type'] = 1;
                    if ($itemIdentificationresultchangeDataV['update_user_id'] != 30){
                        $insertData['update_user_id'] = $itemIdentificationresultchangeDataV['update_user_id']?:0;
                        $insertData['update_time'] = $itemIdentificationresultchangeDataV['update_time']?:0;
                    }
                    if (!empty($itemIdentificationresultchangeDataV['annex_path'])){
                        $anexPath = explode(',',$itemIdentificationresultchangeDataV['annex_path']);
                        $imgPath = 'https://5-mc.cn/common/showPic?path=';

                        $insertData['annex_path'] = str_replace($imgPath,'',$anexPath[0]);
                        $title = explode('.',$insertData['annex_path']);
                        $insertData['annex_title'] = end($title);
//                         foreach ($anexPath as $pathK=>$pathV){
//                             $insertData['annex_path'] = $pathV;
//                             $title = explode('.',$pathV);
//                             $insertData['annex_title'] = end($title);
//
//                         }

                    }

                    $insertData['lock_state'] = 1;
                    $insertData['annex_type'] = $itemIdentificationresultchangeDataV['annex_type'] ?:0;

                    $insertData['ocr_id'] = $itemIdentificationresultchangeDataV['ocr_id'] ? :0;
                    $insertData['create_user_id'] = $itemIdentificationresultchangeDataV['create_user_id']?:0;
                    $insertData['up_annex_date'] = $insertData['create_time'] = $itemIdentificationresultchangeDataV['create_time']?:0;
                    $insertData['item_id'] = $itemIdentificationresultchangeDataV['item_id'] ? :0;
                    $insertData['itemsig_id'] = $itemIdentificationresultchangeDataV['itemsig_id'] ? :0;
                    $insertData['patient_id'] = $itemIdentificationresultchangeDataV['patient_id'] ? :0;
                    $insertData['checktime_id'] = $itemIdentificationresultchangeDataV['checktime_id'] ? :0;
                    $insertData['researchstage_id'] = $itemIdentificationresultchangeDataV['researchstage_id'] ?:0;
                    $insertData['form_id'] = $itemIdentificationresultchangeDataV['form_id'] ? :0;
                    $insertData['collect_date'] = $itemIdentificationresultchangeDataV['collect_date']?:0;

//                    $insertData['patientchecktime_id'] = $itemIdentificationresultchangeDataV['category_id'] ? :0;
                    $insertData['category_id'] = $itemIdentificationresultchangeDataV['category_id'] ? :0;
                    $insertData['is_result'] = 1;
                    $insertData['patient_form_id'] = $itemIdentificationresultchangeDataV['patient_form_id'] ? :0;
                    $insertData['report_type'] = $itemIdentificationresultchangeDataV['report_type']?:0;
                    $insertData['change_type'] = 1;
                    $itemWorkannexResult = $this->LocalService()->itemPatientworkannex->save($insertData);
                    echo 'id:'.$itemWorkannexResult.PHP_EOL;
                }
            }
        }
    }


    public function contab(){

//        $iteminfoData = $this->patientattrUpdate($item=107);
        $limit = $_POST['limit'] ?: '5000';
        $page = $_POST['page'] ?: '1';
        $smallItemId = $_POST['item_id'];
//        $iteminfoData = $this->newLockItemPatientWorkannex($smallItemId,$page,$limit);
//        $iteminfoData = $this->lockItemPatientWorkAndChange();
//        $iteminfoData = $this->lockItemPatientWorkChangeType();
        //外解
//        $iteminfoData = $this->unLockItemPatientWorkAndChange(103);
//        echo '外解锁';die;
        //删除内指标
//        $iteminfoData = $this->delLockItemPatientWorkAndChange(103);

        echo '成功';
        return true;

    }
    //外锁删除内未判断的指标
    public function delLockItemPatientWorkAndChange($smallItemId){
//        $smallItemId = '103';//【MSC-ESLD20211224】人间充质干细胞治疗重症肝病的临床研究（RCT-2.1）==103

        $whereItemPatientworkannex['where'] = [
            'is_del' => 0,
            'item_id' => explode(',', (string)$smallItemId),
            new Operator('annex_type', Operator::OP_NE, 2),
            'lock_state' => 1,
            new Expression('FROM_UNIXTIME(up_annex_date ,"%Y-%m-%d")=?', "2022-09-17")
        ];//annex_type !=3//只查手动写和图片上传的
        $whereItemPatientworkannex['group'] = ['checktime_id','patient_form_id','form_id'];
        $whereItemPatientworkannex['columns'] = ['id','checktime_id','patient_form_id','form_id','itemsig_id','patient_id'];
        $whereItemPatientworkannex['order'] = ['id desc'];
        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);

        if (!empty($itemPatientworkannexData)){
            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>$itemPatientworkannexDataValue) {
                $whereItemIdentificationresultchange['where'] = [
                    'is_del' => 0,
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                    'item_id' => $smallItemId,
                ];
                $whereItemIdentificationresultchange['columns'] =['id','collect_date','lock_state','patientworkannex_id','item_checkname_id','patient_id','itemsig_id','is_sure'];
                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
                if (!empty($itemIdentificationresultchangeData)){
                    $itemChecknameId = array_column($itemIdentificationresultchangeData,'item_checkname_id');
                    $itemChecknameIdUniqueArr = array_unique($itemChecknameId);
                    $changeIdS = implode(',',array_column($itemIdentificationresultchangeData,'id'));
                    $lockStateArr = array_column($itemIdentificationresultchangeData,'lock_state');
                    $isSureArr = array_column($itemIdentificationresultchangeData,'is_sure');
//                    (count($itemChecknameIdUniqueArr) != count($itemChecknameId)) &&
                    if (in_array(0,$lockStateArr) && in_array(1,$lockStateArr) && in_array(0,$isSureArr) && in_array(1,$isSureArr)){
                        $changeIdStr = '';
                        foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey=>$itemIdentificationresultchangeDataValue) {
                            if ($itemIdentificationresultchangeDataValue['is_sure'] == 0){
                                $changeIdStr .= $itemIdentificationresultchangeDataValue['id'].',';
                            }
                        }
                        if (!empty($changeIdStr)){
                            $newChangeIdStr =  trim($changeIdStr,',');
                            if (!empty($newChangeIdStr)){
                                $resultWork = $this->LocalService()->itemIdentificationresultchange->update(['is_del'=>1],[
                                    'id' => explode(',', $newChangeIdStr)
                                ]);

                            }
                        }
                    }
                }
            }
        }
        return true;

    }
    public function selectChagne($useWhere = []){
        $oldCheckName = $useWhere['oldCheckName']?:'';
        $item_id = $useWhere['item_id']?:0;
        $oldCategory_id = $useWhere['oldCategory_id']?:0;
        $type = $useWhere['type']?:0;
        $form_id = $useWhere['form_id']?:0;

        $oldCheckNameArr = explode(',',$oldCheckName);
        $newCheckNames = '';
        foreach ($oldCheckNameArr as $oldCheckNameValue){
            $newCheckNames .= '"'.$oldCheckNameValue.'",';
        }
        $newCheckNames = trim($newCheckNames,',');

        $whereItemCheckname['where'] = [
            'is_del' => 0,
            'name' => $oldCheckNameArr,
            'item_id' => $item_id,
            'category_id' => $oldCategory_id,
        ];
        $whereItemCheckname['columns'] = ['id','item_id','category_id','name','checkname_id'];
        $itemChecknameData = $this->LocalService()->itemCheckname->fetchAll($whereItemCheckname);
        $itemChecknameIdArr = array_column($itemChecknameData,'id');
        $itemChecknameIds = implode(',',$itemChecknameIdArr);
        $change['where'] = [
            'is_del' => 0,
            'item_id' => $item_id,
            'category_id' => $oldCategory_id,
            'item_checkname_id' => $itemChecknameIdArr
        ];
        //1不在表单里的数据；0 为在表单里的数据
        $msig = '在当前表单下的数据';
        if (!empty($type)){
            $change['where']['form_id'] = explode(',', (string)$form_id);
        }else{
            $msig = '不在当前表单下的数据';
            $change['where'][] = new NotIn('form_id', explode(',', (string)$form_id));

        }
        echo $msig.PHP_EOL;
        $change['columns'] = ['id','item_id','category_id','itemsig_id','form_id','patient_id','checktime_id','patient_form_id','researchstage_id','item_checkname_id','update_time','create_time','update_user_id','create_user_id' ];
        $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($change);
        $item_csae  = [];
        $item_csaes  = [];
        $delChange = [];
        $updateChange = [];
        $i = 0;
        $cs = [];
        foreach ($itemIdentificationresultchangeData as &$itemIdentificationresultchangeDataV){
            $itemIdentificationresultchangeDataV['form_name'] = $this->LocalService()->itemForm->getOneFieldVal('name',[
                'is_del' => 0,
                'item_id' => $item_id,
                'id' => $itemIdentificationresultchangeDataV['form_id'],
            ]);
            $itemIdentificationresultchangeDataV['item_name'] = $this->LocalService()->itemCheckname->getOneFieldVal('name',[
                'is_del' => 0,
                'item_id' => $item_id,
                'id' => $itemIdentificationresultchangeDataV['item_checkname_id'],
            ]);
            $stage_name = $this->LocalService()->itemResearchstage->getOneFieldVal('stage_name',[
                'is_del' => 0,
                'id' => $itemIdentificationresultchangeDataV['researchstage_id'],
            ]);//
            $check_name = $this->LocalService()->itemChecktime->getOneFieldVal('check_name',[
                'is_del' => 0,
                'id' => $itemIdentificationresultchangeDataV['checktime_id'],
            ]);
            $itemIdentificationresultchangeDataV['patient_name'] = $this->LocalService()->patient->getOneFieldVal('patient_name',[
                'is_del' => 0,
                'id' => $itemIdentificationresultchangeDataV['patient_id'],
            ]);//
            $itemIdentificationresultchangeDataV['check_stage_name'] = '['.$check_name.']'.$stage_name;
            $itemIdentificationresultchangeDataV['itemsig_name'] = $this->LocalService()->itemSignatory->itemSigninfo($itemIdentificationresultchangeDataV['itemsig_id'], $item_id,0)[0]['label'];
            !empty($itemIdentificationresultchangeDataV['create_time']) && $itemIdentificationresultchangeDataV['create_time'] = date('Y-m-d H:i:s',$itemIdentificationresultchangeDataV['create_time']);
            !empty($itemIdentificationresultchangeDataV['update_time']) && $itemIdentificationresultchangeDataV['update_time'] = date('Y-m-d H:i:s',$itemIdentificationresultchangeDataV['update_time']);
            $itemIdentificationresultchangeDataV['update_user_id'] = $this->LocalService()->adminUser->getOneFieldVal('realname',[
                'is_del' => 0,
                'id' => $itemIdentificationresultchangeDataV['update_user_id'],
            ]);//
            $itemIdentificationresultchangeDataV['create_user_id'] = $this->LocalService()->adminUser->getOneFieldVal('realname', [
                'is_del' => 0,
                'id' => $itemIdentificationresultchangeDataV['create_user_id'],
            ]);//

            $whereItemCsae = [
                'is_del' => 0,
                'ae_type' => [5, 6],
                'item_id' => $item_id,
                'category_id' => $oldCategory_id,
                'checktime_id' => $itemIdentificationresultchangeDataV['checktime_id'],
                'patient_form_id' => $itemIdentificationresultchangeDataV['patient_form_id'],
            ];
            if (!empty($type)){
                $whereItemCsae[] = new NotIn('form_id', explode(',', string($form_id)));
            }else{
                $whereItemCsae['from_id'] = explode(',', string($form_id));

            }
            $itemIdentificationresultchangeDataV['item_csae'] = $this->LocalService()->itemCsae->getCount($whereItemCsae);
            if (!empty($itemIdentificationresultchangeDataV['item_csae'])){
                $cs[$i]['cs'] = '有cs';
                $cs[$i]['cs'] = $itemIdentificationresultchangeDataV['checktime_id'].'-'.$itemIdentificationresultchangeDataV['patient_form_id'].'-'.$item_id;
                $item_csaes[$i]['item_name'] = $itemIdentificationresultchangeDataV['item_name'];
                $item_csaes[$i]['form_name'] = $itemIdentificationresultchangeDataV['form_name'];
                $item_csaes[$i]['patient_name'] = $itemIdentificationresultchangeDataV['patient_name'];
                $item_csaes[$i]['check_stage_name'] = $itemIdentificationresultchangeDataV['check_stage_name'];
                $item_csaes[$i]['form_id'] = $itemIdentificationresultchangeDataV['form_id'];
                $item_csaes[$i]['itemsig_name'] =$itemIdentificationresultchangeDataV['itemsig_name'];
                $item_csae[$itemIdentificationresultchangeDataV['checktime_id'].'-'.$itemIdentificationresultchangeDataV['patient_form_id']] =  $itemIdentificationresultchangeDataV['item_csae'];
            }else{
                $whereItemPatientworkannex['where'] = [
                    'item_id' => $item_id,
                    'checktime_id' => $itemIdentificationresultchangeDataV['checktime_id'],
                    'patient_form_id' => $itemIdentificationresultchangeDataV['patient_form_id'],
                ];
                $whereItemPatientworkannex['columns'] = ['id','checktime_id','patient_form_id','form_id','item_id','itemsig_id','patient_id','category_id','update_user_id','update_time'];
                $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);
                if (!empty($itemPatientworkannexData)){
                    $updateChange[$i] = $itemIdentificationresultchangeDataV;
                }else{
                    $delChange[$i]['id'] = $itemIdentificationresultchangeDataV['id'];
                    $delChange[$i]['item_name'] = $itemIdentificationresultchangeDataV['item_name'];
                    $delChange[$i]['form_name'] = $itemIdentificationresultchangeDataV['form_name'];
                    $delChange[$i]['patient_name'] = $itemIdentificationresultchangeDataV['patient_name'];
                    $delChange[$i]['check_stage_name'] = $itemIdentificationresultchangeDataV['check_stage_name'];
                    $delChange[$i]['itemsig_name'] = $itemIdentificationresultchangeDataV['itemsig_name'];
                    $delChange[$i]['form_id'] = $itemIdentificationresultchangeDataV['form_id'];
                }
            }



            $i++;
        }
        echo '总数：'.count($itemIdentificationresultchangeData).PHP_EOL;
        echo 'cs:<pre>';print_r($cs).PHP_EOL;
        if (!empty($item_csae)){
            if (in_array(1,$item_csae)){
                echo '有cs：<pre>';print_r($item_csae).PHP_EOL;
            }
        }
        if (!empty($delChange)){
            echo '没有附件，不检查的指标，删除总数：'.count($delChange).PHP_EOL;
            echo 'delChang:<pre>';print_r($delChange).PHP_EOL;
            echo  var_export($delChange).PHP_EOL;
        }
        if (!empty($updateChange)){
            echo 'upChang:<pre>';print_r($updateChange).PHP_EOL;

        }
        echo 'cs数据查询：<pre>';print_r($item_csaes).PHP_EOL;
        echo '要更新的数据：<pre>';print_r($itemIdentificationresultchangeData).PHP_EOL;die;



    }

    //外解锁
    public function unLockItemPatientWorkAndChange($smallItemId){
        //时间条件
        $whereItemPatientworkannex['where'] = [
            'is_del' => 0,
            'item_id' => $smallItemId,
            new Operator('annex_type', Operator::OP_NE, 2),
            'lock_state' => 1,
            new Expression('FROM_UNIXTIME(up_annex_date ,"%Y-%m-%d")=?', "2022-09-17"),
        ];//annex_type !=3//只查手动写和图片上传的
        $whereItemPatientworkannex['group'] = ['checktime_id','patient_form_id','form_id'];
        $whereItemPatientworkannex['columns'] = ['id','checktime_id','patient_form_id','form_id','itemsig_id','patient_id'];
        $whereItemPatientworkannex['order'] = ['id desc'];
        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);

        if (!empty($itemPatientworkannexData)){
            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>$itemPatientworkannexDataValue) {
                $whereItemIdentificationresultchange['where'] = [
                    'is_del' => 0,
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                    'item_id' => $smallItemId,
                ];
                $whereItemIdentificationresultchange['columns'] =['id','collect_date','lock_state','patientworkannex_id','item_checkname_id','patient_id','itemsig_id'];
                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
                if (!empty($itemIdentificationresultchangeData)){
                    $itemChecknameId = array_column($itemIdentificationresultchangeData,'item_checkname_id');
                    $itemChecknameIdUniqueArr = array_unique($itemChecknameId);
                    $changeIdS = implode(',',array_column($itemIdentificationresultchangeData,'id'));
                    $lockStateArr = array_column($itemIdentificationresultchangeData,'lock_state');
//                    (count($itemChecknameIdUniqueArr) != count($itemChecknameId)) &&
//                    && in_array(1,$lockStateArr)
                    if (in_array(0,$lockStateArr)){
                        $resultWork = $this->LocalService()->itemPatientworkannex->update(['lock_state'=>0],[
                            'id' => $itemPatientworkannexDataValue['id']
                        ]);
                    }
                }
            }
        }
        return true;

    }

    //内外锁定特殊类表单更新change_type状态
    public function lockItemPatientWorkChangeType($smallItemId){
//        $smallItemId = '72';
//        【5030005】晚期患者-同种异体过继免疫细胞治疗联合抗病毒治疗晚期艾滋病的临床研究==72
        //时间条件
        $whereItemPatientworkannex['where'] =  [
            'is_del' => 0,
            'report_type' => 1,
            'item_id' => $smallItemId,
            new Operator('annex_type', Operator::OP_NE, 2),
            'lock_state' => 1,
            new Expression('FROM_UNIXTIME(up_annex_date ,"%Y-%m-%d")=?', "2022-09-17")
        ];
        $whereItemPatientworkannex['group'] = ['checktime_id','patient_form_id','form_id'];
        $whereItemPatientworkannex['columns'] = ['id','checktime_id','patient_form_id','form_id','itemsig_id','patient_id'];
        $whereItemPatientworkannex['order'] = ['id desc'];
        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);
        if (!empty($itemPatientworkannexData)){
            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>$itemPatientworkannexDataValue) {
                $whereItemIdentificationresultchange['where'] = [
                    'is_del' => 0,
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                    'item_id' => $smallItemId,
                ];
                $whereItemIdentificationresultchange['columns'] =['id','collect_date','lock_state','patientworkannex_id','item_checkname_id','patient_id','itemsig_id'];
                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
                if (!empty($itemIdentificationresultchangeData)){
                    $itemChecknameId = array_column($itemIdentificationresultchangeData,'item_checkname_id');
                    $itemChecknameIdUniqueArr = array_unique($itemChecknameId);
                    if (count($itemChecknameIdUniqueArr) != count($itemChecknameId)){
                        break;
                    }
                    $changeIdS = implode(',',array_column($itemIdentificationresultchangeData,'id'));
                    $lockStateArr = array_column($itemIdentificationresultchangeData,'lock_state');
                    if (in_array(0,$lockStateArr) && in_array(1,$lockStateArr)){
                        break;
                    }

                    if (in_array(1,$lockStateArr) && !empty($changeIdS)){
                        $resultWork = $this->LocalService()->itemPatientworkannex->update(['change_type'=>1],'is_del=0 and lock_state=1 and report_type = 1 and id ='.$itemPatientworkannexDataValue['id']);

                    }
                }
            }
        }
        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,
                    'lock_state' => 1,
                    'item_id' => $smallItemId,
                    new Operator('collect_date', Operator::OP_NE, 0)
                ];
                $whereItemIdentificationresultchange['columns'] =['id','collect_date','lock_state','patientworkannex_id','patient_id','checktime_id','form_id','patient_form_id'];

                $whereItemIdentificationresultchange['group'] = ['checktime_id','patient_form_id'];
                $whereItemIdentificationresultchange['order'] = ['id desc'];
                $whereItemIdentificationresultchange['limit'] = $limit;
                $whereItemIdentificationresultchange['offset'] = $offset;
                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);

                foreach ($itemIdentificationresultchangeData as $k => $itemIdentificationresultchangeDatum) {
                    echo "正在处理第{$k}个" . PHP_EOL;
                    $newWork['collect_date'] = $itemIdentificationresultchangeDatum['collect_date'];
                    $newWork['change_type'] = 1;
                    $newWork['lock_state'] = 1;

                    $where = [
                        'is_del' => 0,
                        'patient_id' => $itemIdentificationresultchangeDatum['patient_id'],
                        'checktime_id' => $itemIdentificationresultchangeDatum['checktime_id'],
                        'patient_form_id' => $itemIdentificationresultchangeDatum['patient_form_id'],
                    ];
                    $resultWork = $this->LocalService()->itemPatientworkannex->update($newWork,$where);
                    if ($resultWork) {
                        echo '更新成功' . PHP_EOL;
                    }

                    $j .= '<pre>'.$page.'--'.$resultWork;
                    $i++;
                }

                echo $i.$j;die;
            }else{
                $offset = intval(($page - 1) * $limit);
                //时间条件
                $time = ' and FROM_UNIXTIME(up_annex_date ,"%Y-%m-%d")="2022-09-17"';
                $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 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'];
                            $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++;
                    }
                }
            }

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

    }

    //外锁定
    public function lockItemPatientWorkannex($whereData = []){
        if (empty($whereData)){
            echo '参数不能为空';
        }
        $whereItemPatientworkannex['where'] = [
            'is_del' => 0,
            'item_id' => explode(',', $whereData['item_id']),
            'lock_state' => 0,
            new Operator('annex_type', Operator::OP_NE, 2)
        ];
        $whereItemPatientworkannex['group'] = ['checktime_id','patient_form_id','form_id'];
        $whereItemPatientworkannex['columns'] = ['id','checktime_id','patient_form_id','form_id','update_user_id','update_time','item_id','collect_date'];
        $whereItemPatientworkannex['order'] = ['id desc'];
        !empty($whereData['oldCategory_id']) && $whereItemPatientworkannex['where'] .= ' and category_id in('.$whereData['oldCategory_id'].')';
        !empty($whereData['form_id']) && $whereItemPatientworkannex['where'] .= ' and form_id in('.$whereData['form_id'].')';
        !empty($whereData['itemsig_id']) && $whereItemPatientworkannex['where'] .= ' and itemsig_id in('.$whereData['itemsig_id'].')';


        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);
        $arr = [];
        $updateWorkIds = '';
        $count = 0;
        if (!empty($itemPatientworkannexData)){
            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>$itemPatientworkannexDataValue) {
                $whereWork = [
                    'is_del' => 0,
                    'lock_state' => 0,
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                    'item_id' => $itemPatientworkannexDataValue['item_id'],
                ];
                $itemPatientworkannexIdArr = $this->LocalService()->itemPatientworkannex->fetchCol('id',$whereWork);
                $count += count($itemPatientworkannexIdArr);
                $updateWorkIds .= implode(',',$itemPatientworkannexIdArr).',';
                $arr[$itemPatientworkannexDataKey]['checktime_id'] = $itemPatientworkannexDataValue['checktime_id'];
                $arr[$itemPatientworkannexDataKey]['patient_form_id'] = $itemPatientworkannexDataValue['patient_form_id'];
                $arr[$itemPatientworkannexDataKey]['id'] = $itemPatientworkannexDataValue['id'];
                //内已锁定
                $whereItemIdentificationresultchange['where'] = [
                    'is_del' => 0,
                    'lock_state' => 1,
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                    'item_id' => $itemPatientworkannexDataValue['item_id'],
                ];
                $whereItemIdentificationresultchange['columns'] =['id','collect_date','lock_state','patientworkannex_id','update_user_id','update_time'];
                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
                if (!empty($itemIdentificationresultchangeData)){
                    $arr[$itemPatientworkannexDataKey]['changeData'] = $itemIdentificationresultchangeData;
                    $changeIdArr = array_column($whereItemIdentificationresultchange,'id');
                    if (in_array(0,$changeIdArr)){
                        $updateChange = [
                            'lock_state'=>1,
                            'lock_state_small'=>1,
                            'update_user_id'=>$itemIdentificationresultchangeDataValue[0]['update_user_id']?:0,
                            'update_time'=>$itemIdentificationresultchangeDataValue[0]['update_time']?:0,
                        ];
                        $resultchange = $this->LocalService()->itemIdentificationresultchange->update($updateChange,'id in ('.implode(',',$changeIdArr).')');
                    }
                    $updateWork = [
                        'lock_state'=>1,
                        'change_type'=>1,
                        'update_user_id'=>$itemPatientworkannexDataValue['update_user_id']?:0,
                        'update_time'=>$itemPatientworkannexDataValue['update_time']?:0,
                    ];
                    if (empty($itemPatientworkannexDataValue['collect_date'])){
                        $collect_date = 0;
                        if (empty($itemIdentificationresultchangeDataValue[0]['collect_date'])){
                            foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey=>$itemIdentificationresultchangeDataValue){
                                if (!empty($collect_date)){
                                    continue;
                                }
                                if (!empty($itemIdentificationresultchangeDataValue['collect_date'])){
                                    $collect_date = $itemIdentificationresultchangeDataValue['collect_date'];
                                }

                            }
                        }

                        $updateWork['collect_date'] = $collect_date;
                    }
                    $resultWork = $this->LocalService()->itemPatientworkannex->update($updateWork,$whereWork);
                }
            }
        }

        $data['count'] = $count;
        $data['updateWorkIds'] = trim($updateWorkIds,',');
        $data['updateWorkData'] = $arr;
        echo '<pre>';print_r($data);die;

    }

    //外锁定
    public function lockItemPatientWorkannexBack($smallItemId){
        $redis = Laminas::$serviceManager->redisExtend->setDatabase(6)->getRedisInstance();
        $keys = 'lockStatus-'.$smallItemId;
        //【CHESS-NCRCID 2106】中国肝硬化伴发轻微型肝性脑病-患者==105
        //【MSC-ESLD20211224】人间充质干细胞治疗重症肝病的临床研究（RCT-2.1）==103
        //【5030005】晚期患者-同种异体过继免疫细胞治疗联合抗病毒治疗晚期艾滋病的临床研究==72
        //【5030004】健康供者筛查-同种异体过继免疫细胞治疗联合抗病毒治疗难治性艾滋病临床研究==72
        //5030006】免疫重建失败-同种异体过继免疫疗法联合抗病毒治疗艾滋病临床试验==77
//        $smallItemId = '105,103,72,74,77';
        //时间条件
        $time = ' and FROM_UNIXTIME(up_annex_date ,"%Y-%m-%d")="2022-09-17"';
//        $time = '';
        $whereItemPatientworkannex['where'] =  'is_del=0 and item_id in(' . $smallItemId.')  and annex_type !=2  and lock_state=0'.$time;//annex_type !=3//只查手动写和图片上传的
        $whereItemPatientworkannex['group'] = ['checktime_id','patient_form_id','form_id'];
        $whereItemPatientworkannex['columns'] = ['checktime_id','patient_form_id','form_id'];
        $whereItemPatientworkannex['order'] = ['id desc'];
        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);
        $arr = [];
        if (!empty($itemPatientworkannexData)){
            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>$itemPatientworkannexDataValue) {
                $arr[$itemPatientworkannexDataKey]['checktime_id'] = $itemPatientworkannexDataValue['checktime_id'];
                $arr[$itemPatientworkannexDataKey]['patient_form_id'] = $itemPatientworkannexDataValue['patient_form_id'];
                $arr[$itemPatientworkannexDataKey]['id'] = $itemPatientworkannexDataValue['id'];
                //内已锁定
                $whereItemIdentificationresultchange['where'] = [
                    'is_del' => 0,
                    'lock_state' => 1,
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                ];
                $whereItemIdentificationresultchange['columns'] =['id','collect_date','lock_state','patientworkannex_id'];
                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
                if (!empty($itemIdentificationresultchangeData)){
                    $collect_date = 0;
                    $patientworkannex_id = '';
                    $arr[$itemPatientworkannexDataKey]['changeData'] = $itemIdentificationresultchangeData;
                    foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey=>$itemIdentificationresultchangeDataValue) {
                        if (empty($itemIdentificationresultchangeDataValue['lock_state'])){
                            $resultchange = $this->LocalService()->itemIdentificationresultchange->update(['lock_state'=>1,'lock_state_small'=>1],'id= '.$itemIdentificationresultchangeDataValue['id']);
                        }
                        if (!empty($itemIdentificationresultchangeDataValue['patientworkannex_id']) && !empty($itemIdentificationresultchangeDataValue['collect_date'])){
//                            $newWork['id'] = $itemIdentificationresultchangeDataValue['patientworkannex_id'];
                            if (!empty($collect_date) && !empty($patientworkannex_id)) break;
                            $collect_date = $itemIdentificationresultchangeDataValue['collect_date'];
                            $patientworkannex_id = $itemIdentificationresultchangeDataValue['patientworkannex_id'];
                        }
                    }
                    if (!empty($collect_date) && !empty($patientworkannex_id)){
                        $newWork['collect_date'] = $collect_date;
                        $newWork['change_type'] = 1;
                        $newWork['lock_state'] = 1;
                        $resultWork = $this->LocalService()->itemPatientworkannex->update($newWork,'is_del=0 and lock_state=0 and id in('.$patientworkannex_id.')');
                    }
                }
            }
        }
        if (!empty($arr)){
            $str = json_encode($arr);
            $result = $redis->set($keys,$str);

        }
        return true;

    }

    //内外锁定
    public function lockItemPatientWorkAndChange($smallItemId){
//        $smallItemId = '103';//【MSC-ESLD20211224】人间充质干细胞治疗重症肝病的临床研究（RCT-2.1）==103
        //时间条件
        $time = ' and FROM_UNIXTIME(up_annex_date ,"%Y-%m-%d")="2022-09-17"';
        $whereItemPatientworkannex['where'] =  'is_del=0 and item_id in(' . $smallItemId.')  and annex_type !=2  and lock_state=1'.$time;//annex_type !=3//只查手动写和图片上传的
        $whereItemPatientworkannex['group'] = ['checktime_id','patient_form_id','form_id'];
        $whereItemPatientworkannex['columns'] = ['id','checktime_id','patient_form_id','form_id','itemsig_id','patient_id'];
        $whereItemPatientworkannex['order'] = ['id desc'];
        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);

        if (!empty($itemPatientworkannexData)){
            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>$itemPatientworkannexDataValue) {
                $whereItemIdentificationresultchange['where'] = [
                    'is_del' => 0,
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                    'item_id' => $smallItemId,

                ];
                $whereItemIdentificationresultchange['columns'] =['id','collect_date','lock_state','patientworkannex_id','item_checkname_id','patient_id','itemsig_id'];
                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
                if (!empty($itemIdentificationresultchangeData)){
                    $itemChecknameId = array_column($itemIdentificationresultchangeData,'item_checkname_id');
                    $itemChecknameIdUniqueArr = array_unique($itemChecknameId);
                    if (count($itemChecknameIdUniqueArr) != count($itemChecknameId)){
                        continue;
                    }
                    $collect_date = 0;
                    $patientworkannex_id = '';
                    $changeIdS = implode(',',array_column($itemIdentificationresultchangeData,'id'));
                    $lockStateArr = array_column($itemIdentificationresultchangeData,'lock_state');
                    if (in_array(0,$lockStateArr) && in_array(1,$lockStateArr)){
                        continue;
                    }

//                    foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey=>$itemIdentificationresultchangeDataValue) {
////                        if (empty($itemIdentificationresultchangeDataValue['lock_state'])){
////                            $resultchange = $this->LocalService()->itemIdentificationresultchange->update(['lock_state'=>1,'lock_state_small'=>1],'id= '.$itemIdentificationresultchangeDataValue['id']);
////                        }
//                        if (!empty($itemIdentificationresultchangeDataValue['patientworkannex_id']) && !empty($itemIdentificationresultchangeDataValue['collect_date'])){
//                            $collect_date = $itemIdentificationresultchangeDataValue['collect_date'];
//                            $patientworkannex_id = $itemIdentificationresultchangeDataValue['patientworkannex_id'];
//                        }
//                        if (!empty($collect_date) && !empty($patientworkannex_id)) break;
//
//                    }
//                    if (!empty($collect_date) && !empty($patientworkannex_id)){
                    if (in_array(0,$lockStateArr) && !empty($changeIdS)){
                        $resultchange = $this->LocalService()->itemIdentificationresultchange->update(['lock_state'=>1,'lock_state_small'=>1],'id in('.$changeIdS.')');
                    }
//                        $newWork['collect_date'] = $collect_date;
//                        $newWork['change_type'] = 1;
//                        $newWork['lock_state'] = 1;
//                        $resultWork = $this->LocalService()->itemPatientworkannex->update($newWork,'is_del=0 and lock_state=0 and id in('.$patientworkannex_id.')');
//                    }
                }
            }
        }
        return true;
        echo '<pre>';print_r($itemPatientworkannexData);die;

    }

    /**
    结果
     */
    public function oldItemIdentificationResultChangeInsert($item_id = 83){

        $iteminfoId= $this->LocalService()->itemInfo->getOneFieldVal('id','is_del=0 and old_id='.$item_id);
        $iteminfoBigId= $this->LocalService()->itemInfo->getOneFieldVal('fid','is_del=0 and id='.$iteminfoId);

        //中心
        $whereItemSignatory['where'] = [
            'is_del' => 0,
            'item_id' => $iteminfoBigId,
        ];
        $whereItemSignatory['columns'] = ['id','old_id'];
        $itemSignatoryIdData = $this->LocalService()->itemSignatory->fetchAll($whereItemSignatory);

        $signtoryDatas = [];
        if (!empty($itemSignatoryIdData)){
            foreach($itemSignatoryIdData as $k=>$v)
            {
                $signtoryDatas[$v['old_id']] = $v;
            }
        }

        //区号
        $itemCsaeData = $this->LocalService()->patientattrs->dbData('oa_item_csae','is_del=0 and item_id in( '.$item_id.')');// and programme_id !=0

        $wherePatientworkannex['where'] = [
            'is_del' => 0,
            'item_id' => $item_id,
        ];
        $patientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($wherePatientworkannex);
        $patientworkannexDatas = [];
        if (!empty($patientworkannexData)){
            foreach ($patientworkannexData as $patientworkannexDataKey=>$patientworkannexDataValue) {
                $patientworkannexDatas[$patientworkannexDataValue['id_old']] = $patientworkannexDataValue;//id_old
            }
        }
        if(!empty($itemCsaeData)){
//            $patientworkannexIdArr = array_column($itemCsaeData,'file_id');
//            $patientworkannexIds = implode(',',$patientworkannexIdArr);

            //            echo '<pre>';print_r($randomdetailsData);die;
            foreach ($itemCsaeData as $itemCsaeDataKey=>$itemCsaeDataValue){
                if (!empty($itemCsaeDataValue['content'])){
                    $jsonDecodeContentData = json_decode($itemCsaeDataValue['content'],1);
                    $arr['item_id'] = $item_id;//$itemCsaeDataValue['item_id'];//$iteminfoId
                    $arr['itemsig_id'] = $itemCsaeDataValue['center_id'];//$iteminfoId;//
                    $arr['patientworkannex_id'] = $itemCsaeDataValue['file_id'];
                    $arr['patient_id'] = $itemCsaeDataValue['patient_id'];
                    $arr['collect_date'] = $itemCsaeDataValue['collect_date'];
                    $arr['ocr_id'] = $itemCsaeDataValue['itemocr_id'];
                    $arr['lock_state'] = $itemCsaeDataValue['is_lock'];
                    $arr['create_user_id'] = $arr['update_user_id'] = $itemCsaeDataValue['operation_user'];
                    $arr['update_time'] = $itemCsaeDataValue['operation_time'];
                    $arr['id_old'] = $old_id = $itemCsaeDataValue['id'];
//                    $arr['source'] = $itemCsaeDataValue['source'];//数据来源  0：后台管理系统、1：Real端、小程序


                    unset($itemCsaeDataValue['id']);
                    foreach ($jsonDecodeContentData as $jsonDecodeContentDataKey=>$jsonDecodeContentDataValue){
                        $arr['unit'] = $jsonDecodeContentDataValue['unit'];
                        $is_normal_type = 0;
                        if (isset($jsonDecodeContentDataValue['is_normal']) && $jsonDecodeContentDataValue['is_normal'] == 1){
                            $is_normal_type = 1;
                        }
                        if (isset($jsonDecodeContentDataValue['is_cs']) && $jsonDecodeContentDataValue['is_cs'] == 1){
                            $is_normal_type = 2;
                        }
                        if (isset($jsonDecodeContentDataValue['is_ae']) && $jsonDecodeContentDataValue['is_ae'] == 1){
                            $is_normal_type = 3;
                        }
                        if (isset($jsonDecodeContentDataValue['is_confirm'])){//小锁定
                            $arr['lock_state_small'] = $jsonDecodeContentDataValue['is_confirm'];//小锁定
                        }
                        if (isset($jsonDecodeContentDataValue['is_sure'])){//小锁定
                            $arr['is_sure'] = $jsonDecodeContentDataValue['is_sure'];//
                        }
                        $arr['is_normal_type'] = $is_normal_type;
                        $arr['result'] = $jsonDecodeContentDataValue['result'];
                        $arr['item_name'] = $jsonDecodeContentDataValue['item_name'];

                        $arr['reference_range_max'] = $jsonDecodeContentDataValue['reference_range_max'];
                        $arr['reference_range_min'] = $jsonDecodeContentDataValue['reference_range_min'];
                        $arr['flag_color'] = 1;
                        if(isset($patientworkannexDatas[$itemCsaeDataValue['file_id']])){

                            if (!empty($patientworkannexDatas[$itemCsaeDataValue['file_id']]['category_id'])){
                                $oldCategoryId = $patientworkannexDatas[$itemCsaeDataValue['file_id']]['category_id'];

                                //项目检查项名称设置表
                                $whereItemCheckname['where'] = [
                                    'is_del' => 0,
                                    'item_id' => $item_id,
                                    'category_id' => $oldCategoryId,
                                ];
                                $whereItemCheckname['columns'] = ['id','name','alias','checkname_id','unit','max_val','min_val','variable','check_type','min_range','max_range','min_symbol','max_symbol'];
                                $itemChecknameData = $this->LocalService()->itemCheckname->fetchAll($whereItemCheckname);
                                if (!empty($itemChecknameData) && !empty($arr['item_name'])){
                                    $arr['item_name'] = trim($arr['item_name']);
                                    foreach ($itemChecknameData as $itemChecknameDataKey=>$itemChecknameDataValue) {
                                        $olAlias = trim($itemChecknameDataValue['alias']);
                                        $olAliasArr = $olAlias?explode(',',$olAlias):[];
                                        if ($arr['item_name'] == trim($itemChecknameDataValue['name']) || in_array($arr['item_name'],$olAliasArr)){
                                            $arr['checkname_id']  = $itemChecknameDataValue['checkname_id'];
                                            $arr['item_min_val'] = $itemChecknameDataValue['min_val'];//最大值
                                            $arr['item_max_val'] = $itemChecknameDataValue['max_val'];//最小值
                                            $arr['item_unit'] = $itemChecknameDataValue['unit'];//单位
                                            $arr['min_symbol'] = $itemChecknameDataValue['min_symbol'];//最小值符号
                                            $arr['max_symbol'] = $itemChecknameDataValue['max_symbol'];//最大值符号
                                            $arr['check_type'] = $itemChecknameDataValue['check_type'];//检查值类型1整数2一位小数3两位小数4三位小数5文本
                                            $arr['item_checkname_id'] = $itemChecknameDataValue['id'];//指标id
                                            $arr['item_min_range'] = $itemChecknameDataValue['min_range'];//项目下限浮动值
                                            $arr['item_max_range'] = $itemChecknameDataValue['max_range'];//项目上限浮动值
                                            break;

                                        }
                                    }

                                }

                            }
//                        $arr['min_range'] = $jsonDecodeContentDataValue['min_range'];//下限
//                        $arr['max_range'] = $jsonDecodeContentDataValue['max_range'];//下限
//                        $arr['item_min_val'] = $jsonDecodeContentDataValue['reference_range_min'];//最大值
//                        $arr['item_max_val'] = $jsonDecodeContentDataValue['reference_range_max'];//最小值
//                        $arr['item_unit'] = $jsonDecodeContentDataValue['item_unit'];//单位
//                        $arr['min_symbol'] = $jsonDecodeContentDataValue['min_symbol'];//最小值符号
//                        $arr['max_symbol'] = $jsonDecodeContentDataValue['max_symbol'];//最大值符号
//                        $arr['item_result'] = $jsonDecodeContentDataValue['item_unit'];//项目里的结果(不展示)
//                        $arr['is_sure'] = $jsonDecodeContentDataValue['is_sure'];//
//                        $arr['check_type'] = $jsonDecodeContentDataValue['check_type'];//检查值类型1整数2一位小数3两位小数4三位小数5文本
//                        $arr['item_checkname_id'] = $jsonDecodeContentDataValue['item_checkname_id'];//指标id
//                        $arr['item_min_range'] = $jsonDecodeContentDataValue['item_min_range'];//项目下限浮动值
//                        $arr['item_max_range'] = $jsonDecodeContentDataValue['item_max_range'];项目上限浮动值
                        }

//                        $arr['checkname_id'] = $jsonDecodeContentDataValue['checkname_id'];//
//                        $arr['checkname_id'] = isset($patientworkannexDatas[$itemCsaeDataValue['file_id']]['checkname_id'])?$patientworkannexDatas[$itemCsaeDataValue['file_id']]['checkname_id']:0;
                        $arr['checktime_id'] = isset($patientworkannexDatas[$itemCsaeDataValue['file_id']]['checktime_id'])?$patientworkannexDatas[$itemCsaeDataValue['file_id']]['checktime_id']:0;
                        $arr['researchstage_id'] = isset($patientworkannexDatas[$itemCsaeDataValue['file_id']]['researchstage_id'])?$patientworkannexDatas[$itemCsaeDataValue['file_id']]['researchstage_id']:0;
                        $arr['form_id'] = isset($patientworkannexDatas[$itemCsaeDataValue['file_id']]['form_id'])?$patientworkannexDatas[$itemCsaeDataValue['file_id']]['form_id']:0;
                        $arr['category_id'] = isset($patientworkannexDatas[$itemCsaeDataValue['file_id']]['category_id'])?$patientworkannexDatas[$itemCsaeDataValue['file_id']]['category_id']:0;
                        $arr['annex_path'] = isset($patientworkannexDatas[$itemCsaeDataValue['file_id']]['annex_path'])?$this->ossPath.$patientworkannexDatas[$itemCsaeDataValue['file_id']]['annex_path']:'';
                        $arr['category_id'] = isset($patientworkannexDatas[$itemCsaeDataValue['file_id']]['category_id'])?$patientworkannexDatas[$itemCsaeDataValue['file_id']]['category_id']:0;
                        $arr['patient_form_id'] = isset($patientworkannexDatas[$itemCsaeDataValue['file_id']]['patient_form_id'])?$patientworkannexDatas[$itemCsaeDataValue['file_id']]['patient_form_id']:0;
                        $arr['annex_type'] = isset($patientworkannexDatas[$itemCsaeDataValue['file_id']]['annex_type'])?$patientworkannexDatas[$itemCsaeDataValue['file_id']]['annex_type']:0;
                        $arr['report_type'] = isset($patientworkannexDatas[$itemCsaeDataValue['file_id']]['report_type'])?$patientworkannexDatas[$itemCsaeDataValue['file_id']]['report_type']:0;
                        if (isset($patientworkannexDatas[$itemCsaeDataValue['file_id']])){
                            if ($patientworkannexDatas[$itemCsaeDataValue['file_id']]['annex_type'] == 3){
                                $itemPatientworkannexUP['ocr_state'] = 1;
                            }else{
                                $itemPatientworkannexUP['ocr_state'] =$patientworkannexDatas[$itemCsaeDataValue['file_id']]['ocr_state'];
                            }
                            $itemPatientworkannexUP['id'] = $itemCsaeDataValue['file_id'];
                            $itemPatientworkannexUP['is_result'] = 1;
                            $itemPatientworkannexUP['change_type'] = 1;
                            $itemPatientworkannexUP['lock_state'] = $itemCsaeDataValue['is_lock'];
                            $randnumberId = $this->LocalService()->itemPatientworkannex->save($itemPatientworkannexUP);

                        }

                        $changeId = $this->LocalService()->itemIdentificationresultchange->save($arr);
                    }
                }


            }

        }

        if(!empty($changeId)){
            echo '<span style="color：green">同步成功<span>'.'<br>';
        }else{
            echo '<span style="color：red">同步失败<span>'.'<br>';
        }
        die;

    }


    public function newItemIdentificationResultChangeWriteFileUPdate($where = []){
        $flag = 0;
        if(empty($where)){
            $redis = Laminas::$serviceManager->redisExtend->setDatabase(6)->getRedisInstance();
            $keys = 'asyncErr';
            $result = $redis->lPop($keys);
            $flag = 1;
            if (empty($result)){
                $flag = 2;
                return true;
            }
            $itemItemsigId = explode('-',$result);
            $where['item_id'] = $itemItemsigId[0];
            $where['itemsig_id'] = $itemItemsigId[1];
            $where['patient_id'] = $itemItemsigId[2];
            $where['patient_form_id'] = $itemItemsigId[3];
            $where['category_id'] = $itemItemsigId[4];
            $where['checktime_id'] = $itemItemsigId[5];
            $where['form_id'] = $itemItemsigId[6];
        }
        $itemItemsigPath = $where['item_id'].'/'.$where['itemsig_id'].'/';
        $whereItemIdentificationresultchange['where'] = [
            'is_del' => 0,
            'is_annul' => 0,
            'lock_state' => 1,
            'item_id' => $where['item_id'],
            'itemsig_id' => $where['itemsig_id'],
            'patient_id' => $where['patient_id'],
            'form_id' => $where['form_id'],
            'checktime_id' => $where['checktime_id'],
        ];
        $whereItemIdentificationresultchange['columns'] = ['id','item_name','checktime_id','category_id','form_id','checkname_id','item_name','result','unit','item_min_val'=>'reference_range_min','item_max_val'=>'reference_range_max','is_normal_type','collect_date','min_symbol','max_symbol'];
        $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
        $itemIdentificationresultchangeWriteFileData = [];
        if (!empty($itemIdentificationresultchangeData)){
            foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey=>$itemIdentificationresultchangeDataValue) {
                $itemIdentificationresultchangeWriteFileData[$itemIdentificationresultchangeDataValue['checktime_id']][$itemIdentificationresultchangeDataValue['form_id']][] = $itemIdentificationresultchangeDataValue;
            }
        }
        $itemIdentificationResultPath = $this->LocalService()->config['itemIdentificationResultPath'].$itemItemsigPath?:APP_PATH.'/data/itemIdentificationResultPath/'.$itemItemsigPath;

        if(!file_exists($itemIdentificationResultPath)){
            $resultPath = mkdir($itemIdentificationResultPath, 0777, true);
            if(!$resultPath){
                return false;
            }

        }
        $itemIdItemsigIdCategoryIdPath = $itemIdentificationResultPath.$where['item_id'].'-'.$where['itemsig_id'].'-'.$where['patient_id'].'.txt';

        $oldData = [];
        if (file_exists($itemIdItemsigIdCategoryIdPath)){
            $itemIdentificationresultchangeJson = file_get_contents( $itemIdItemsigIdCategoryIdPath);
            $oldData = json_decode($itemIdentificationresultchangeJson,true);

        }

        $checktime_id = $where['checktime_id'];
        $category_id = $where['form_id'];//$where['category_id'];
        if (!empty($itemIdentificationresultchangeWriteFileData)){
            $itemIdentificationresultchangeWriteFileDataStr = json_encode($itemIdentificationresultchangeWriteFileData);
            if (!empty($oldData)){

                $oldData[$checktime_id][$category_id] = $itemIdentificationresultchangeWriteFileData[$checktime_id][$category_id];
                $itemIdentificationresultchangeWriteFileDataStr = json_encode($oldData);

            }
            $result = file_put_contents( $itemIdItemsigIdCategoryIdPath, $itemIdentificationresultchangeWriteFileDataStr);
            if (empty($result)) return false;
        }else{
            if(!empty($oldData) && isset($oldData[$checktime_id][$category_id])){
                if (count($oldData[$checktime_id])>1){
                    unset($oldData[$checktime_id][$category_id]);
                }else{
                    unset($oldData[$checktime_id]);
                }
                $oldDataStr = json_encode($oldData);
                $result = file_put_contents( $itemIdItemsigIdCategoryIdPath, $oldDataStr);
                if (empty($result)) return false;
            }
        }
        if (!empty($result)){
            $asyncErr = $where['item_id'].'-'.$where['itemsig_id'].'-'.$where['patient_id'].'-'.$where['patient_form_id'].'-'.$where['category_id'].'-'.$where['checktime_id'].'-'.$where['form_id'];
            $asyncErr1 = $this->LocalService()->itemIdentificationresultchange->asyncErr($asyncErr,1);
        }
        return true;
    }


    public function itemIdentificationResultChangeWriteFile($item_id=0,$itemsig_id=0,$patient_id=0,$category_id=0,$checktime_id=0){
        $flag = 0;
        $redis = Laminas::$serviceManager->redisExtend->setDatabase(6)->getRedisInstance();
        $keys = 'itemIdItemsigIdData';
        $keyErr = 'itemIdItemsigIdDataErr';
        $keyNormalErr = 'itemIdItemsigIdDataNormalErr';
        if (empty($item_id) && empty($itemsig_id)  && empty($patient_id)){
            $result = $redis->lPop($keys);
            $flag = 1;
            if (empty($result)){
                $result = $redis->lPop($keyErr);
                $flag = 2;
                if (empty($result)){
                    $flag = 3;
                    return false;
                }
            }

            $itemItemsigId = explode('-',$result);
            $item_id = $itemItemsigId[0];
            $itemsig_id = $itemItemsigId[1];
            $patient_id = $itemItemsigId[2];
        }
        $whereItemIdentificationresultchange['where'] = [
            'is_del' => 0,
            'is_annul' => 0,
            'lock_state' => 1,
            'item_id' => $item_id,
            'itemsig_id' => $itemsig_id,
            'patient_id' => $patient_id,
        ];

        $whereItemIdentificationresultchange['columns'] = ['id','item_id','item_name','checktime_id','category_id','form_id','checkname_id','item_name','result','unit','item_min_val'=>'reference_range_min','item_max_val'=>'reference_range_max','is_normal_type','collect_date','min_symbol','max_symbol'];
//        $whereItemIdentificationresultchange['columns'] = ['id','item_name','checktime_id','category_id','checkname_id','item_name','result','unit','item_min_val','item_max_val','is_normal_type','collect_date','min_symbol','max_symbol'];
//        $whereItemIdentificationresultchange['columns'] = ['id','patient_id','checktime_id','category_id','item_name','checkname_id','item_name','result','unit','item_min_val','item_max_val','is_normal_type'];
        $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);

        $itemIdentificationresultchangeWriteFileData = [];
        if (!empty($itemIdentificationresultchangeData)){
            foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey=>$itemIdentificationresultchangeDataValue) {
//                $itemIdentificationresultchangeWriteFileData[$itemIdentificationresultchangeDataValue['patient_id']][$itemIdentificationresultchangeDataValue['checktime_id']][] = $itemIdentificationresultchangeDataValue;
//                $itemIdentificationresultchangeWriteFileData[$itemIdentificationresultchangeDataValue['checktime_id']][$itemIdentificationresultchangeDataValue['category_id']][] = $itemIdentificationresultchangeDataValue;
                $itemIdentificationresultchangeWriteFileData[$itemIdentificationresultchangeDataValue['checktime_id']][$itemIdentificationresultchangeDataValue['form_id']][] = $itemIdentificationresultchangeDataValue;
            }
        }
        $itemItemsigPath = $item_id.'/'.$itemsig_id.'/';
        $itemIdentificationResultPath = $this->LocalService()->config['itemIdentificationResultPath'].$itemItemsigPath?:APP_PATH.'/data/itemIdentificationResultPath/'.$itemItemsigPath;
        if(!file_exists($itemIdentificationResultPath)){
            $resultPath = mkdir($itemIdentificationResultPath, 0777, true);
            if(!$resultPath){
                $str =  $item_id.'-'.$itemsig_id.'-'.$patient_id;
                $result = $redis->rPush($keys,$str);
//                $result = $this->setItemItemsigId($item_id,$itemsig_id,$patient_id);
            }

        }

        if (!empty($itemIdentificationresultchangeWriteFileData)){
            $itemIdentificationresultchangeWriteFileDataStr = json_encode($itemIdentificationresultchangeWriteFileData);
            $result = file_put_contents( $itemIdentificationResultPath.$item_id.'-'.$itemsig_id.'-'.$patient_id.'.txt', $itemIdentificationresultchangeWriteFileDataStr);
            if (empty($result)){
                $str =  $item_id.'-'.$itemsig_id.'-'.$patient_id;
                if ($flag == 0 ){
                    $result = $redis->rPush($keyNormalErr,$str);
                }else if ($flag == 1 ){
                    $result = $redis->rPush($keyErr,$str);
                }else if ($flag == 2 ){
                    $keyErrPath = $this->LocalService()->config['itemIdentificationResultPath'].$keyErr.'/';
                    if(!file_exists($keyErrPath)){
                        $resultPath = mkdir($keyErrPath, 0777, true);
                    }
                    $errArr['item_id'] =  $item_id;
                    $errArr['itemsig_id'] =  $itemsig_id;
                    $errArr['patient_id'] =  $patient_id;
                    $errArr['change'] =  $itemIdentificationresultchangeWriteFileData;
                    $content = json_encode($errArr);
//                    $content = var_export($errArr, true);
                    $result =  file_put_contents($keyErrPath . $item_id.'-'.$itemsig_id.'-'.$patient_id. '.log', $content . PHP_EOL . PHP_EOL, FILE_APPEND|LOCK_EX);
                }
            }
//            if (empty($result)){
//                $str =  $item_id.'-'.$itemsig_id.'-'.$patient_id;
//                $result = $redis->rPush($keys,$str);
////                $result = $this->setItemItemsigId($item_id,$itemsig_id,$patient_id);
//            }
        }
//        echo '<pre>';print_r($result).PHP_EOL;
        return $result;
    }
    public function setItemItemsigIdData($type = 0){
        $redis = Laminas::$serviceManager->redisExtend->setDatabase(6)->getRedisInstance();
        $keys = 'itemIdItemsigIdData';
        $itemDoctorideaKey = 'itemDoctorideaKey';//医嘱
        $itemDoctorideaKeyErr = 'itemIdItemsigIdDataErr';//医嘱错误key
        $itemDoctorideaKeyErrs = 'itemIdItemsigIdDataStr';//医嘱错误key
        $iteminfoIdArr = $this->LocalService()->itemInfo->fetchCol('id','is_del=0 and is_mainitem=1');
        $iteminfoIdSmallArr = [];
        $item = [];
        if (!empty($iteminfoIdArr)){
            $ids = implode(',',$iteminfoIdArr);

            $whereItemInfo['where'] = [
                'is_del' => 0,
                'fid' => $iteminfoIdArr
            ];
            $whereItemInfo['columns'] = ['id','name','fid'];
            $iteminfoIdSmallArr = $this->LocalService()->itemInfo->fetchAll($whereItemInfo);
            if (!empty($iteminfoIdSmallArr)){
                foreach ($iteminfoIdSmallArr as $iteminfoIdSmallArrKey=>&$iteminfoIdSmallArrValue){
                    $itemSignatoryIdArr = $this->LocalService()->itemSignatory->fetchCol('id','is_del=0 and item_id ='.$iteminfoIdSmallArrValue['fid']);
                    if (!empty($itemSignatoryIdArr)){
                        foreach ($itemSignatoryIdArr as $itemSignatoryId) {
                            if (empty($type)){
                                $patientIdData = $this->LocalService()->itemIdentificationresultchange->fetchCol('patient_id',['is_del'=>0,'is_annul'=>0,'lock_state'=>1,'item_id'=>$iteminfoIdSmallArrValue['id'],'itemsig_id'=>$itemSignatoryId]);
                            }else{
                                $patientIdData = $this->LocalService()->itemDoctoridea->fetchCol('patient_id','is_del=0 and lock_state = 1 and item_id='.$iteminfoIdSmallArrValue['id'].' and itemsig_id='.$itemSignatoryId);
                            }
                            $categoryIds = '';
                            $newCategoryIdData= [];
                            if (!empty($patientIdData)){
                                $newCategoryIdData = array_filter(array_unique($patientIdData));
                                $categoryIds = trim(implode(',',array_filter(array_unique($patientIdData))),',');
                            }
                            $iteminfoIdSmallArrValue['itemsig_id'] = $itemSignatoryId;
                            $iteminfoIdSmallArrValue['category_id'] = $categoryIds;
                            if (!empty($iteminfoIdSmallArrValue['id']) || !empty($itemSignatoryId) || !empty($categoryIds) || !empty($newCategoryIdData)){
                                foreach ($newCategoryIdData as $newCategoryIdDataKey=>$newCategoryIdDataValue) {
                                    $str =  $iteminfoIdSmallArrValue['id'].'-'.$itemSignatoryId.'-'.$newCategoryIdDataValue;
                                    $item[] = $str;
                                    if (empty($type)){
                                        $result = $redis->rPush($keys,$str);
                                        if (empty($result)){
                                            $redis->rPush('itemIdItemsigIdDataErr',$str);
                                        }
                                    }else{
                                        $result = $redis->rPush($itemDoctorideaKey,$str);
                                        if (empty($result)){
                                            $redis->rPush($itemDoctorideaKeyErr,$str);
                                        }
                                    }

                                }

                            }
                        }
                    }
                }
                if(!empty($item)){
                    if (empty($type)){
                        $redis->set('itemIdItemsigIdDataStr',json_encode($item));
                    }else{
                        $redis->set($itemDoctorideaKeyErrs,json_encode($item));
                    }

                }
            }
        }

        return true;
        echo '<pre>';print_r($item);die;
        echo '<pre>';print_r($iteminfoIdSmallArr);die;
    }

    public function asyncErr($str='',$type=0,$keys = 'asyncErr'){
        if (empty($str) && $type != 0){
            return true;
        }
        $redis = Laminas::$serviceManager->redisExtend->setDatabase(6)->getRedisInstance();
//        $keys = 'asyncErr';
        if ($type == 1){
            $result = $redis->lrem($keys,$str);
        }else{
            $result = $redis->rPush($keys,$str);
        }
        return true;
    }

    public function doctorIdeaWriteFile($where = [],$typeUpdate = 0){
        $keys = 'itemDoctorideaKey';
        $keyErr = 'asyncDoctorideaErr';
        $keyErrs = 'doctorideaErr';
        $flag = 0;
        if(!empty($typeUpdate)){
            if (empty($where)){
                $result = $this->redisObj->lPop($keys);
                $flag = 1;
                if (empty($result)){
                    $result = $this->redisObj->lPop($keyErrs);
                    $flag = 2;
                    if (empty($result)){
                        $flag = 3;
                        return false;
                    }
                }

                $itemItemsigId = explode('-',$result);
                $where['item_id'] = $itemItemsigId[0];
                $where['itemsig_id'] = $itemItemsigId[1];
                $where['patient_id'] = $itemItemsigId[2];

            }
            $where['keys'] = $keys;
            $whereItemDoctoridea = [
                'where'=>'is_del=0 and lock_state = 1 and item_id='.$where['item_id'].' and itemsig_id='.$where['itemsig_id'].' and patient_id='.$where['patient_id'],
                'columns' => ['id','checktime_id','category_id','form_id','result','stop_nurse_name','start_nurse_name','stop_doctor_name','start_doctor_name','stop_time','start_time','collect_date'],
            ];
            $itemDoctoridea = $this->LocalService()->itemDoctoridea->fetchAll($whereItemDoctoridea);
            $itemDoctorideaWriteFileData = [];
            if (!empty($itemDoctoridea)){
                foreach ($itemDoctoridea as $itemDoctorideaKey=>$itemDoctorideaValue) {
                    $itemDoctorideaWriteFileData[$itemDoctorideaValue['checktime_id']][$itemDoctorideaValue['form_id']][] = $itemDoctorideaValue;
                }
            }
            $where['str'] =  $where['item_id'].'-'.$where['itemsig_id'].'-'.$where['patient_id'].'-8';
            $itemIdentificationResultPath = $this->getWriteFilePath($where);
            if (!empty($itemDoctorideaWriteFileData)){
                $itemDoctorideaWriteFileDataStr = json_encode($itemDoctorideaWriteFileData);
                $result = file_put_contents( $itemIdentificationResultPath.$where['str'].'.txt', $itemDoctorideaWriteFileDataStr);
                if (empty($result)){
                    if ($flag == 0 ){
                        $result = $this->redisObj->rPush($keyErrs,$where['str']);
                    }else if ($flag == 1 ){
                        $result = $this->redisObj->rPush($keyErrs,$where['str']);
                    }else if ($flag == 2 ){
                        $keyErrPath = $this->LocalService()->config['itemIdentificationResultPath'].$keyErr.'/';
                        if(!file_exists($keyErrPath)){
                            $resultPath = mkdir($keyErrPath, 0777, true);
                        }
                        $errArr =  $where;
                        $errArr['change'] =  $itemDoctorideaWriteFileData;
                        $content = json_encode($errArr);
//                    $content = var_export($errArr, true);
                        $result =  file_put_contents($keyErrPath . $where['str']. '.log', $content . PHP_EOL . PHP_EOL, FILE_APPEND|LOCK_EX);
                    }
                }

            }
            if (!empty($result)) return true;

            return false;

        }else{
            $flag = 0;
            if(empty($where)){
                $where['keys'] = $keyErr;
                $result = $this->redisObj->lPop($keyErr);
                $flag = 1;
                if (empty($result)){
                    $flag = 2;
                    return true;
                }
                $itemItemsigId = explode('-',$result);
                $where['item_id'] = $itemItemsigId[0];
                $where['itemsig_id'] = $itemItemsigId[1];
                $where['patient_id'] = $itemItemsigId[2];
                $where['patient_form_id'] = $itemItemsigId[3];
                $where['category_id'] = $itemItemsigId[4];
                $where['checktime_id'] = $itemItemsigId[5];
                $where['form_id'] = $itemItemsigId[6];
            }

            $itemItemsigPath = $where['item_id'].'/'.$where['itemsig_id'].'/';
            $whereItemDoctoridea = [
                'where' => 'is_del=0 and lock_state = 1 and item_id='.$where['item_id'].' and itemsig_id='.$where['itemsig_id'].' and patient_id='.$where['patient_id'].' and form_id='.$where['form_id'].' and checktime_id='.$where['checktime_id'],
                'columns' => ['id','checktime_id','category_id','form_id','result','stop_nurse_name','start_nurse_name','stop_doctor_name','start_doctor_name','stop_time','start_time','collect_date'],
            ];
            $itemDoctoridea = $this->LocalService()->itemDoctoridea->fetchAll($whereItemDoctoridea);
            $itemDoctorideaWriteFileData = [];
            if (!empty($itemDoctoridea)){
                foreach ($itemDoctoridea as $itemDoctorideaKey=>$itemDoctorideaValue) {
                    $itemDoctorideaWriteFileData[$itemDoctorideaValue['checktime_id']][$itemDoctorideaValue['form_id']][] = $itemDoctorideaValue;
                }
            }
            $where['str'] =  $where['item_id'].'-'.$where['itemsig_id'].'-'.$where['patient_id'].'-8';
            $itemIdentificationResultPath = $this->getWriteFilePath($where);
            $itemIdItemsigIdCategoryIdPath = $itemIdentificationResultPath.$where['str'].'.txt';

            $oldData = [];
            if (file_exists($itemIdItemsigIdCategoryIdPath)){
                $itemIdentificationresultchangeJson = file_get_contents( $itemIdItemsigIdCategoryIdPath);
                $oldData = json_decode($itemIdentificationresultchangeJson,true);

            }

            $checktime_id = $where['checktime_id'];
            $category_id = $where['form_id'];
            if (!empty($itemDoctorideaWriteFileData)){
                $itemDoctorideaWriteFileDataStr = json_encode($itemDoctorideaWriteFileData);
                if (!empty($oldData)){
                    $oldData[$checktime_id][$category_id] = $itemDoctorideaWriteFileData[$checktime_id][$category_id];
                    $itemDoctorideaWriteFileDataStr = json_encode($oldData);

                }
                $result = file_put_contents( $itemIdItemsigIdCategoryIdPath, $itemDoctorideaWriteFileDataStr);
                if (empty($result)) return false;
            }else{
                if(!empty($oldData) && isset($oldData[$checktime_id][$category_id])){
                    if (count($oldData[$checktime_id])>1){
                        unset($oldData[$checktime_id][$category_id]);
                    }else{
                        unset($oldData[$checktime_id]);
                    }
                    $oldDataStr = json_encode($oldData);
                    $result = file_put_contents( $itemIdItemsigIdCategoryIdPath, $oldDataStr);
                    if (empty($result)) return false;
                }
            }
            if (!empty($result)){
                $asyncErr = $where['item_id'].'-'.$where['itemsig_id'].'-'.$where['patient_id'].'-'.$where['patient_form_id'].'-'.$where['category_id'].'-'.$where['checktime_id'].'-'.$where['form_id'];
                $asyncErr1 = $this->LocalService()->itemIdentificationresultchange->asyncErr($asyncErr,1,$where['keys']);
            }
            return true;


        }
    }

    public function getWriteFilePath($where = []){
        $itemItemsigPath = $where['item_id'].'/'.$where['itemsig_id'].'/';
        $itemIdentificationResultPath = $this->LocalService()->config['itemIdentificationResultPath'].$itemItemsigPath?:APP_PATH.'/data/itemIdentificationResultPath/'.$itemItemsigPath;
        if(!file_exists($itemIdentificationResultPath)){
            $resultPath = mkdir($itemIdentificationResultPath, 0777, true);
            if(!$resultPath){
                $result = $this->redisObj->rPush($where['keys'],$where['str']);
            }

        }
        return $itemIdentificationResultPath;

    }


//    //gi et
//    public function setItemItemsigId($item_id,$itemsig_id,$patient_id)
//    {
//        $redis = Laminas::$serviceManager->redisExtend->setDatabase(13)->getRedisInstance();
//        $data = [];
//        $keys = 'identificationResult';
//        $oldArr = $redis->get($keys);
//        if (!empty($oldArr)) $data = json_decode($oldArr,1);
//        array_push($data,['item_id'=>$item_id,'itemsig_id'=>$itemsig_id,'itemsig_id'=>$patient_id]);
//        $arr = json_encode($data);
//        $result = $redis->set($keys,$arr);
//        return $result;
//    }
//    public function getItemItemsigId()
//    {
//        $redis = Laminas::$serviceManager->redisExtend->setDatabase(13)->getRedisInstance();
//        $keys = 'itemIdItemsigIdData';
//        $result = $redis->rPop($keys);
//        if (empty($result)){
//            return false;
//        }
//
//        $itemItemsigId = explode('-',$result);
//        $item_id = $itemItemsigId[0];
//        $itemsig_id = $itemItemsigId[1];
//        $patient_id = $itemItemsigId[2];
//        $changeResult = $this->LocalService()->itemIdentificationresultchange->itemIdentificationResultChangeWriteFile($item_id,$itemsig_id,$patient_id);
//        if (empty($changeResult)){
//            $str =  $item_id.'-'.$itemsig_id.'-'.$patient_id;
//            $result = $redis->rPush($keys,$str);
//        }
//        return true;

//    }




    public function changLockData($item_id =0,$itemsig_id =0 ,$patient_id =0,$checktime_id =0,$category_id = 0){
//        指标变量名,结果,单位,正常值下限,正常值上限,临床意义评价  【cs状态】,受试者,中心,项目,检查点,化验单变量名
        $item_id = 102;
        $itemsig_id = 320;
        $patient_id = 498;
        $checktime_id = 438;
        $whereItemIdentificationresultchange['where'] = [
            'is_del' => 0,
            'lock_state' => 1,
            'item_id' => $item_id,
            'itemsig_id' => $itemsig_id,
            'patient_id' => $patient_id,
            'checktime_id' => $checktime_id,
        ];
        $whereItemIdentificationresultchange['columns'] = ['id','item_id','is_normal_type','result','item_name','reference_range_max','reference_range_min','unit','item_unit','item_variable','patient_id','checktime_id','itemsig_id','category_id','patient_form_id','item_checkname_id'];
        $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
        if (!empty($itemIdentificationresultchangeData)){
            $patientIdS = implode(',',array_filter(array_unique( array_column($itemIdentificationresultchangeData, 'patient_id'))));
            $categoryIdS = implode(',',array_filter(array_unique( array_column($itemIdentificationresultchangeData, 'category_id'))));
            $itemIdS = implode(',',array_filter(array_unique( array_column($itemIdentificationresultchangeData, 'item_id'))));
            $checktimeIdS = implode(',',array_filter(array_unique( array_column($itemIdentificationresultchangeData, 'checktime_id'))));
            $itemsigIdS = implode(',',array_filter(array_unique( array_column($itemIdentificationresultchangeData, 'itemsig_id'))));
            $itemChecknameIdS = implode(',',array_filter(array_unique( array_column($itemIdentificationresultchangeData, 'item_checkname_id'))));
            if (!empty($itemsigIdS)){
                $whereItemSignatory['where'] = [
                    'is_del' => 0,
                    'id' => explode(',', $itemsigIdS)
                ];
                $whereItemSignatory['columns'] = ['id', 'signatory_id'];
                $itemSignatoryData = $this->LocalService()->itemSignatory->fetchAll($whereItemSignatory);
                if (!empty($itemSignatoryData)){
                    foreach ($itemSignatoryData as $itemSignatoryDataKey=>$itemSignatoryDataValue) {
                        $itemSignatoryDatas[$itemSignatoryDataValue['id']] = $itemSignatoryDataValue;
                    }
                    $signatoryIdS = implode(',',array_filter(array_unique( array_column($itemSignatoryData, 'signatory_id'))));
                    if (!empty($signatoryIdS)){
                        $itemSignInfoNameArr = $this->LocalService()->signatoryInfo->fetchCol('info_name',"is_del=0 and id in(" . $signatoryIdS . ")");
                        foreach ($itemSignatoryDatas as $itemSignatoryDatasKey=>&$itemSignatoryDatasValue) {
                            $itemSignatoryDatasValue['info_name'] = isset($itemSignInfoNameArr[$itemSignatoryDatasValue['signatory_id']]) ? $itemSignInfoNameArr[$itemSignatoryDatasValue['signatory_id']]:'';
                        }
                    }
                }


            }
            //受试者
            !empty($patientIdS) && $patientNameArr = $this->LocalService()->patient->fetchCol('patient_name','is_del=0 and id in('.$patientIdS.')');
            //分类变量名称
            !empty($categoryIdS) && $itemChecknameCategoryArr = $this->LocalService()->dictionaryCheckcategory->fetchCol('category_variable', 'is_del=0 and id in('.$categoryIdS.')');
            //项目名称
            !empty($itemIdS) && $itemInfoNameArr = $this->LocalService()->itemInfo->fetchCol('name','is_del=0 and id in('.$itemIdS.')');
            //检查点名称
            !empty($checktimeIdS) && $itemChecktimeNameArr = $this->LocalService()->itemChecktime->fetchCol('check_name','is_del=0 and id in('.$checktimeIdS.')');
            //项目检查项名称设置表
            !empty($itemChecknameIdS) && $itemChecknameArr = $this->LocalService()->itemCheckname->fetchCol('variable','is_del=0 and id in('.$itemChecknameIdS.')');

        }
        $isNormalTypeArr = ['','正常','cs','ncs'];
        if (!empty($itemIdentificationresultchangeData)){
            foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey => &$itemIdentificationresultchangeDataValue) {
                $itemIdentificationresultchangeDataValue['is_normal_type'] = $isNormalTypeArr[$itemIdentificationresultchangeDataValue['is_normal_type']];
                $itemIdentificationresultchangeDataValue['patient_name'] = isset($patientNameArr[$itemIdentificationresultchangeDataValue['patient_id']]) ? $patientNameArr[$itemIdentificationresultchangeDataValue['patient_id']]:'';
                $itemIdentificationresultchangeDataValue['category_variable'] = isset($itemChecknameCategoryArr[$itemIdentificationresultchangeDataValue['category_id']]) ? $itemChecknameCategoryArr[$itemIdentificationresultchangeDataValue['category_id']]:'';
                $itemIdentificationresultchangeDataValue['item_info_name'] = isset($itemInfoNameArr[$itemIdentificationresultchangeDataValue['item_id']]) ? $itemInfoNameArr[$itemIdentificationresultchangeDataValue['item_id']]:'';
                $itemIdentificationresultchangeDataValue['check_name'] = isset($itemChecktimeNameArr[$itemIdentificationresultchangeDataValue['checktime_id']]) ? $itemChecktimeNameArr[$itemIdentificationresultchangeDataValue['checktime_id']]:'';
                $itemIdentificationresultchangeDataValue['itemsig_info_name'] = isset($itemSignatoryDatas[$itemIdentificationresultchangeDataValue['itemsig_id']]['info_name']) ? $itemSignatoryDatas[$itemIdentificationresultchangeDataValue['itemsig_id']]['info_name']:'';
                $itemIdentificationresultchangeDataValue['item_variable'] = isset($itemChecknameArr[$itemIdentificationresultchangeDataValue['item_checkname_id']]) ? $itemChecknameArr[$itemIdentificationresultchangeDataValue['item_checkname_id']]:'';
            }
        }
        echo '<pre>';print_r($itemIdentificationresultchangeData);die;
        return $itemIdentificationresultchangeData;
    }

    //跟据类型改变结果值
    public function resultCheckType($result,$checkType){
        switch ($checkType){
            case 1:
                $result = intval($result);
                break;
            case 2:
                $resultArr = explode('.',$result);
                if (count($resultArr) > 1){
                    if (strlen($resultArr[1]) < 2){
                        $intNum = strlen($resultArr[0])+2;
                        $result = str_pad($result, $intNum, 0);
                    }
                }else{
                    $result = $result.'.0';
                }
                break;
            case 3:
                $resultArr = explode('.',$result);
                if (count($resultArr) >1){
                    if (strlen($resultArr[1]) < 2){
                        $intNum = strlen($resultArr[0])+3;
                        $result = str_pad($result, $intNum, 0);
                    }
                }else{
                    $result = $result.'.00';
                }
                break;
            case 4:
                $resultArr = explode('.',$result);
                if (count($resultArr) >1){
                    if (strlen($resultArr[1]) < 3){
                        $intNum = strlen($resultArr[0])+4;
                        $result = str_pad($result, $intNum, 0);
                    }
                }else{
                    $result = $result.'.000';
                }
                break;
        }
        return $result;

    }


    //cs ncs
    //$result结果  $minRange上限  $maxRange下限  $min最小值 $max最大值 $minType大于等于  $maxType小于等于
    public function isNormalType($result,$minRange,$maxRange,$min,$max,$minType,$maxType){
        $isNormalType = 0;
        if (empty($minType)){
            $minType = '≥';
        }
        if (empty($maxType)){
            $maxType = '≤';
        }
        if($minType != '' && $minType == '>'){
            $contrastResultMin = $result > $min;
        }
        if($minType != '' && $minType == '≥'){//≥
            $contrastResultMin = $result >= $min;
        }

        if($maxType != '' && $maxType == '<'){
            $contrastResultMax = $result < $max;
        }
        if($maxType != '' && $maxType == '≤'){//≤
            $contrastResultMax = $result <= $max;
        }
        //上下值
        if (!empty($minRange) || !empty($maxRange)){

            //判断上下都有
            if(!empty($minRange) && !empty($maxRange)){

                if (($contrastResultMin) && ($contrastResultMax)){
                    //在最小值与最大值之间的
                    //正常
                    $isNormalType = 1;
                }else{
                    if (($minRange <= $result) && ($result <= $maxRange)){
                        //在上下之间的为NCS
                        $isNormalType = 3;
                    }else{
                        //小于或大于上下限时为cs
                        $isNormalType = 2;
                    }

                }

            }else{
                //有下限的
                if($minRange){
                    if ($contrastResultMin){
                        //正常===大于等于下限的
                        $isNormalType = 1;
                    }else{
                        if ($minRange <= $result){
                            //在上下之间的为NCS
                            $isNormalType = 3;
                        }else{
                            //小于或大于上下限时为cs
                            $isNormalType = 2;
                        }

                    }

                }
                //有上限的
                if($maxRange){
                    if ($contrastResultMax){
                        //正常===小于等于上限的
                        $isNormalType = 1;
                    }else{
                        if ($result <= $maxRange){
                            //在上下之间的为NCS
                            $isNormalType = 3;
                        }else{
                            //小于或大于上下限时为cs
                            $isNormalType = 2;
                        }
                    }
                }
            }

        }else{
            //没有上限与下限时只判断正常，其它不判断
//
            //最大值最小值
            if(!empty($min) && !empty($max)){
                if(($contrastResultMin) && ($contrastResultMax) ){
                    //正常
                    $isNormalType = 1;
                }
            }
        }
        return $isNormalType;
    }

    //补属性id
    public function patientattrUpdate(){
        $item_id = 107;
        $wherePatientattrs['where'] = [
            'is_del' => 0,
            'item_id' => $item_id
        ];
        $patientattrsData = $this->LocalService()->patientattrs->fetchCol('attr_field',$wherePatientattrs['where']);

        $wherePatient['where'] = [
            'is_del' => 0,
            'item_id' => $item_id
        ];
        $patientData = $this->LocalService()->patient->fetchAll($wherePatient);
        if (!empty($patientattrsData) && !empty($patientData)){
            $newPatientattrsData = array_flip($patientattrsData);
            foreach ($patientData as $patientDataKey=>$patientDataVaule) {
                $patient_number = '';
                if (!empty($patientDataVaule['patient_content'])){
                    $patientContent = json_decode($patientDataVaule['patient_content'],1);
                    if (is_array($patientContent) && !empty($patientContent)){
                        foreach ($patientContent as $patientContentKey=>&$patientContentVaule){
                            if ($patientContentVaule['field']=='number'){
                                $patient_number = $patientContentVaule['value']?:'';
                            }
                            if ($patientContentVaule['field']=='randgroup_id'){
                                unset($patientContent[$patientContentKey]);
                            }
                            $patientContentVaule['id'] = isset($newPatientattrsData[$patientContentVaule['field']])?$newPatientattrsData[$patientContentVaule['field']]:0;
                        }
                        $patientContent = array_merge($patientContent);
                        $newPatientContent = json_encode($patientContent);
                        $up['patient_content'] = $newPatientContent;
                        $up['id'] = $patientDataVaule['id'];
                        $result = $this->LocalService()->patient->save($up);
                    }
                }
                $upNumber['patient_number'] = $patient_number;
                $upNumber['patient_number'] = $patientDataVaule['id'];
                $result1 = $this->LocalService()->patient->save($upNumber);

            }
        }
        return true;
    }



    public function delChangeCSCheckNameData($useData=[]){
        if(empty($useData)){
            echo '参数为空';die;
        }
        $item_id = $useData['item_id'];
        $form_id = $useData['form_id'];
        $oldCategory_id = $useData['oldCategory_id'];
        $oldCheckName = $useData['oldCheckName'];
        $newCheckName = $useData['newCheckName'];
        $newCategoryId = $useData['newCategoryId'];
        $newCheckId = $useData['newCheckId'];

        $where = '';//!=2
        $itemFormNameArr = $this->LocalService()->itemForm->fetchCol('name','is_del=0 and item_id in('.$item_id.')');
        $wherePatientArr['where'] = [
            'is_del' => 0,
            'item_id' => explode(',', (string)$item_id)
        ];
        $wherePatientArr['columns'] = ['id','patient_name','patient_number'];
        $patientData = $this->LocalService()->patient->fetchAll($wherePatientArr);//$item_id
        $patientNameArr = [];
        if(!empty($patientData)){
            foreach ($patientData as $patientDataKey=>$patientDataValue) {
                $patientNameArr[$patientDataValue['id']] = $patientDataValue;
            }
        }

        $whereItemPatientworkannex['where'] =  'is_del=0  and lock_state = 1 and item_id =' . $item_id.'  and annex_type !=2 and form_id='.$form_id.' and category_id='.$oldCategory_id.$where;
//        $whereItemPatientworkannex['group'] = ['checktime_id','patient_form_id','form_id'];
        $whereItemPatientworkannex['columns'] = ['id','checktime_id','patient_form_id','form_id','itemsig_id','patient_id','category_id','update_user_id','update_time'];
        $whereItemPatientworkannex['order'] = ['id desc'];
        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);
        $itemCsaeIdArr = [];
        if (!empty($itemPatientworkannexData)){
            $redisKey = 'itemworkChangeCheckname-'.$item_id.'-'.$form_id;
            $redisKeyData = 'itemworkChangeChecknameData-'.$item_id.'-'.$form_id;
            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>&$itemPatientworkannexDataValue) {
                $key = $item_id.'-'.$itemPatientworkannexDataValue['checktime_id'] . '-' . $itemPatientworkannexDataValue['patient_form_id'];//. '-' .$itemPatientworkannexDataValue['id'];

                $whereItemIdentificationresultchange['where'] = [
                    'is_del' => 0,
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                    'item_id' => $item_id
                ];
                $whereItemIdentificationresultchange['columns'] = ['id','item_checkname_id','item_name','category_id','report_type','is_normal_type','result'];
                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
                $itemPatientworkannexDataValue['change'] = $itemIdentificationresultchangeData;
                if (!empty($patientNameArr) && isset($patientNameArr[$itemPatientworkannexDataValue['patient_id']]) ){
                    $patient_name = $patientNameArr[$itemPatientworkannexDataValue['patient_id']]['patient_name'];
                    $patient_number = $patientNameArr[$itemPatientworkannexDataValue['patient_id']]['patient_number'];
                    $patientNameNumber = '';
                    if (!empty($patient_number)) $patientNameNumber = '【'.$patient_number.'】';
                    if (!empty($patient_name)) $patientNameNumber .= $patient_name;
                    $itemPatientworkannexDataValue['patient_name'] = $patientNameNumber;
                }
                if (!empty($itemFormNameArr) && isset($itemFormNameArr[$itemPatientworkannexDataValue['form_id']]) ){
                    $itemPatientworkannexDataValue['form_name'] = $itemFormNameArr[$itemPatientworkannexDataValue['form_id']];
                }

                $flag = 0;
                if (!empty($itemIdentificationresultchangeData)) {
                    $changeIdArr = array_column($itemIdentificationresultchangeData,'id');
                    $patient_change_id = implode(', ', $changeIdArr);
                    if(!empty($patient_change_id)){
                        $whereItemCsae['where'] = [
                            'is_del' => 0,
                            'is_ae_sure' => 1,
                            'patient_change_id' => $changeIdArr,
                        ];

                        $itemCsaeData = $this->LocalService()->itemCsae->fetchCol('patient_change_id',$whereItemCsae['where']);
                        $delChangeIds = '';
                        $csChangeId = 0;
                        $csChangeIdFlag = 0;
                        if(!empty($itemCsaeData)){
                            if(count($itemCsaeData) == 1){
                                $flag = 1;
                            }else if(count($itemCsaeData) > 1){
                                $flag = 2;
                                $itemCsaeIdArr[$key] = $itemCsaeData;
                            }

                            if($flag == 1){
                                foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey=>$itemIdentificationresultchangeDataValue) {
                                    if(in_array($itemIdentificationresultchangeDataValue['id'],$itemCsaeData)){
                                        if (empty($csChangeIdFlag)) {
                                            if (in_array($itemIdentificationresultchangeDataValue['item_name'],[$oldCheckName,$newCheckName])){
                                                $csChangeId = $itemIdentificationresultchangeDataValue['id'];
                                                $csChangeIdFlag = 1;
                                            }
                                            empty($csChangeIdFlag) && $csChangeId = $itemIdentificationresultchangeDataValue['id'];
                                        }
                                    }else{
                                        $delChangeIds .= $itemIdentificationresultchangeDataValue['id'].',';
                                    }
                                }

                                if (!empty($csChangeId)){
                                    $upChange['item_checkname_id'] = $newCheckId;
                                    $upChange['item_name'] = $newCheckName;
                                    $upChange['category_id'] = $newCategoryId;
                                    $upChange['checkname_id'] = $useData['checkname_id'];
                                    $upChange['lock_state'] = 1;
//                                    $upChange['report_type'] = 1;
                                    $resultChange = $this->LocalService()->itemIdentificationresultchange->update($upChange,'id='.$csChangeId);
                                    $resultCsae = $this->LocalService()->itemCsae->update($upChange,'patient_change_id='.$csChangeId);

                                }


                            }

                        }else{
                            $resultFlag = 0;
                            foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey=>$itemIdentificationresultchangeDataValue) {
                                if(empty($csChangeIdFlag) || empty($resultFlag)){
                                    if (!empty($itemIdentificationresultchangeDataValue['result'])){
//                                    in_array($itemIdentificationresultchangeDataValue['is_normal_type'],[1,2,3])
                                        $csChangeId = $itemIdentificationresultchangeDataValue['id'];
                                        $resultFlag = 1;
                                        $csChangeIdFlag = 1;
                                    }else{
                                        if (!empty($resultFlag)){
                                            if (in_array($itemIdentificationresultchangeDataValue['item_name'],[$oldCheckName,$newCheckName])){
                                                $csChangeId = $itemIdentificationresultchangeDataValue['id'];
                                                $csChangeIdFlag = 1;
                                            }
                                        }

                                    }

                                    empty($csChangeIdFlag) && $csChangeId = $itemIdentificationresultchangeDataValue['id'];

                                }
                            }
                            if (!empty($csChangeId)){
                                $upChange['item_checkname_id'] = $newCheckId;
                                $upChange['item_name'] = $newCheckName;
                                $upChange['category_id'] = $newCategoryId;
                                $upChange['checkname_id'] = $useData['checkname_id'];
                                $upChange['lock_state'] = 1;

//                                    $upChange['report_type'] = 1;
                                $resultChange = $this->LocalService()->itemIdentificationresultchange->update($upChange,'id='.$csChangeId);
                                $resultCsae = $this->LocalService()->itemCsae->update($upChange,'patient_change_id='.$csChangeId);

                            }
                            $delChangeIds = implode(',',array_diff($changeIdArr,[$csChangeId]));
//
//
                        }

                        if (isset($delChangeIds) && !empty($delChangeIds)){
                            $delChangeIds = trim($delChangeIds,',');
                            $resultChange = $this->LocalService()->itemIdentificationresultchange->update(['is_del'=>1],'id in('.$delChangeIds.')');
                            $resultCsae = $this->LocalService()->itemCsae->update(['is_del'=>1],'patient_change_id in('.$delChangeIds.')');
                        }

                    }


                }
                if ($flag != 2){
                    $upWork['category_id'] = $newCategoryId;
                    $upWork['update_user_id'] = $itemPatientworkannexDataValue['update_user_id'];
                    $upWork['update_time'] = $itemPatientworkannexDataValue['update_time'];
                    $resultWork = $this->LocalService()->itemPatientworkannex->update($upWork,'id ='.$itemPatientworkannexDataValue['id']);

                }

            }
            $redis = Laminas::$serviceManager->redisExtend->setDatabase(6)->getRedisInstance();
            if(!empty($itemCsaeIdArr)){
                $itemCsaeIdStr = json_encode($itemCsaeIdArr);
                $result = $redis->set($redisKey,$itemCsaeIdStr);
            }

            $itemPatientworkannexDataStr = json_encode($itemPatientworkannexData);
            $result = $redis->set($redisKeyData,$itemPatientworkannexDataStr);

        }
        return true;
        echo '<pre>';print_r($itemPatientworkannexData);die;
    }
    public function delOldCheckNameMoreData($useData=[]){
        if(empty($useData)){
            echo '参数为空';die;
        }
        $item_id = $useData['item_id'];
        $form_id = $useData['form_id'] ? $useData['form_id']:0;
        $oldCategory_id = $useData['oldCategory_id'];
        $oldCategory_ids = $useData['oldCategory_ids'];
        $oldCheckName = $useData['oldCheckName'];
        $newCheckName = $useData['newCheckName'];
        $newCategoryId = $useData['newCategoryId'];
        $newCheckId = $useData['newCheckId'];

        $whereItemPatientworkannex['where'] =  'is_del=0  and lock_state = 1 and item_id =' . $item_id.'  and annex_type !=2  and category_id='.$oldCategory_id;
        if(!empty($form_id))  $whereItemPatientworkannex['where'] .= ' and form_id='.$form_id;
        $whereItemPatientworkannex['group'] = 'form_id';//['checktime_id','patient_form_id','form_id'];
        $whereItemPatientworkannex['columns'] = ['id','checktime_id','patient_form_id','form_id','item_id','itemsig_id','patient_id','category_id','update_user_id','update_time'];
        $whereItemPatientworkannex['order'] = ['id desc'];
        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);
//        echo '<pre>';print_r($whereItemPatientworkannex);die;
        $changeDataId = [];
        $i = 0;
        if(!empty($itemPatientworkannexData)){
            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>$itemPatientworkannexDataValue){
                if (empty($oldCheckName)){
                    echo '老的指标名称不能为空';die;
                }
                $oldCheckNameArr = explode(',',$oldCheckName);

                $newCheckNames = '';
                foreach ($oldCheckNameArr as $oldCheckNameValue){
                    $newCheckNames .= '"'.$oldCheckNameValue.'",';
                }
                $newCheckNames = trim($newCheckNames,',');

                $whereItemCheckname['where'] = [
                    'is_del' => 0,
                    'name' => $oldCheckNameArr,
                    'item_id' => $item_id,
                    'category_id' => $oldCategory_id,
                ];
                $whereItemCheckname['columns'] = ['id','item_id','category_id','name','checkname_id'];
                $itemChecknameData = $this->LocalService()->itemCheckname->fetchAll($whereItemCheckname);

                if (empty($itemChecknameData)) continue;
                $itemChecknameIdArr = array_column($itemChecknameData,'id');
                $itemChecknameIds = implode(',',$itemChecknameIdArr);

                $whereItemIdentificationresultchange['where'] = [
                    'is_del' => 0,
                    'form_id' =>  $itemPatientworkannexDataValue['form_id'],
                    'item_id' => $item_id,
                    'item_checkname_id' => $itemChecknameIdArr,

                ];
                $whereItemIdentificationresultchange['columns'] = ['id','item_checkname_id','researchstage_id','patient_id','item_name','category_id','report_type','patient_form_id','checktime_id','item_id','form_id'];
                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
                if (empty($itemIdentificationresultchangeData)) continue;

                $itemIdentificationresultchangeDatas = [];
                foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataK=>$itemIdentificationresultchangeDataV){
                    if (isset($itemIdentificationresultchangeDatas[$itemIdentificationresultchangeDataV['checktime_id'].'-'.$itemIdentificationresultchangeDataV['patient_form_id']])){
                        $itemIdentificationresultchangeDatas[$itemIdentificationresultchangeDataV['checktime_id'].'-'.$itemIdentificationresultchangeDataV['patient_form_id']][] = $itemIdentificationresultchangeDataV;
                    }else{
                        $itemIdentificationresultchangeDatas[$itemIdentificationresultchangeDataV['checktime_id'].'-'.$itemIdentificationresultchangeDataV['patient_form_id']][] = $itemIdentificationresultchangeDataV;

                    }
                }
//                echo '<pre>';print_r($itemIdentificationresultchangeDatas);die;

                foreach ($itemIdentificationresultchangeDatas as $itemIdentificationresultchangeDatasK=>$itemIdentificationresultchangeDatasV){
                    $formIdS = implode(',',array_unique(array_column($itemIdentificationresultchangeDatasV,'form_id')));
                    $itemFormNameArr = $this->LocalService()->itemForm->fetchCol('name','is_del=0 and item_id ='.$item_id.' and id in('.$formIdS.')');
                    echo '<pre>';'第'.$i.'个'.PHP_EOL;print_r($itemFormNameArr).PHP_EOL;
                    $itemIdentificationresultchangeDatasKArr = explode('-',$itemIdentificationresultchangeDatasK);
                    $whereItemIdentificationresultchanges = 'is_del=0 and checktime_id=' . $itemIdentificationresultchangeDatasKArr[0] . ' and patient_form_id=' . $itemIdentificationresultchangeDatasKArr[1] . ' and item_id =' . $item_id;
                    $itemIdentificationresultchangeCount = $this->LocalService()->itemIdentificationresultchange->getCount($whereItemIdentificationresultchanges);
                    $whereItemIdentificationresultchangeDel = 'is_del=0 and checktime_id=' . $itemIdentificationresultchangeDatasKArr[0] . ' and patient_form_id=' . $itemIdentificationresultchangeDatasKArr[1] . ' and item_id =' . $item_id.' and item_checkname_id in('.$itemChecknameIds.')';
                    $itemIdentificationresultchangeCountDel = $this->LocalService()->itemIdentificationresultchange->getCount($whereItemIdentificationresultchangeDel);
                    echo '总的指标数量：'.$itemIdentificationresultchangeCount.'===要删除的指标数量：'.$itemIdentificationresultchangeCountDel.PHP_EOL;
//                    if ($itemIdentificationresultchangeCount > $itemIdentificationresultchangeCountDel){
//                    if ($itemIdentificationresultchangeCount == $itemIdentificationresultchangeCountDel){
                    if (!empty($itemIdentificationresultchangeCountDel)){
                        $whereItemCsae['where'] = [
                            'is_del' => 0,
                            'checktime_id' => $itemIdentificationresultchangeDatasKArr[0],
                            'patient_form_id' =>$itemIdentificationresultchangeDatasKArr[1],
                            'item_id' => $item_id,
                            'item_checkname_id' => $itemChecknameIdArr,
                        ];
                        $whereItemCsae['columns'] = ['id','patient_change_id','is_ae_sure','item_id','ae_type','update_user_id','update_time'];
                        $itemCsaeData = $this->LocalService()->itemCsae->fetchAll($whereItemCsae);
//                        $itemIdentificationresultchangeCount = $this->LocalService()->itemCsae->getCount($whereItemCsae);
                        if (!empty($itemCsaeData)){
                            foreach ($itemCsaeData as $itemCsaeDataKey=>$itemCsaeDataValue){
                                if ($itemCsaeDataValue['ae_type'] == 5 || $itemCsaeDataValue['ae_type'] == 6){
                                    echo '<pre>';'有cs第'.$i.'个'.print_r($itemCsaeData).PHP_EOL;
                                    $changeDataId['cs'][] = $itemCsaeData;
                                    continue;
                                }
                                echo '<pre>';'cs第'.$i.'个'.$whereItemCsae['where'].PHP_EOL;
                                $itemResult = $this->LocalService()->itemCsae->update(['is_del'=>1,'update_user_id'=>$itemCsaeDataValue['update_user_id'],'update_time'=>$itemCsaeDataValue['update_time']],'id='.$itemCsaeDataValue['id']);
                            }

                        }
                        echo 'change第'.$i.'个'.PHP_EOL;
//                        echo '<pre>';print_r($whereItemIdentificationresultchanges).PHP_EOL;die;
                        echo '<pre>';$whereItemIdentificationresultchanges.PHP_EOL;
                        $itemChangeResult = $this->LocalService()->itemIdentificationresultchange->update(['is_del'=>1],$whereItemIdentificationresultchangeDel);
                        if ($itemIdentificationresultchangeCount == $itemIdentificationresultchangeCountDel){
                            $whereItemPatientworkannexUp['where'] = $whereItemIdentificationresultchanges;
                            $whereItemPatientworkannexUp['columns'] = ['id','checktime_id','patient_form_id','update_user_id','update_time'];
                            $itemPatientworkannexDataUp = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannexUp);
                            if (!empty($itemPatientworkannexDataUp)){
                                foreach ($itemPatientworkannexDataUp as $itemPatientworkannexDataUpV){
                                    $workUpdateArr = ['change_type'=>0,'lock_state'=>0,'update_user_id'=>$itemPatientworkannexDataUpV['update_user_id'],'update_time'=>$itemPatientworkannexDataUpV['update_time']];
                                    $itemWorkannexResult = $this->LocalService()->itemPatientworkannex->update($workUpdateArr,'id='.$itemPatientworkannexDataUpV['id']);

                                }

                            }
                        }
                    }else{

                        if(!empty($itemIdentificationresultchangeCount)){
                            $whereItemCsae['where'] = [
                                'is_del' => 0,
                                'checktime_id' => $itemIdentificationresultchangeDatasKArr[0],
                                'patient_form_id' => $itemIdentificationresultchangeDatasKArr[1],
                                'item_id' => $item_id,
                                'item_checkname_id' => $itemChecknameIdArr
                            ];
                            $whereItemCsae['columns'] = ['id','patient_change_id','is_ae_sure','item_id','ae_type','update_user_id','update_time'];
                            $itemCsaeData = $this->LocalService()->itemCsae->fetchAll($whereItemCsae);
                            if (!empty($itemCsaeData)){
                                foreach ($itemCsaeData as $itemCsaeDataKey=>$itemCsaeDataValue){
                                    if ($itemCsaeDataValue['ae_type'] == 5 || $itemCsaeDataValue['ae_type'] == 6){
                                        echo '<pre>';'有cs第'.$i.'个'.print_r($itemCsaeData).PHP_EOL;
                                        $changeDataId['cs'][] = $itemCsaeData;
                                        continue;
                                    }
                                    echo '<pre>';'cs第'.$i.'个'.$whereItemCsae['where'].PHP_EOL;
                                    $itemResult = $this->LocalService()->itemCsae->update(['is_del'=>1,'update_user_id'=>$itemCsaeDataValue['update_user_id'],'update_time'=>$itemCsaeDataValue['update_time']],'id='.$itemCsaeDataValue['id']);
                                }

                            }
                            echo 'change第'.$i.'个'.PHP_EOL;
                            echo '<pre>';$whereItemIdentificationresultchanges.PHP_EOL;
                            $itemChangeResult = $this->LocalService()->itemIdentificationresultchange->update(['is_del'=>1],$whereItemIdentificationresultchangeDel);
                            $whereItemPatientworkannexUp['where'] = $whereItemIdentificationresultchanges;
                            $whereItemPatientworkannexUp['columns'] = ['id','checktime_id','patient_form_id','update_user_id','update_time'];
                            $itemPatientworkannexDataUp = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannexUp);
                            if (!empty($itemPatientworkannexDataUp)){
                                foreach ($itemPatientworkannexDataUp as $itemPatientworkannexDataUpV){
                                    $workUpdateArr = ['change_type'=>0,'lock_state'=>0,'update_user_id'=>$itemPatientworkannexDataUpV['update_user_id'],'update_time'=>$itemPatientworkannexDataUpV['update_time']];
                                    $itemWorkannexResult = $this->LocalService()->itemPatientworkannex->update($workUpdateArr,'id='.$itemPatientworkannexDataUpV['id']);

                                }

                            }
                        }

                        $changeArr['checktime_id'] =  $itemIdentificationresultchangeDatasKArr[0];
                        $changeArr['patient_form_id'] =  $itemIdentificationresultchangeDatasKArr[1];
                        $changeArr['item_id'] =  $item_id;
                        foreach ($itemIdentificationresultchangeDatasV as &$value){
                            $stage_name = $this->LocalService()->itemResearchstage->getOneFieldVal('stage_name','is_del=0 and id ='.$value['researchstage_id']);//
                            $check_name = $this->LocalService()->itemChecktime->getOneFieldVal('check_name','is_del=0 and id ='.$value['checktime_id']);//
                            $patient_name = $this->LocalService()->patient->getOneFieldVal('patient_name','is_del=0 and id ='.$value['patient_id']);//
                            $form_names = $this->LocalService()->itemForm->getOneFieldVal('name','is_del=0 and id ='.$value['form_id']);//
                            $value['patient_name'] = $patient_name;
                            $value['form_name'] = $form_names;
                            $value['check_stage_name'] = '['.$stage_name.']'.$check_name;
                        }
                        $changeArr['arr'] =  $itemIdentificationresultchangeDatasV;

                        $changeDataId['ch'][] = $changeArr;

                    }

                    $i++;
                }

//                echo '<pre>';print_r($itemIdentificationresultchangeDatas);die;

            }

        }
        echo '成功'.PHP_EOL;
        return true;
        echo '<pre>';print_r($changeDataId);die;
    }

    //普通删除主方法
    public function delChangeCSCheckNameMoreData($useData=[]){

        if(empty($useData)){
            echo '参数为空';die;
        }
        $item_id = $useData['item_id'];
        $form_id = $useData['form_id'] ? $useData['form_id']:0;
        $oldCategory_id = $useData['oldCategory_id'];
        $oldCheckName = $useData['oldCheckName'];
        $newCheckName = $useData['newCheckName'];
        $newCategoryId = $useData['newCategoryId'];
        $newCheckId = $useData['newCheckId'];

        $where = '';//!=2
        $itemFormNameArr = $this->LocalService()->itemForm->fetchCol('name',[
            'is_del' => 0,
            'item_id' => explode(',', $item_id)
        ]);
        $wherePatientArr['where'] = [
            'is_del' => 0,
            'item_id' => explode(',', $item_id)
        ];
        $wherePatientArr['columns'] = ['id','patient_name','patient_number'];
        $patientData = $this->LocalService()->patient->fetchAll($wherePatientArr);//$item_id
        $patientNameArr = [];
        if(!empty($patientData)){
            foreach ($patientData as $patientDataKey=>$patientDataValue) {
                $patientNameArr[$patientDataValue['id']] = $patientDataValue;
            }
        }

        $whereItemPatientworkannex['where'] =  'is_del=0  and lock_state = 1 and item_id =' . $item_id.'  and annex_type !=2  and category_id='.$oldCategory_id.$where;
        if(!empty($form_id))  $whereItemPatientworkannex['where'] .= ' and form_id='.$form_id;
//        $whereItemPatientworkannex['group'] = ['checktime_id','patient_form_id','form_id'];
        $whereItemPatientworkannex['columns'] = ['id','checktime_id','patient_form_id','form_id','item_id','itemsig_id','patient_id','category_id','update_user_id','update_time'];
        $whereItemPatientworkannex['order'] = ['id desc'];
        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);


        $itemCsaeIdArr = [];
        if (!empty($itemPatientworkannexData)){
            $redisKey = 'itemworkChangeCheckname-'.$item_id.'-'.$form_id;
            $redisKeyData = 'itemworkChangeChecknameData-'.$item_id.'-'.$form_id;
            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>&$itemPatientworkannexDataValue) {
                echo '正在处理第'.$itemPatientworkannexDataKey.'个==分类id为：'.$oldCategory_id. PHP_EOL;

                $key = $item_id.'-'.$itemPatientworkannexDataValue['checktime_id'] . '-' . $itemPatientworkannexDataValue['patient_form_id'];

                $category_id = $this->LocalService()->itemForm->getOneFieldVal('checklist_id',"item_id = ".$itemPatientworkannexDataValue['item_id'] ." and is_del = 0 and id = ".$itemPatientworkannexDataValue['form_id']);
                if($category_id == $oldCategory_id) continue;
//                echo $category_id.'==='.$oldCategory_id;
                $whereItemCheckname['where'] = [
                    'is_del' => 0,
                    'category_id' => $category_id,
                    'item_id' => $itemPatientworkannexDataValue['item_id']
                ];
                $whereItemCheckname['columns'] = ['id','item_id','category_id','name','checkname_id'];
                $itemChecknameData = $this->LocalService()->itemCheckname->fetchAll($whereItemCheckname);
                $itemPatientworkannexDataValue['itemChecknameData'] = $itemChecknameData;
                $itemChecknameDatas = [];
                if(!empty($itemChecknameData)){
                    foreach ($itemChecknameData as $itemChecknameDataKey=>$itemChecknameDataValue) {
                        $itemChecknameDatas[$itemChecknameDataValue['name']] = $itemChecknameDataValue;
                    }
                }
                if(empty($itemChecknameDatas)) continue;

                $whereItemIdentificationresultchange['where'] = [
                    'is_del' => 0,
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                    'item_id' => $item_id
                ];
                $whereItemIdentificationresultchange['columns'] = ['id','item_checkname_id','item_name','category_id','report_type','is_normal_type','result'];
                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
                $itemPatientworkannexDataValue['change'] = $itemIdentificationresultchangeData;
                if (!empty($patientNameArr) && isset($patientNameArr[$itemPatientworkannexDataValue['patient_id']]) ){
                    $patient_name = $patientNameArr[$itemPatientworkannexDataValue['patient_id']]['patient_name'];
                    $patient_number = $patientNameArr[$itemPatientworkannexDataValue['patient_id']]['patient_number'];
                    $patientNameNumber = '';
                    if (!empty($patient_number)) $patientNameNumber = '【'.$patient_number.'】';
                    if (!empty($patient_name)) $patientNameNumber .= $patient_name;
                    $itemPatientworkannexDataValue['patient_name'] = $patientNameNumber;
                }
                if (!empty($itemFormNameArr) && isset($itemFormNameArr[$itemPatientworkannexDataValue['form_id']]) ){
                    $itemPatientworkannexDataValue['form_name'] = $itemFormNameArr[$itemPatientworkannexDataValue['form_id']];
                }

                if (!empty($itemIdentificationresultchangeData)) {
                    $changeCount = count($itemIdentificationresultchangeData);
                    $changeIdArr = array_column($itemIdentificationresultchangeData,'id');
                    $patient_change_id = implode(', ', $changeIdArr);
                    if(!empty($patient_change_id)){
                        $upChangeArrRedis  = [];//and is_ae_sure = 1==and ae_type in(5,6)
                        $whereItemCsae['where'] = [
                            'is_del' => 0,
                            'patient_change_id' => $patient_change_id
                        ];

                        $itemCsaeData = $this->LocalService()->itemCsae->fetchCol('patient_change_id',$whereItemCsae['where']);
                        $delChangeIds = '';
                        $delCsIds = '';
                        $itemChecknameArr = array_keys($itemChecknameDatas);
                        if(!empty($itemCsaeData)){
                            foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey=>$itemIdentificationresultchangeDataValue) {
//                                if($itemIdentificationresultchangeDataValue['item_name'] != '梅毒螺旋体抗体') continue;

                                //指标不一样====1和1-2时要打开
                                if (in_array($item_id,[85,94]) && ($itemIdentificationresultchangeDataValue['category_id'] == 285) && ($itemIdentificationresultchangeDataValue['item_name'] == '梅毒螺旋体抗体')){
                                    $itemIdentificationresultchangeDataValue['item_name'] = '梅毒螺旋体抗体(TP-Ab)';
                                }
                                //指标不一样====1和1-2时要打开
//                                if (in_array($item_id,[85,94]) && ($itemIdentificationresultchangeDataValue['category_id'] == 294) && ($itemIdentificationresultchangeDataValue['item_name'] == '丙肝抗体(HCV-Ab)')){
//                                    $itemIdentificationresultchangeDataValue['item_name'] = '丙肝抗体';
//                                }
                                if (in_array($item_id,[85,94,109]) && ($itemIdentificationresultchangeDataValue['category_id'] == 294) && ($itemIdentificationresultchangeDataValue['item_name'] == '丙肝抗体(HCV-Ab)')){
                                    $itemIdentificationresultchangeDataValue['item_name'] = '丙肝抗体';
                                }
//                                echo'<pre>';print_r(($itemIdentificationresultchangeDataValue));die;

                                $upChangeArr  = [];
                                $upCsArr = [];

                                if(in_array($itemIdentificationresultchangeDataValue['item_name'],$itemChecknameArr)){
                                    $upChangeArrRedis['item_checkname_id'] = $upChangeArr['item_checkname_id'] = $itemChecknameDatas[$itemIdentificationresultchangeDataValue['item_name']]['id'];
                                    $upChangeArrRedis['category_id'] = $upChangeArr['category_id'] = $itemChecknameDatas[$itemIdentificationresultchangeDataValue['item_name']]['category_id'];
                                    $upChangeArrRedis['checkname_id'] = $upChangeArr['checkname_id'] = $itemChecknameDatas[$itemIdentificationresultchangeDataValue['item_name']]['checkname_id'];
                                    $upChangeArrRedis['id'] = $upChangeArr['id'] = $itemIdentificationresultchangeDataValue['id'];
                                    $upChangeArrRedis['lock_state'] = $upChangeArr['lock_state'] = 1;

                                    //指标不一样====1和1-2时要打开
                                     $upChangeArrRedis['item_name'] = $upChangeArr['item_name'] = $itemChecknameDatas[$itemIdentificationresultchangeDataValue['item_name']]['name'];

                                    $resultChange = $this->LocalService()->itemIdentificationresultchange->save($upChangeArr);
                                    $upChangeArrRedis['is_normal_type'] = $itemIdentificationresultchangeDataValue['is_normal_type'];
                                    $upChangeArrRedis['result'] = $itemIdentificationresultchangeDataValue['result'];
                                    $itemCsaeIdArr[$key]['change'][] = $upChangeArrRedis;

                                    echo '正在处理第'.$itemPatientworkannexDataKey.'-change'.$itemIdentificationresultchangeDataKey.'个==分类id为：'.$oldCategory_id. PHP_EOL;

                                    if(in_array($itemIdentificationresultchangeDataValue['id'],$itemCsaeData)){

                                        $upCsArr['item_checkname_id'] = $itemChecknameDatas[$itemIdentificationresultchangeDataValue['item_name']]['id'];
                                        $upCsArr['category_id'] = $itemChecknameDatas[$itemIdentificationresultchangeDataValue['item_name']]['category_id'];
                                        $upCsArr['checkname_id'] = $itemChecknameDatas[$itemIdentificationresultchangeDataValue['item_name']]['checkname_id'];

                                        //指标不一样====1和1-2时要打开
                                        $upCsArr['item_name'] = $itemChecknameDatas[$itemIdentificationresultchangeDataValue['item_name']]['name'];


//                                            $upCsArr[$itemIdentificationresultchangeDataKey]['patient_change_id'] = $itemIdentificationresultchangeDataValue['id'];
                                        $upCsArr['lock_state'] = 1;
                                        $itemCsaeIdArr[$key]['cs'][] = $upCsArr;

                                        $resultCsae = $this->LocalService()->itemCsae->update($upCsArr,'is_del=0 and patient_change_id='.$itemIdentificationresultchangeDataValue['id']);
                                        echo '正在处理第'.$itemPatientworkannexDataKey.'-cs'.$itemIdentificationresultchangeDataKey.'个==分类id为：'.$oldCategory_id. PHP_EOL;

                                    }else{
                                        $delCsIds .= $itemIdentificationresultchangeDataValue['id'].',';
                                    }
                                } else{
                                    $delChangeIds .= $itemIdentificationresultchangeDataValue['id'].',';
                                }

                            }
                            if (!empty($delCsIds) && !empty($upCsArr)){
                                $delCsIds = trim($delCsIds,',');
                                $resultCsae = $this->LocalService()->itemCsae->update(['is_del'=>1],'patient_change_id in('.$delCsIds.')');
                            }

                        }else{

                            foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey=>$itemIdentificationresultchangeDataValue) {
//                                if($itemIdentificationresultchangeDataValue['item_name'] != '梅毒螺旋体抗体') continue;
                                    //指标不一样====1和1-2时要打开
                                if (in_array($item_id,[85,94]) && ($itemIdentificationresultchangeDataValue['category_id'] == 285) && ($itemIdentificationresultchangeDataValue['item_name'] == '梅毒螺旋体抗体')){
                                    $itemIdentificationresultchangeDataValue['item_name'] = '梅毒螺旋体抗体(TP-Ab)';
                                }

                                //指标不一样====1和1-2时要打开
//                                if (in_array($item_id,[85,94]) && ($itemIdentificationresultchangeDataValue['category_id'] == 294) && ($itemIdentificationresultchangeDataValue['item_name'] == '丙肝抗体(HCV-Ab)')){
//                                    $itemIdentificationresultchangeDataValue['item_name'] = '丙肝抗体';
//                                }

                                if (in_array($item_id,[85,94,109]) && ($itemIdentificationresultchangeDataValue['category_id'] == 294) && ($itemIdentificationresultchangeDataValue['item_name'] == '丙肝抗体(HCV-Ab)')){
                                    $itemIdentificationresultchangeDataValue['item_name'] = '丙肝抗体';
                                }
                                $upChangeArr  = [];
                                if(in_array($itemIdentificationresultchangeDataValue['item_name'],$itemChecknameArr)){
                                    $upChangeArrRedis['item_checkname_id'] = $upChangeArr['item_checkname_id'] = $itemChecknameDatas[$itemIdentificationresultchangeDataValue['item_name']]['id'];
                                    $upChangeArrRedis['category_id'] = $upChangeArr['category_id'] = $itemChecknameDatas[$itemIdentificationresultchangeDataValue['item_name']]['category_id'];
                                    $upChangeArrRedis['checkname_id'] = $upChangeArr['checkname_id'] = $itemChecknameDatas[$itemIdentificationresultchangeDataValue['item_name']]['checkname_id'];
                                    $upChangeArrRedis['id'] = $upChangeArr['id'] = $itemIdentificationresultchangeDataValue['id'];
                                    $upChangeArrRedis['lock_state'] = $upChangeArr['lock_state'] = 1;

                                    //指标不一样====1和1-2时要打开
                                    $upChangeArrRedis['item_name'] = $upChangeArr['item_name'] = $itemChecknameDatas[$itemIdentificationresultchangeDataValue['item_name']]['name'];

                                    $resultChange = $this->LocalService()->itemIdentificationresultchange->save($upChangeArr);
                                    $upChangeArrRedis['is_normal_type'] = $itemIdentificationresultchangeDataValue['is_normal_type'];
                                    $upChangeArrRedis['result'] = $itemIdentificationresultchangeDataValue['result'];
                                    $itemCsaeIdArr[$key]['change'][] = $upChangeArrRedis;

                                    echo '正在处理第'.$itemPatientworkannexDataKey.'-change'.$itemIdentificationresultchangeDataKey.'个==分类id为：'.$oldCategory_id. PHP_EOL;

                                } else{
                                    $delChangeIds .= $itemIdentificationresultchangeDataValue['id'].',';
                                }

                            }

                        }
                        if (!empty($delChangeIds) && !empty($upChangeArrRedis)){
                            $delChangeIds = trim($delChangeIds,',');
                            $resultChange = $this->LocalService()->itemIdentificationresultchange->update(['is_del'=>1],'id in('.$delChangeIds.')');
                            $resultCsae = $this->LocalService()->itemCsae->update(['is_del'=>1],'patient_change_id in('.$delChangeIds.')');
                        }


                    }


                }
                $upWork['category_id'] = $category_id;
                $upWork['update_user_id'] = $itemPatientworkannexDataValue['update_user_id'];
                $upWork['update_time'] = $itemPatientworkannexDataValue['update_time'];
                if (!empty($delChangeIds) && !empty($upChangeArrRedis)){
                    $resultWork = $this->LocalService()->itemPatientworkannex->update($upWork,'id ='.$itemPatientworkannexDataValue['id']);
                }
                //暂时不用，
//                $resultWork = $this->LocalService()->itemPatientworkannex->update($upWork,'id ='.$itemPatientworkannexDataValue['id']);


            }
            $redis = Laminas::$serviceManager->redisExtend->setDatabase(6)->getRedisInstance();
            if(!empty($itemCsaeIdArr)){
                $this->delRepeatChangeCheckName($itemCsaeIdArr);
                $itemCsaeIdStr = json_encode($itemCsaeIdArr);
                $result = $redis->set($redisKey,$itemCsaeIdStr);
            }
            $itemPatientworkannexDataStr = json_encode($itemPatientworkannexData);
            $result = $redis->set($redisKeyData,$itemPatientworkannexDataStr);

        }
        return true;
        echo '<pre>';print_r($itemPatientworkannexData);die;
    }

    //没锁并且change没有数据的更新分类(单调)
    public function updateWorkNotLockState($useData = []){
        if(empty($useData)){
            echo '参数为空';die;
        }
        $item_id = $useData['item_id'];
        $form_id = $useData['form_id'] ? $useData['form_id']:0;
        $oldCategory_id = $useData['oldCategory_id'];
        $whereItemPatientworkannex['where'] =  'is_del=0  and change_type =0  and item_id =' . $item_id.'  and annex_type !=2  and category_id='.$oldCategory_id;
        if(!empty($form_id))  $whereItemPatientworkannex['where'] .= ' and form_id='.$form_id;
        $whereItemPatientworkannex['columns'] = ['id','checktime_id','patient_form_id','form_id','item_id','itemsig_id','patient_id','category_id','update_user_id','update_time'];
        $whereItemPatientworkannex['order'] = ['id desc'];
        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);
        if (!empty($itemPatientworkannexData)){
            $itemFormNameArr = $this->LocalService()->itemForm->fetchCol('checklist_id','is_del=0 and item_id in('.$item_id.') and id in ('.implode(',',array_column($itemPatientworkannexData,'form_id')).')');
            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>$itemPatientworkannexDataValue) {
                if (isset($itemFormNameArr[$itemPatientworkannexDataValue['form_id']]) && !empty($itemFormNameArr[$itemPatientworkannexDataValue['form_id']])){
                    $category_id = $itemFormNameArr[$itemPatientworkannexDataValue['form_id']];
                    if (!empty($itemPatientworkannexDataValue['category_id']) && ($itemPatientworkannexDataValue['category_id'] != $category_id)){
                        $upArr = [
                            'category_id'=>$category_id,
                            'update_time'=>$itemPatientworkannexDataValue['update_time'],
                            'update_user_id'=>$itemPatientworkannexDataValue['update_user_id'],
                        ];
                        $resultWork = $this->LocalService()->itemPatientworkannex->update($upArr,'id='.$itemPatientworkannexDataValue['id']);

                    }
                }
            }
        }
        echo '<pre>';print_r($itemPatientworkannexData);die;

    }
    //普通指标删除
    public function delRepeatChangeCheckName($itemChangeDelData){

        $changeData = array_column($itemChangeDelData,'change');
        if(!isset($changeData) || empty($changeData)) return false;
        foreach ($changeData as $itemPatientworkannexDataKey=>$itemChangeDelDataValue){
            $changeIdArr = array_column($itemChangeDelDataValue,'item_checkname_id','id');

            $itemCheckNameId = array_column($itemChangeDelDataValue,'item_checkname_id');
            $itemCheckNameUniqueId = array_unique($itemCheckNameId);
            $newItemCheckNameId = array_diff_assoc($itemCheckNameId,$itemCheckNameUniqueId);

            $csaeData = [];
            $updateChangeArr = [];
            $updateChangeCheckIdArr = [];
            if(!empty($changeIdArr) && !empty($newItemCheckNameId)){
                $whereCS['where'] = [
                    'is_del' => 0,
                    'patient_change_id' => array_keys($changeIdArr),
                    'item_checkname_id' => $newItemCheckNameId,
                ];
                $whereCS['columns'] = ['id'=>'patient_change_id','item_checkname_id'];
                $csaeData = $this->LocalService()->itemCsae->fetchAll($whereCS);
            }
            if (!empty($csaeData)){
                $newChangeIdArr = array_column($csaeData,'item_checkname_id','id');
                foreach ($changeIdArr as $id=>$item_checkname_id) {
                    if (in_array($item_checkname_id,$newChangeIdArr) && !in_array($id,array_keys($newChangeIdArr))){
                        $updateChangeArr[$id] = $id;
                    }
                }

                if (!empty($updateChangeArr)){
                    $this->LocalService()->itemIdentificationresultchange->update(['is_del' => 1], ['id' => $updateChangeArr]);
                }
                echo '使用cs数据删除' . var_export($updateChangeArr) . PHP_EOL;
            }else {

                foreach ($itemChangeDelDataValue as $itemIdentificationresultchangeDatasKey => $itemIdentificationresultchangeDatasValue) {
                    if (!empty($itemIdentificationresultchangeDatasValue['result']) && !empty($itemIdentificationresultchangeDatasValue['is_normal_type'])) {
                        if (in_array($itemIdentificationresultchangeDatasValue['item_checkname_id'], $updateChangeArr)) {
                            if (isset($updateChangeCheckIdArr[$itemIdentificationresultchangeDatasValue['item_checkname_id']]) && $updateChangeCheckIdArr[$itemIdentificationresultchangeDatasValue['item_checkname_id']] == 1) {
                                continue;
                            }
                        }
                        $updateChangeArr[$itemIdentificationresultchangeDatasValue['id']] = $itemIdentificationresultchangeDatasValue['item_checkname_id'];
                        $updateChangeCheckIdArr[$itemIdentificationresultchangeDatasValue['item_checkname_id']] = 1;

                    } else if (!empty($itemIdentificationresultchangeDatasValue['result']) || !empty($itemIdentificationresultchangeDatasValue['is_normal_type'])) {
                        if (in_array($itemIdentificationresultchangeDatasValue['item_checkname_id'], $updateChangeArr)) {
                            if (isset($updateChangeCheckIdArr[$itemIdentificationresultchangeDatasValue['item_checkname_id']]) && ($updateChangeCheckIdArr[$itemIdentificationresultchangeDatasValue['item_checkname_id']] != 3)) {
                                continue;
                            }
                        }
                        $updateChangeArr[$itemIdentificationresultchangeDatasValue['id']] = $itemIdentificationresultchangeDatasValue['item_checkname_id'];
                        $updateChangeCheckIdArr[$itemIdentificationresultchangeDatasValue['item_checkname_id']] = 2;
                    } else {
                        if (in_array($itemIdentificationresultchangeDatasValue['item_checkname_id'], $updateChangeArr)) {
                            continue;
                        }
                        $updateChangeArr[$itemIdentificationresultchangeDatasValue['id']] = $itemIdentificationresultchangeDatasValue['item_checkname_id'];
                        $updateChangeCheckIdArr[$itemIdentificationresultchangeDatasValue['item_checkname_id']] = 3;
                    }

                }
                if (!empty($updateChangeArr)) {
                    $changeIdUpdate = array_diff_key($changeIdArr, $updateChangeArr);
                    if (!empty($changeIdUpdate)) {
                        $newChangeIdUpdate = array_flip($changeIdUpdate);
                        $this->LocalService()->itemIdentificationresultchange->update(['is_del' => 1], ['id' => $newChangeIdUpdate]);
                    }
                }
                echo '删除' . var_export($changeIdUpdate) . PHP_EOL;
            }
        }
        return true;
        die;

    }

    //查询csae数据重复去重,
    public function repeatCsAe($type = 1,array $where = []){
        $patientWhere['where'] = [
            'is_del' => 0
        ];
        !empty($where) && $patientWhere['where'] = ArrayUtils::merge($patientWhere['where'], $where);
        $patientWhere['columns'] = [
            'patient_change_id'=>new Expression('GROUP_CONCAT(patient_change_id)'),
            'ids'=>new Expression('GROUP_CONCAT(id)'),
            'item_name'=>new Expression('GROUP_CONCAT(item_name)'),
            'patient_form_ids'=>new Expression('GROUP_CONCAT(patient_form_id)'),
            'patient_ids'=>new Expression('GROUP_CONCAT(patient_id)'),
            'checktime_ids'=>new Expression('GROUP_CONCAT(checktime_id)'),
            'result'=>new Expression('GROUP_CONCAT(result)'),
            'unit'=>new Expression('GROUP_CONCAT(unit)'),
            'reference_range_max'=>new Expression('GROUP_CONCAT(reference_range_max)'),
            'reference_range_min'=>new Expression('GROUP_CONCAT(reference_range_min)'),
            'is_sure'=>new Expression('GROUP_CONCAT(is_sure)'),
            'is_ae_sure'=>new Expression('GROUP_CONCAT(is_ae_sure)'),
            'ae_type'=>new Expression('GROUP_CONCAT(ae_type)'),
            'create_time'=>new Expression('GROUP_CONCAT(FROM_UNIXTIME(create_time,"%Y-%m-%d %H:%i:%s"))'),
            'update_time'=>new Expression('GROUP_CONCAT(FROM_UNIXTIME(update_time,"%Y-%m-%d %H:%i:%s"))'),
            'count'=>new Expression('count(*)'),
            'id',
            'item_id',
            'patient_form_id',
            'patient_id',
            'form_id',
            'checktime_id',
            'researchstage_id',
            'update_user_id',
        ];
        $patientWhere['group'] = ['patient_form_id','checktime_id','patient_id','patient_change_id'];
        $patientWhere['having'] = 'count > 1';
        $datas = $this->LocalService()->itemCsae->fetchAll($patientWhere);


        $csIds = '';
        $newPatientIds = '';
        $csIdArr = [];
        $patientIdArr = [];
        $count = 0;
        foreach ($datas as &$dataColumn) {
            $newCsIdArr = explode(',',$dataColumn['ids']);
            $count += count($newCsIdArr);
            $newPatientIdArr = array_unique(explode(',',$dataColumn['patient_ids']));
            array_shift($newCsIdArr);
//            array_pop($newCsIdArr);
            if (!empty($newCsIdArr)){
                $csIds .= implode(',',$newCsIdArr).',';
            }
            if (!empty($newPatientIdArr)){
                $newPatientIds .= implode(',',$newPatientIdArr).',';
            }
            $csIdArr[] = $dataColumn['ids'];
            $patientIdArr[] = $dataColumn['patient_ids'];
            $dataColumn['form_name'] = $this->LocalService()->itemForm->getOneFieldVal('name', 'is_del=0 and id=' . $dataColumn['form_id']);
            $dataColumn['check_name'] = $this->LocalService()->itemChecktime->getOneFieldVal('check_name', 'is_del=0 and id=' . $dataColumn['checktime_id']);
            $dataColumn['stage_name'] = $this->LocalService()->itemResearchstage->getOneFieldVal('stage_name', 'is_del=0 and id=' . $dataColumn['researchstage_id']);
            $dataColumn['patient_name'] = $this->LocalService()->patient->getOneFieldVal('patient_name', 'is_del=0 and id=' . $dataColumn['patient_id']);
            $dataColumn['patient_number'] = $this->LocalService()->patient->getOneFieldVal('patient_number', 'is_del=0 and id=' . $dataColumn['patient_id']);
            if (!empty($dataColumn['patient_number'])){
                $dataColumn['patient_name'] = '【'.$dataColumn['patient_number'].'】'.$dataColumn['patient_name'];
            }
            $dataColumn['check_name'] = '【'.$dataColumn['stage_name'].'】'.$dataColumn['check_name'];

        }
        $csIds = trim($csIds,',');
        $delCount = count(explode(',',$csIds));
        $data['sql'] =  'update yikeen_item_csae set is_del=1 where id in('.$csIds.')';
        $data['count'] = $count;
        $data['delCount'] = $delCount;
        $data['csIdArr'] = $csIdArr;
        $data['newPatientIds'] = $newPatientIds;
        $data['patientIdArr'] = $csIdArr;
        $data['data'] = $datas;
        if($type == 2 && !empty($csIds)){
            $resultCsae = $this->LocalService()->itemCsae->update(['is_del'=>1], 'id in( ' . $csIds.')');
            echo '<pre>成功删除'.$csIds.'<pre>';
            echo '<pre>';print_r($data);
            die;

        }
        echo '<pre>';print_r($data);die;

    }


    //更新某个字段
    public function updateFeildDate($useData = []){
        if(empty($useData)){
            echo '参数为空';die;
        }
        $item_id = $useData['item_id'];
        $ids = $useData['id'];
        $field_up = $useData['field_up'];
        $field_value = $useData['field_value'];
        $field = $useData['field'];
        $where = $useData['where']?:'';
        $type = $useData['type']?:'';
        if (empty($where)){
            $whereItemPatientworkannex['where'] =  'is_del=0  and item_id =' . $item_id.'  and annex_type !=2  and id in('.$ids.')';
        }else{
            $whereItemPatientworkannex['where'] =  $where;
        }

        $returnData = [];
        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);
        if (!empty($itemPatientworkannexData)){
            if (!empty($field_up)){
                $upArr = json_decode($field_up,1);
            }else{
                $upArr[$field] = $field_value;
            }
            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>$itemPatientworkannexDataValue) {
                $returnData[$itemPatientworkannexDataKey]['workannexIds'] = implode(',',array_column($itemPatientworkannexData,'id'));

                $upArr['update_time'] = $itemPatientworkannexDataValue['update_time'];
                $upArr['update_user_id'] = $itemPatientworkannexDataValue['update_user_id'];

                ($type == 2) && $resultWork = $this->LocalService()->itemPatientworkannex->update($upArr,'id='.$itemPatientworkannexDataValue['id']);

                $whereChange['where'] = [
                    'is_del' => 0,
                    'item_id' => $itemPatientworkannexDataValue['item_id'],
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                ];

                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereChange);
                if (!empty($itemIdentificationresultchangeData)){
                    $returnData[$itemPatientworkannexDataKey]['changeIds'] = $patient_change_id = implode(',',array_column($itemIdentificationresultchangeData,'id'));
                    if($type == 2){
                        foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey=>$itemIdentificationresultchangeDataValue) {
                            $upArr['update_time'] = $itemIdentificationresultchangeDataValue['update_time'];
                            $upArr['update_user_id'] = $itemIdentificationresultchangeDataValue['update_user_id'];
                            $resultChange = $this->LocalService()->itemIdentificationresultchange->update($upArr,'id in('.$itemIdentificationresultchangeDataValue['id'].')');
                        }
                    }

                    $whereCsae['where'] = [
                        'is_del' => 0,
                        'patient_change_id' => $patient_change_id,
                    ];
                    $whereCsae['columns'] = ['id','checktime_id','patient_form_id','item_name'];
                    $csData = $this->LocalService()->itemCsae->fetchAll($whereCsae);
                    if (!empty($csData)){
                        $returnData[$itemPatientworkannexDataKey]['csaeIds'] = $csaeIds = implode(',',array_column($csData,'id'));
                        if($type == 2){
                            foreach ($csData as $csDataKey=>$csDataValue) {
                                $upArr['update_time'] = $csDataValue['update_time'];
                                $upArr['update_user_id'] = $csDataValue['update_user_id'];
                                $resultCsae = $this->LocalService()->itemCsae->update($upArr,'id in('.$csDataValue['id'].')');
                            }
                        }

                    }

                }
            }


        }
        echo '<pre>';print_r($returnData);

        echo '<pre>';print_r($itemPatientworkannexData);die;
    }

    //补附件==
    public function updateChange($item = []){
        if(empty($item)){
            echo '参数为空';die;
        }
        $itemSignatoryIdData = [];
//        foreach ($arr as $k=>$item) {
            $itemFormNameArr = $this->LocalService()->itemForm->fetchCol('name','is_del=0 and item_id in('.$item['item_id'].')');//$item_id
            $wherePatientArr['where'] = [
                'is_del' => 0,
                'item_id' => $item['item_id']
            ];
            $wherePatientArr['columns'] = ['id','patient_name','patient_number'];
            $patientData = $this->LocalService()->patient->fetchAll($wherePatientArr);//$item_id
            $patientNameArr = [];
            if(!empty($patientData)){
                foreach ($patientData as $patientDataKey=>$patientDataValue) {
                    $patientNameArr[$patientDataValue['id']] = $patientDataValue;
                }
            }
            $whereItemPatientChange['where'] =  'is_del=0  and lock_state = 1 and item_id =' . $item['item_id'].'  and annex_type !=2 ';
            if(isset($item['form_id']) && !empty($item['form_id'])) $whereItemPatientChange['where'] .= ' and form_id='.$item['form_id'];
            if(isset($item['oldCategory_id']) && !empty($item['oldCategory_id'])) $whereItemPatientChange['where'] .= ' and category_id='.$item['oldCategory_id'];

            $whereItemPatientChange['columns'] = [
                'id'=>'id',
                'patient_form_id'=>'patient_form_id',
                'checktime_id'=>'checktime_id',
                'patientworkannex_id'=>'patientworkannex_id',
                'item_checkname_id'=>'item_checkname_id',
                'category_id'=>'category_id',
                'item_name'=>'item_name',
                'item_id'=>'item_id',
                'itemsig_id'=>'itemsig_id',
                'form_id'=>'form_id',
                'patient_id'=>'patient_id',
                'annex_path'=>'annex_path',
                'annex_type'=>'annex_type',
                'ocr_id'=>'ocr_id',
                'researchstage_id'=>'researchstage_id',
                'collect_date'=>'collect_date',
                'report_type'=>'report_type',
                'create_time'=>'create_time',
                'create_user_id'=>'create_user_id',
            ];
            $whereItemPatientChange['group'] = ['checktime_id','patient_form_id'];
            $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemPatientChange);
//            echo '<pre>';print_r($itemIdentificationresultchangeData);die;
            $count =0;
            $i=0;
            $notCheckData = [];
            if (!empty($itemIdentificationresultchangeData)){
                foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey=>$itemIdentificationresultchangeDataValue){
                    $itemIdentificationresultchangeDataValue['from_name'] = $itemFormNameArr[$itemIdentificationresultchangeDataValue['form_id']];
                    $itemIdentificationresultchangeDataValue['patient_name'] = '【'.$patientNameArr[$itemIdentificationresultchangeDataValue['patient_id']]['patient_number'].'】'.$patientNameArr[$itemIdentificationresultchangeDataValue['patient_id']]['patient_name'];
//                    echo '<pre>';print_r($itemIdentificationresultchangeDataValue);die;
                    $whereItemPatientworkannex['where'] =  'is_del=0  and lock_state = 1 and item_id =' . $item['item_id'].'  and annex_type !=2  and patient_form_id in('.$itemIdentificationresultchangeDataValue['patient_form_id'].') and checktime_id in('.$itemIdentificationresultchangeDataValue['checktime_id'].')';
                    $whereItemPatientworkannex['columns'] = [
                        'id'=>'id',
                        'patient_form_id'=>'patient_form_id',
                        'checktime_id'=>'checktime_id',
                        'category_id'=>'category_id',
                    ];

                    $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);
                    if (!empty($itemPatientworkannexData)){
                        $count++;
                    }else{

                        //验证老系统的数据
//                        if (!empty($itemIdentificationresultchangeDataValue['annex_path'])){
//                            $annexPath = explode(',',$itemIdentificationresultchangeDataValue['annex_path']);
//                            foreach ($annexPath as $annexPathKey=>$annexPathValue){
//                                $newPath = explode('path=',$annexPathValue);
//                                $newPathWork = end($newPath);
//                                $pathArr = explode('/',$newPathWork);
//                                $workArr['annex_title'] = end($pathArr);
//
//
////                            echo '正在处理第一'.$itemIdentificationresultchangeDataKey.'个'. PHP_EOL;
//                                //附件
//                                $oldItemPatientworkannexData = $this->LocalService()->itemIdentificationresult->dbData('oa_item_patientworkannex','is_del=0  and annex_path ="'.$newPathWork.'"','id');
//                                $oldItemPatientworkannexInfoIdData = $this->LocalService()->itemIdentificationresult->dbData('oa_item_patientworkannex','is_del=0  and info_id !=0 and annex_path ="'.$newPathWork.'"','info_id');
//
//                                if(empty($oldItemPatientworkannexData) && empty($oldItemPatientworkannexInfoIdData)){
//                                    $notCheckData[$count] = $itemIdentificationresultchangeDataValue;
//                                    continue;//return false;
//                                }
//
//                                //查询老数据附件
//                                $oldItemPatientworkannexInfoIdDatas = implode(',',array_column($oldItemPatientworkannexInfoIdData,'info_id'));
//                                $oldItemPatientworkfileData = $this->LocalService()->itemIdentificationresult->dbData('oa_item_patientworkfile','is_del=0  and id in('.$oldItemPatientworkannexInfoIdDatas.')','patientwork_id');
//                                if(empty($oldItemPatientworkfileData)){
//                                    $notCheckData[$count] = $itemIdentificationresultchangeDataValue;
//                                    continue;
//                                }
//                                $oldItemPatientworkfileDatas = implode(',',array_column($oldItemPatientworkfileData,'patientwork_id'));
//                                $oldItemPatientworkData = $this->LocalService()->itemIdentificationresult->dbData('oa_item_patientwork','is_del=0 and  is_opener=1 and id in('.$oldItemPatientworkfileDatas.')','id');
//                                if(empty($oldItemPatientworkData)){
//                                    $notCheckData[$count] = $itemIdentificationresultchangeDataValue;
//                                    continue;
//                                }
//                                echo '要补充附件个数'.$i. PHP_EOL;
//                                $i++;
////                            echo "检查的正在处理第{$count}个" . PHP_EOL;
//                            }
//                        }



                        $itemSignatoryIdData[$itemIdentificationresultchangeDataKey]['item_id'] = $itemIdentificationresultchangeDataValue['item_id'];
                        $itemSignatoryIdData[$itemIdentificationresultchangeDataKey]['itemsig_id'] = $itemIdentificationresultchangeDataValue['itemsig_id'];
                        $workArr = [
                            'annex_title'=>'',//======
                            'annex_type'=>$itemIdentificationresultchangeDataValue['annex_type'],
                            'annex_path'=>$itemIdentificationresultchangeDataValue['annex_path'],
                            'confirm_state'=>1,
                            'ocr_state'=>1,
                            'lock_state'=>1,
                            'ocr_id'=>$itemIdentificationresultchangeDataValue['ocr_id'],
                            'item_id'=>$itemIdentificationresultchangeDataValue['item_id'],
                            'itemsig_id'=>$itemIdentificationresultchangeDataValue['itemsig_id'],
                            'patient_id'=>$itemIdentificationresultchangeDataValue['patient_id'],
                            'checktime_id'=>$itemIdentificationresultchangeDataValue['checktime_id'],
                            'researchstage_id'=>$itemIdentificationresultchangeDataValue['researchstage_id'],
                            'form_id'=>$itemIdentificationresultchangeDataValue['form_id'],
                            'collect_date'=>$itemIdentificationresultchangeDataValue['collect_date'],
//                        'patientchecktime_id'=>$itemIdentificationresultchangeDataValue['annex_title'],
                            'category_id'=>$itemIdentificationresultchangeDataValue['category_id'],//$item['newCategoryId'],
                            'is_result'=>1,
                            'patient_form_id'=>$itemIdentificationresultchangeDataValue['patient_form_id'],
                            'report_type'=>$itemIdentificationresultchangeDataValue['report_type'],
                            'change_type'=>1,
                            'update_user_id'=>0,
                            'create_user_id'=>0,
                            'up_annex_date'=>$itemIdentificationresultchangeDataValue['create_time']?:0,
                            'create_time'=>$itemIdentificationresultchangeDataValue['create_time']?:0,

                        ];
                        if (!empty($itemIdentificationresultchangeDataValue['annex_path'])){
                            $annexPath = explode(',',$itemIdentificationresultchangeDataValue['annex_path']);
                            foreach ($annexPath as $annexPathKey=>$annexPathValue){
                                $newPath = explode('path=',$annexPathValue);
                                $newPathWork = end($newPath);
                                $pathArr = explode('/',$newPathWork);
                                $workArr['annex_title'] = end($pathArr);
                                $workArr['annex_path']=$newPathWork;
                                $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->save($workArr);
                                $count++;
                                echo "正在处理第{$count}个" . PHP_EOL;
                            }
                        }else{
                            $count++;
                            echo "正在处理第{$count}个" . PHP_EOL;
                            $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->save($workArr);
                        }

                    }

                }
            }

//        }
//        echo '<pre>';print_r($notCheckData).PHP_EOL;
        echo $count.PHP_EOL;
//        echo '<pre>';print_r($itemSignatoryIdData);die;

        return $count;
        echo '<pre>';print_r($itemIdentificationresultchangeData);die;

    }

    public function updateCategory($item = []){
        if(empty($item)){
            echo '参数为空';die;
        }
        $redis = Laminas::$serviceManager->redisExtend->setDatabase(6)->getRedisInstance();
        $itemFormNameArr = $this->LocalService()->itemForm->fetchCol('name','is_del=0 ');
        $wherePatientArr['where'] = ['is_del' => 0];
        $wherePatientArr['columns'] = ['id','patient_name','patient_number','item_id'];
        $patientData = $this->LocalService()->patient->fetchAll($wherePatientArr);//$item_id
        $patientNameArr = [];
        if(!empty($patientData)){
            foreach ($patientData as $patientDataKey=>$patientDataValue) {
                $patientNameArr[$patientDataValue['id']] = $patientDataValue;
            }
        }
        $whereItemInfo['where'] = ['is_del' => 0];
        $whereItemInfo['columns'] = ['id','name','fid'];
        $itemData = $this->LocalService()->itemInfo->fetchAll($whereItemInfo);
        $itemDatas = [];
        foreach ($itemData as $itemDataKey=>$itemDataValue){
            $itemDatas[$itemDataValue['id']] = $itemDataValue;
        }
        $updateChangeArr = [];
        $whereItemPatientworkannex['where'] =  'is_del=0  and lock_state = 1   and annex_type !=2  and category_id='.$item['oldCategory_id'].' and item_id ='.$item['item_id'];
        $whereItemPatientworkannex['group'] = ['checktime_id','patient_form_id','form_id'];
        $whereItemPatientworkannex['columns'] = ['id','checktime_id','patient_form_id','form_id','itemsig_id','patient_id','category_id','item_id'];
        $whereItemPatientworkannex['order'] = ['id desc'];
        $itemPatientworkannexData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);

        if (!empty($itemPatientworkannexData)){
            foreach ($itemPatientworkannexData as $itemPatientworkannexDataKey=>&$itemPatientworkannexDataValue) {
                echo "正在处理第{$itemPatientworkannexDataKey}个==分类id：".$item['oldCategory_id'] . PHP_EOL;
                $category_id = $this->LocalService()->itemForm->getOneFieldVal('checklist_id',"item_id = ".$itemPatientworkannexDataValue['item_id'] ." and is_del = 0 and id = ".$itemPatientworkannexDataValue['form_id']);
                $whereItemCheckname['where'] = [
                    'is_del' => 0,
                    'category_id' => $category_id,
                    'item_id' => $itemPatientworkannexDataValue['item_id'],
                ];
                $whereItemCheckname['columns'] = ['id','item_id','category_id','name','checkname_id'];
                $itemChecknameInfo = $this->LocalService()->itemCheckname->fetchOne($whereItemCheckname);
                $itemChecknameData = $this->LocalService()->itemCheckname->fetchAll($whereItemCheckname);

                if (!empty($patientNameArr) && isset($patientNameArr[$itemPatientworkannexDataValue['patient_id']]) ){
                    $patient_name = $patientNameArr[$itemPatientworkannexDataValue['patient_id']]['patient_name'];
                    $patient_number = $patientNameArr[$itemPatientworkannexDataValue['patient_id']]['patient_number'];
                    $patientNameNumber = '';
                    if (!empty($patient_number)) $patientNameNumber = '【'.$patient_number.'】';
                    if (!empty($patient_name)) $patientNameNumber .= $patient_name;
                    $itemPatientworkannexDataValue['patient_name'] = $patientNameNumber;
                }
                if (!empty($itemFormNameArr) && isset($itemFormNameArr[$itemPatientworkannexDataValue['form_id']]) ){
                    $itemPatientworkannexDataValue['form_name'] = $itemFormNameArr[$itemPatientworkannexDataValue['form_id']];
                }
                if (!empty($itemDatas) && isset($itemDatas[$itemPatientworkannexDataValue['item_id']]) ){
                    $itemInfo = $this->LocalService()->itemInfo->fetchCol('name','is_del=0 and id='.$itemDatas[$itemPatientworkannexDataValue['item_id']]['fid']);
                    $itemPatientworkannexDataValue['item_b_name'] = array_values($itemInfo)[0];
                    $itemPatientworkannexDataValue['item_s_name'] = $itemDatas[$itemPatientworkannexDataValue['item_id']]['name'];
                }

                $whereItemIdentificationresultchange['where'] = [
                    'is_del' => 0,
                    'is_annul' => 0,
                    'checktime_id' => $itemPatientworkannexDataValue['checktime_id'],
                    'patient_form_id' => $itemPatientworkannexDataValue['patient_form_id'],
                    'item_id' => $itemPatientworkannexDataValue['item_id'],
                ];

                $whereItemIdentificationresultchange['columns'] = ['id','item_checkname_id','item_name','result','is_normal_type'];
                $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchOne($whereItemIdentificationresultchange);
                $itemIdentificationresultchangeDatas = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
                if(!empty($itemIdentificationresultchangeDatas)){
                    $itemPatientworkannexDataValue['itemCheckName'] = $itemChecknameData;
                    $itemPatientworkannexDataValue['itemChangeCheckName'] = $itemIdentificationresultchangeDatas;

                     if($itemPatientworkannexDataValue['category_id'] == $itemChecknameInfo['category_id']){
                        unset($itemPatientworkannexData[$itemPatientworkannexDataKey]);
                        continue;
                    }

                    $updateChangeArr[$itemPatientworkannexDataKey]['item_id'] = $itemChecknameInfo['item_id'];
                    $updateChangeArr[$itemPatientworkannexDataKey]['form_id'] = $itemPatientworkannexDataValue['form_id'];
                    $updateChangeArr[$itemPatientworkannexDataKey]['oldCategory_id'] = $itemPatientworkannexDataValue['category_id'];
                    $updateChangeArr[$itemPatientworkannexDataKey]['newCategoryId'] = $itemChecknameInfo['category_id'];
                    $updateChangeArr[$itemPatientworkannexDataKey]['newCheckName'] = $itemChecknameInfo['name'];
                    $updateChangeArr[$itemPatientworkannexDataKey]['newCheckId'] = $itemChecknameInfo['id'];
                    $updateChangeArr[$itemPatientworkannexDataKey]['checkname_id'] = $itemChecknameInfo['checkname_id'];

                    $flag = 0;
                    foreach ($itemIdentificationresultchangeDatas as $itemIdentificationresultchangeDatasKey=>$itemIdentificationresultchangeDatasValue){
                        if(!empty($itemIdentificationresultchangeDatasValue['result']) && !empty($itemIdentificationresultchangeDatasValue['is_normal_type'])){
                            $updateChangeArr[$itemPatientworkannexDataKey]['oldCheckName'] = $itemIdentificationresultchangeDatasValue['item_name'];
                            $updateChangeArr[$itemPatientworkannexDataKey]['oldCheckId'] = $itemIdentificationresultchangeDatasValue['item_checkname_id'];
                            $flag = 1;
                            continue;
                        }else if(!empty($itemIdentificationresultchangeDatasValue['result']) || !empty($itemIdentificationresultchangeDatasValue['is_normal_type'])){
                            $updateChangeArr[$itemPatientworkannexDataKey]['oldCheckName'] = $itemIdentificationresultchangeDatasValue['item_name'];
                            $updateChangeArr[$itemPatientworkannexDataKey]['oldCheckId'] = $itemIdentificationresultchangeDatasValue['item_checkname_id'];
                            $flag = 1;
                        }

                    }
                    if(empty($flag)){
                        $updateChangeArr[$itemPatientworkannexDataKey]['oldCheckName'] = $itemIdentificationresultchangeData['item_name'];
                        $updateChangeArr[$itemPatientworkannexDataKey]['oldCheckId'] = $itemIdentificationresultchangeData['item_checkname_id'];

                    }
                }

            }
        }

        if (!empty($updateChangeArr)) {
            $updateChangeStr = json_encode($updateChangeArr);
            $itemPatientworkannexDataStr = json_encode($itemPatientworkannexData);
            $redis->set('newitemCheckNamePatchDataStrLine-'.$item['item_id'].'-'.$item['oldCategory_id'],$updateChangeStr);
            $redis->set('newitemChangeAndCheckNamePatchDataStrLine-'.$item['item_id'].'-'.$item['oldCategory_id'],$itemPatientworkannexDataStr);
            foreach ($updateChangeArr as $key=>$value){
                $this->delChangeCSCheckNameData($value);
            }
            echo "处理成功" . PHP_EOL;
        }
        return true;
        echo $updateChangeStr;die;
    }


    public function sendChangLockData($whereData = []){

        $whereItemChangesendlog['where'] = [
            'is_del' => 0,
            'type' => $whereData['type'],
            'item_id' => $whereData['item_id'],
            'patient_id' => $whereData['patient_id'],
            'checktime_id' => $whereData['checktime_id'],
            'patient_form_id' => $whereData['patient_form_id'],
        ];
        $whereItemChangesendlog['order'] = ['id DESC'];
        $itemChangesendlogInfo = $this->LocalService()->itemChangesendlog->fetchOne($whereItemChangesendlog);
        $transactionType = 'Insert';
        !empty($itemChangesendlogInfo) && $transactionType = 'Update';
        $sendData = $this->selectChangCheckName($whereData);
        $checkNameId = implode(',', array_keys($sendData['sendData']));

        $xml = new LaboratoryXmlGenerator();
        $xml->setHeader([
            [
                'key' => 'LBYN_',
                'value' => $whereData['type'], // 0 fou 1 shi
                'transactionType' => $transactionType, // 0 fou 1 shi
                'id' => $checkNameId
            ],
            [
                'key' => 'LBDAT_',
                'value' => $whereData['type']==2 ? '' : $sendData['collect_date'], // 2 fou 1 shi
                'transactionType' => $transactionType, // 0 fou 1 shi
            ],
        ]);
        $xml->setPatientId($whereData['patient_id']);
        $xml->setFormId($whereData['form_id']);
        $xml->setCheckTimeId($whereData['checktime_id']);
        $xml->setItemSignId($whereData['itemsig_id']);
        $xml->setItemId($whereData['item_id']);
        $sendData = $xml->setContent($sendData['sendData']);
//        echo '<pre>';print_r($sendData);die;
        return $sendData;
    }

    //数据查询
    public function selectChangCheckName($whereData = []){
        $item_id = $whereData['item_id'];
        $checktime_id = $whereData['checktime_id'];
        $patient_form_id = $whereData['patient_form_id'];
        $patient_id = $whereData['patient_id'];
        $category_id = $whereData['category_id'];
        $sendData = [];
        $itemChecknameStatusData = [];
        $redisKey = 'sendChangeCheckNeme:'.$whereData['item_id'].'-'.$whereData['itemsig_id'].'-'.$whereData['checktime_id'].'-'.$whereData['patient_form_id'].'-'.$whereData['form_id'].'-'.$whereData['category_id'].'-'.$whereData['patient_id'].'-'.$whereData['type'];
        $report_type = 0;
        $whereDictionaryCheckcategory['where'] = [
            'is_del' => 0,
            'id' => $category_id,
        ];
        $dictionaryCheckcategoryInfo = $this->LocalService()->dictionaryCheckcategory->fetchOne($whereDictionaryCheckcategory);
        if(!empty($dictionaryCheckcategoryInfo) && !empty($dictionaryCheckcategoryInfo['report_type'])) $report_type = 1;
        if(!empty($whereData['type']) && $whereData['type'] == 1){
            $whereItemChangesendlogInfo['where'] = $whereItemChangesendlog['where'] = [
                'is_del' => 0,
                'type' => $whereData['type'],
                'item_id' => $item_id,
                'patient_id' => $patient_id,
                'checktime_id' => $checktime_id,
                'patient_form_id' => $patient_form_id
            ];
            if(isset($whereData['where_log_time']) && !empty($whereData['where_log_time'])) {
                $whereItemChangesendlogInfo['where']['create_time'] = $whereItemChangesendlog['where']['create_time'] = strtotime($whereData['where_log_time']);
            };
            $whereItemChangesendlogInfo['order'] = ['id DESC'];
            $itemChangesendlogInfo = $this->LocalService()->itemChangesendlog->fetchOne($whereItemChangesendlogInfo);
//            !empty($itemChangesendlogInfo['create_time']) && $whereItemChangesendlog['where'] .= ' and FROM_UNIXTIME(create_time ,"%Y-%m-%d")="'.date('Y-m-d',$itemChangesendlogInfo['create_time']).'"';
            if(!empty($itemChangesendlogInfo['create_time'])){
                $monthTime = strtotime('-1 month',$itemChangesendlogInfo['create_time']);
                $whereItemChangesendlog['where'] .= ' and create_time >='.$monthTime;
            }
            $whereItemChangesendlog['columns'] = ['id','change_id','item_id','is_normal_type','result','item_name','reference_range_max','reference_range_min','unit','patient_id','checktime_id','itemsig_id','category_id','patient_form_id','item_checkname_id'];
            $itemChangesendlogData = $this->LocalService()->itemChangesendlog->fetchAll($whereItemChangesendlog);
            if (!empty($itemChangesendlogData)){
                $itemChecknameStatusData = array_unique(array_column($itemChangesendlogData,'change_id'));
            }
        }else{
            $whereItemChangesendlogInfo['where'] = $whereItemChangesendlog['where'] = [
                'is_del' => 0,
                'type' => $whereData['type'],
                'item_id' => $item_id,
                'patient_id' => $patient_id,
                'checktime_id' => $checktime_id,
                'patient_form_id' => $patient_form_id,

            ];
            if(isset($whereData['where_log_time']) && !empty($whereData['where_log_time'])){
                $whereItemChangesendlogInfo['where']['create_time'] = $whereItemChangesendlog['where']['create_time'] = strtotime($whereData['where_log_time']);
            };

            $whereItemChangesendlogInfo['order'] = ['id DESC'];
            $itemChangesendlogInfo = $this->LocalService()->itemChangesendlog->fetchOne($whereItemChangesendlogInfo);
//            !empty($itemChangesendlogInfo['create_time']) && $whereItemChangesendlog['where'] .= ' and FROM_UNIXTIME(create_time ,"%Y-%m-%d")="'.date('Y-m-d',$itemChangesendlogInfo['create_time']).'"';
            if(!empty($itemChangesendlogInfo['create_time'])){
                $monthTime = strtotime('-1 month',$itemChangesendlogInfo['create_time']);
                $whereItemChangesendlog['where'] .= ' and create_time >='.$monthTime;
            }
            $whereItemChangesendlog['columns'] = ['id','item_id','is_normal_type','result','item_name','reference_range_max','reference_range_min','unit','category_id','item_checkname_id'];
            $itemChangesendlogData = $this->LocalService()->itemChangesendlog->fetchAll($whereItemChangesendlog);
            if (!empty($itemChangesendlogData)){
                $itemChecknameStatusData = array_unique(array_column($itemChangesendlogData,'item_checkname_id'));
            }
        }
        if(!empty($whereData['type'])  && $whereData['type'] == 1){
            $whereName['where'] ='is_del=0 and category_id ='.$category_id.' and item_id='.$item_id;
            $itemChecknameDataArr = $this->LocalService()->itemCheckname->fetchAll($whereName);
            $itemChecknameDataArrs = array_column($itemChecknameDataArr,null,'id');
//            var_dump(array_keys($itemChecknameDataArrs));die;
            $whereItemIdentificationresultchange['where'] = [
                'is_del' => 0,
                'lock_state' => 1,
                'is_annul' => 0,
                'item_id' => $item_id,
                'patient_id' => $patient_id,
                'checktime_id' => $checktime_id,
                'patient_form_id' => $patient_form_id,
            ];
            $whereItemIdentificationresultchange['columns'] = ['change_id'=>'id','collect_date','item_id','form_id','is_normal_type','result','item_name','reference_range_max','reference_range_min','unit','patient_id','checktime_id','itemsig_id','category_id','patient_form_id','item_checkname_id'];
            $itemChecknameData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);

            $newCheckName = [];
            foreach ($itemChecknameData as $keys=>$values){
                if(isset($itemChecknameDataArrs[$values['item_checkname_id']])){
                    unset($itemChecknameDataArrs[$values['item_checkname_id']]);
                }
            }
            if (!empty($itemChecknameDataArrs)){
                foreach ($itemChecknameDataArrs as $checknamekeys=>$checknamevalues){
                    $newCheckName[$checknamekeys]['change_id'] = 0;
                    $newCheckName[$checknamekeys]['collect_date'] = '';
                    $newCheckName[$checknamekeys]['item_id'] = $item_id;
                    $newCheckName[$checknamekeys]['form_id'] = $itemChecknameData[0]['form_id'];
                    $newCheckName[$checknamekeys]['is_normal_type'] = '';
                    $newCheckName[$checknamekeys]['result'] = '';
                    $newCheckName[$checknamekeys]['item_name'] = $checknamevalues['name'];
                    $newCheckName[$checknamekeys]['reference_range_max'] = '';
                    $newCheckName[$checknamekeys]['reference_range_min'] = '';
                    $newCheckName[$checknamekeys]['unit'] = '';
                    $newCheckName[$checknamekeys]['patient_id'] = $patient_id;
                    $newCheckName[$checknamekeys]['itemsig_id'] = $itemChecknameData[0]['itemsig_id'];
                    $newCheckName[$checknamekeys]['category_id'] = $category_id;
                    $newCheckName[$checknamekeys]['patient_form_id'] = $patient_form_id;
                    $newCheckName[$checknamekeys]['item_checkname_id'] = $checknamevalues['id'];
                    $newCheckName[$checknamekeys]['operation'] =  'Update';
                }
            }
            $itemChecknameData = array_merge($itemChecknameData,$newCheckName);

            if (!empty($itemChecknameData)){
                $itemChecknameIdS = implode(',',array_filter(array_unique( array_column($itemChecknameData, 'item_checkname_id'))));
                !empty($itemChecknameIdS) && $itemChecknameArr = $this->LocalService()->itemCheckname->fetchCol('variable','is_del=0 and id in('.$itemChecknameIdS.')');
                foreach ($itemChecknameData as $itemChecknameDataKey => &$itemChecknameDataValue) {
                    $itemChecknameDataValue['item_variable'] = '';
                    if (isset($itemChecknameArr[$itemChecknameDataValue['item_checkname_id']])){
                        $itemChecknameDataValue['item_variable'] = $itemChecknameArr[$itemChecknameDataValue['item_checkname_id']];
                    }

                    $itemChecknameDataValue['operation'] =  in_array($itemChecknameDataValue['change_id'],$itemChecknameStatusData)?'Update':'Insert';
                }

            }
        }else{

            $whereItemCheckname['where'] = [
                'is_del' => 0,
                'item_id' => $item_id,
                'category_id' => $category_id
            ];
            $whereItemCheckname['columns'] = ['item_checkname_id'=>'id','item_id','category_id','item_name'=>'name','alias','unit','reference_range_max'=>'max_val','reference_range_min'=>'min_val','item_variable'=>'variable'];
            $itemChecknameData = $this->LocalService()->itemCheckname->fetchAll($whereItemCheckname);
            if (!empty($itemChecknameData)){
                foreach ($itemChecknameData as $itemChecknameDataKeys => &$itemChecknameDataValues) {
                    if(empty($itemChecknameDataValues['item_name'])){
                        $itemChecknameDataValues['item_name'] = $itemChecknameDataValues['alias'] ? $itemChecknameDataValues['alias']:'';
                    }
                    unset($itemChecknameDataValues['alias']);
                    $itemChecknameDataValues['is_normal_type'] = '';
                    $itemChecknameDataValues['result'] = '';
                    $itemChecknameDataValues['collect_date'] = '';
                    $itemChecknameDataValues['form_id'] = $whereData['form_id'];
                    $itemChecknameDataValues['checktime_id'] = $checktime_id;
                    $itemChecknameDataValues['itemsig_id'] = $whereData['itemsig_id'];
                    $itemChecknameDataValues['patient_id'] = $whereData['patient_id'];
                    $itemChecknameDataValues['patient_form_id'] = $whereData['patient_form_id'];
                    $itemChecknameDataValues['operation'] =  in_array($itemChecknameDataValues['item_checkname_id'],$itemChecknameStatusData)?'Update':'Insert';
                }

            }
        }
        if(!empty($itemChecknameData)){
            ArrayHelper::multisort($itemChecknameData,'item_checkname_id');
            $changeIds = '';
            if (isset($itemChecknameData[0]['change_id'])){
                $changeIds = implode(',',array_column($itemChecknameData,'change_id'));
            }
            $itemChecknameIds = implode(',',array_column($itemChecknameData,'item_checkname_id'));

            $redis = Laminas::$serviceManager->redisExtend->setDatabase(6)->getRedisInstance();
            $itemChecknameDataStr = json_encode($itemChecknameData);
            $result = $redis->set($redisKey,$itemChecknameDataStr);
            $str = str_replace('sendChangeCheckNeme:','',$redisKey);
            $whereData['sendRedisKey'] = $str;
            $whereData['changeIds'] = $changeIds;
            $whereData['itemChecknameIds'] = $itemChecknameIds;
            $sendRedisKey = 'sendChangeCheckNeme:'.date('Y-m-d').':'.$str;
            $whereDataJson = json_encode($whereData);
            $resultDate = $redis->set($sendRedisKey,$whereDataJson);
            $sendData = $this->changeArray($itemChecknameData,$report_type);
            if (!empty($sendData)){
                $sendData['whereData'] = $whereData;
            }
        }
        return $sendData;
    }

    //改数据
    public function changeArray($data = [],$report_type=0){
        $sendData = [];
        $isNormalTypeArr = ['','正常','cs','ncs'];
        $fieldArr = ['is_normal_type'=>'LBCLSIG','reference_range_max'=>'LBORNRHI','reference_range_min'=>'LBORNRLO','result'=>'LBORRES','unit'=>'LBORRESU'];
        $collect_date = '';
        foreach ($data as $key => &$value) {
            $check = [];
            $newItemVariables = '';
            $item_variable = '';
            if (!empty($value['item_variable'])){
                $item_variable = $value['item_variable'];
                $newItemVariableArr = explode('_',$item_variable);
                $newItemVariables = end($newItemVariableArr);
            }
            if (isset($value['collect_date']) && !empty($value['collect_date'])) $collect_date = date('Y-m-d',$value['collect_date']);

            $check[0]['itemOID'] = $item_variable;
            $check[0]['value'] =$value['item_name'];
            $check[0]['transactionType'] = $value['operation'];

            $check[1]['itemOID'] = $fieldArr['result'].'_'.$newItemVariables;
            $check[1]['value'] = $value['result'];//?:'';
            $check[1]['transactionType'] = $value['operation'];


            $check[2]['itemOID'] = $fieldArr['is_normal_type'].'_'.$newItemVariables;
            $check[2]['value'] = $isNormalTypeArr[$value['is_normal_type']];
            $check[2]['transactionType'] = $value['operation'];

            if(empty($report_type)){
                $check[3]['itemOID'] = $fieldArr['reference_range_min'].'_'.$newItemVariables;
                $check[3]['value'] = $value['reference_range_min'];//?:'';
                $check[3]['transactionType'] = $value['operation'];


                $check[4]['itemOID'] = $fieldArr['reference_range_max'].'_'.$newItemVariables;
                $check[4]['value'] = $value['reference_range_max'];//?:'';
                $check[4]['transactionType'] = $value['operation'];



                $check[5]['itemOID'] = $fieldArr['unit'].'_'.$newItemVariables;
                $check[5]['value'] = $value['unit'];//?:'';
                $check[5]['transactionType'] = $value['operation'];
            }



            $sendData[$value['item_checkname_id']] = $check;
        }
        $newSendData['collect_date'] = $collect_date;
        $newSendData['sendData'] = $sendData;

        return $newSendData;

    }

    //添加log
    public function insertItemChangesendlog($dataKey = []){
        $item_id = $dataKey['item_id'];
        $type = $dataKey['type'];
        $category_id = $dataKey['category_id'];
        $redis = Laminas::$serviceManager->redisExtend->setDatabase(6)->getRedisInstance();
        $redisKey = 'sendChangeCheckNeme:'.$dataKey['item_id'].'-'.$dataKey['itemsig_id'].'-'.$dataKey['checktime_id'].'-'.$dataKey['patient_form_id'].'-'.$dataKey['form_id'].'-'.$dataKey['category_id'].'-'.$dataKey['patient_id'].'-'.$dataKey['type'];
        $oldData = $redis->get($redisKey);
        $resultDel = $redis->del($redisKey);
        if(!empty($oldData)){
            $itemChecknameData = json_decode($oldData,1);
            if(!empty($itemChecknameData)){
                $err = [];
                $resultItemCheckname = 0;
                foreach ($itemChecknameData as $itemChecknameDataKey=>&$itemChecknameDataValue){
                    $itemChecknameDataValue['type'] = $type;
                    $itemChecknameDataValue['checktime_id'] = $dataKey['checktime_id'];
                    $resultItemCheckname = $this->LocalService()->itemChangesendlog->insert($itemChecknameDataValue);
                    if(empty($resultItemCheckname)){
                        $err[$itemChecknameDataKey] = $itemChecknameDataValue;
                    }
                }
                if(!empty($err)){
                    $resultSet = $redis->set($redisKey,json_encode($err));
                }
            }
        }

        return true;
    }

    //是否可补图片
    public function checKRepairImg($parameter){
        $item_id = $parameter['item_id'];
        $patient_form_id = $parameter['patient_form_id'];
        $checktime_id = $parameter['checktime_id'];

//        $patient_form_id = 146969;//$_POST['patient_form_id'] ?: 0;
//        $checktime_id = 527;//$_POST['checktime_id'] ?: 0;
//        $item_id = 97;//$_POST['item_id'] ?: 0;
        if (empty($checktime_id) || empty($patient_form_id) || empty($item_id)) {
            //参数不正确
            return 1;
        }

        ///and annex_type != 4 补单直接锁定，没有预览
        $whereItemIdentificationresultchange['where'] = [
            'is_del' => 0,
            'patient_form_id' => $patient_form_id,
            'checktime_id' => $checktime_id,
        ];

        $whereItemPatientworkannex['where'] = $whereItemIdentificationresultchange['where'];
        $whereItemPatientworkannex['columns'] = ['id','annex_type','change_type'];
        $itemPatientworkannexChangeType = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);
        if(empty($itemPatientworkannexChangeType)){
            //未查到附件。。。
            return 1;
        }else{
            //一次可补多张
            foreach ($itemPatientworkannexChangeType as $itemPatientworkannexChangeTypeK=>$itemPatientworkannexChangeTypeV){
                if ($itemPatientworkannexChangeTypeV['annex_type'] == 5){
                    //医嘱不能补单
                    return 1;
                }
//                if ($itemPatientworkannexChangeTypeV['annex_type'] == 4 && $itemPatientworkannexChangeTypeV['change_type'] == 0){
//                    //已有补单，还未锁定不可再补------ 一次只能补一张暂时
//                    return 1;
//                }
//                if ($itemPatientworkannexChangeTypeV['annex_type'] == 3){
//                    //有手动填写的不能补单
//                    return 1;
//                }
            }

        }

        $whereItemIdentificationresultchange['columns'] =['id','item_checkname_id','lock_state','category_id'];
        $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
        if(empty($itemIdentificationresultchangeData)){
            //未查找到锁定指标数据
            return 1;
        }else{
            if(in_array(0,array_column($itemIdentificationresultchangeData,'lock_state'))){
                //此单未锁定，不能补单
                return 1;
            }
        }
        $category_id = array_column($itemIdentificationresultchangeData,'category_id')[0];
        //项目检查项名称设置表
        $whereItemCheckname['where'] = [
            'is_del' => 0,
            'item_id' => $item_id,
            'category_id' => $category_id
        ];
        $whereItemCheckname['columns'] = ['id','name'];
        $itemChecknameData = $this->LocalService()->itemCheckname->fetchAll($whereItemCheckname);
        if(empty($itemChecknameData)){
            //未查找到指标数据
            return 1;
        }

        $itemChecknameIdArr = array_filter(array_unique(array_column($itemIdentificationresultchangeData,'item_checkname_id')));
        if(count($itemChecknameData) == 0) {
            //没查到指标
            return 1;
        }
        if(count($itemChecknameIdArr) == 0) {
            //锁定的指标没有查到
            return 1;
        }
        if(count($itemChecknameData) == count($itemChecknameIdArr)){
            //指标数据已全不能再补
            return 1;
        }
        return 2;

    }

    //重新识别
    public function reidentification($id = 0)
    {
        if (empty($id)) {
            return false;
        }
        $whereItemPatientworkannex['where'] = [
            'is_del' => 0,
            'id' => $id
        ];
        $itemPatientworkannexInfo = $this->LocalService()->itemPatientworkannex->fetchOne($whereItemPatientworkannex);
        if (empty($itemPatientworkannexInfo)) {
            return false;
        }
        $whereItemIdentificationresult['where'] = [
            'is_del' => 0,
            'workannex_id' => $id,
        ];
        $itemIdentificationresultInfo = $this->LocalService()->itemIdentificationresult->fetchOne($whereItemIdentificationresult);

        $cacheOcrId = $this->LocalService()->itemIdentificationresult->getOcrTemplateCache($itemPatientworkannexInfo);
        !empty($cacheOcrId) && $itemPatientworkannexInfo['ocr_id'] = $cacheOcrId;

        //识别模板设置数据
        $whereDictionaryOcr['where'] = [
            'is_del' => 0,
            'id' => $itemPatientworkannexInfo['ocr_id']
        ];
        $whereDictionaryOcr['columns'] = ['id','name','key_val','separator'];
        $dictionaryOcrInfo = $this->LocalService()->dictionaryOcr->fetchOne($whereDictionaryOcr);

        if (empty($dictionaryOcrInfo)){
            return false;
        }
        if (empty($dictionaryOcrInfo['key_val'])){
            return false;
        }
        if (empty($dictionaryOcrInfo['separator'])){
            return false;
        }

        $dictionarySetocrfieldData = $this->LocalService()->dictionarySetocrfield->getAllGroupType();
        $imgPath =  Oss::getUploadDomain().$itemPatientworkannexInfo['annex_path'];
        $result = Ocr::ocr_result($imgPath, $dictionaryOcrInfo['key_val'], $dictionaryOcrInfo['separator'], $dictionarySetocrfieldData);
        if ($result['error_code'] != 0) {
            return false;
        }

        $upWorkannex['ocr_state'] = 1;
        $upWorkannex['is_result'] = 1;
        $upWorkannex['ocr_id'] = $itemPatientworkannexInfo['ocr_id'];
        $upWorkannex['id'] = $id;
        $upWorkannex['lock_state'] = 1;
        $resultItemPatientworkannex = $this->LocalService()->itemPatientworkannex->save($upWorkannex);
        $arr['content'] = json_encode($result);
        $arr['workannex_id'] = $id;
        if (!empty($itemIdentificationresultInfo)){
            $id = $arr['id'] = $itemIdentificationresultInfo['id'];
            $resultItemIdentificationresult = $this->LocalService()->itemIdentificationresult->save($arr);
            return true;

        }else{
            $id = $this->LocalService()->itemIdentificationresult->save($arr);
            return true;

        }


    }


    public function checkNameIds($parameter){

        $item_id = $parameter['item_id'];
        $patient_form_id = $parameter['patient_form_id'];
        $checktime_id = $parameter['checktime_id'];
        $category_id = $parameter['category_id'];
        $patient_id = $parameter['patient_id'];
        $itemsig_id = $parameter['itemsig_id'];
        $type = $parameter['type']?1:0;
        //and annex_type != 4===and lock_state = 1
        //// 同一个分类id，同一个检查点id，同一个人===change_type=0
        $whereItemIdentificationresultchangeAnnexType['where'] = [
            'is_del' => 0,
            'annex_type' => 4,
            'patient_form_id' => $patient_form_id,
            'checktime_id' => $checktime_id,
            'formcontent_id' => $parameter['patientformcontent_id'] ?? 0,
        ];
        $itemIdentificationresultchangeDataAnnexType = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemIdentificationresultchangeAnnexType);

        $whereItemIdentificationresultchange['where'] = [
            //'is_del' => 0,
            'category_id' => $category_id,
            'checktime_id' => $checktime_id,
            'item_id' => $item_id,
            'patient_id' => $patient_id,
            'itemsig_id' => $itemsig_id,
            'patientformcontent_id' => $parameter['patientformcontent_id'] ?? 0,
        ];

        if(empty($itemIdentificationresultchangeDataAnnexType)){
            $whereItemIdentificationresultchange['where']['is_annul'] = 1;
        }
        !empty($type) && $whereItemIdentificationresultchange['where']['lock_state'] = 1;
        $whereItemIdentificationresultchange['columns'] = ['id', 'item_checkname_id', 'is_identification', 'item_name'];
        $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemIdentificationresultchange);
        if(empty($itemIdentificationresultchangeData)){
            return [];
        }

        $itemChecknameIdArr = $isIdentificationChecknameIdArr = [];
        foreach($itemIdentificationresultchangeData as &$itemIdentificationresultchangeDatum) {
            $itemChecknameIdArr[] = $itemIdentificationresultchangeDatum['item_checkname_id'];
            if($itemIdentificationresultchangeDatum['is_identification']) {
                $isIdentificationChecknameIdArr[] = $itemIdentificationresultchangeDatum['item_checkname_id'];
            }
        }



        //项目检查项名称设置表
        $whereItemCheckname['where'] = [
            'is_del' => 0,
            'item_id' => $item_id,
            'category_id' => $category_id,
        ];
        $whereItemCheckname['columns'] = ['id','name','alias','checkname_id','unit','max_val','min_val','variable','check_type','min_range','max_range','min_symbol','max_symbol'];
        $itemChecknameData = $this->LocalService()->itemCheckname->fetchAll($whereItemCheckname);
        if(empty($itemChecknameData)){
            return [];
        }

        $newItemChecknameData = [];
        foreach ($itemChecknameData as $key=>$value){
            if(empty($itemIdentificationresultchangeDataAnnexType)){
                if(in_array($value['id'],$itemChecknameIdArr)){
                    $newItemChecknameData[] = $value;
                }
            }else{
                // 补图，只显示未查的指标
                if( in_array($value['id'], $isIdentificationChecknameIdArr) || !in_array($value['id'], $itemChecknameIdArr)){
                    $newItemChecknameData[] = $value;
                }
            }

        }
        return $newItemChecknameData;

    }


    public function getRelationArr($where)
    {
        $res = [];
        $pic_data                    = []; //存储化验单图片 键为项目ID_中心ID_受试者ID_检查点ID_表单ID
        //查询对应的化验单附件表
        $whereItemPatientworkannex = [
            'where' =>'is_del=0',
            'columns' =>['id','patient_form_id','item_id', 'itemsig_id', 'patient_id','checktime_id','annex_path'],
            'order'   => ['patient_id', 'checktime_id', 'form_id']
        ];
        $itemPatientworkannexImgData = $this->LocalService()->itemPatientworkannex->fetchAll($whereItemPatientworkannex);
        if(!empty($itemPatientworkannexImgData)){
            foreach ($itemPatientworkannexImgData as $itemPatientworkannexImg){
                $keys = $itemPatientworkannexImg['item_id'] . '_' . $itemPatientworkannexImg['itemsig_id'] . '_' . $itemPatientworkannexImg['patient_id'] . '_' . $itemPatientworkannexImg['checktime_id'] . '_' . $itemPatientworkannexImg['patient_form_id'];
                $pic_data[$keys][]                    = $itemPatientworkannexImg['annex_path'];
                $pic_data[$keys]                      = array_unique($pic_data[$keys]);
            }
        }


        $whereCahangeArr        = [
            'where'   => $where,
            'columns' => ['id', 'item_id', 'itemsig_id', 'patient_id', 'is_normal_type', 'annex_path', 'form_id', 'checktime_id','item_name','item_unit','item_min_val','item_max_val','lock_state_small','result','min_range','max_range'],
            'order'   => ['patient_id', 'checktime_id', 'form_id']
        ];
        $identification_results = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereCahangeArr);
        //按照检查点、检查点表单顺序查询识别结果表 根据item_id itemsig_id  patient_id  checktime_id form_id  is_del = 0  lock_state = 1[已锁定的数据]  查询识别结果 查询
        $patient_checktime_form_data = [];
        if (!empty($identification_results)) {
            foreach ($identification_results as $result) {
                $key = $result['item_id'] . '_' . $result['itemsig_id'] . '_' . $result['patient_id'] . '_' . $result['checktime_id'] . '_' . $result['form_id'];
                if(in_array($result['is_normal_type'],[2,3])){
                    $patient_checktime_form_data[$key][] = $result;
                }
            }

            $res['pic_data'] = $pic_data;
            $res['patient_checktime_form_data'] = $patient_checktime_form_data;
        }
        return $res;
    }


    /**
     * Notes: 统计异常值数据
     * @param
     * @return
     * @author haojinhua
     * @date 2024-06-05
     */
    public function fetchtotalNum($where){
        $item_arr = $itemsig_arr = $patient_arr = $categort_arr = [];
        $whereCahangeArr        = [
            'where'   => $where,
            'columns' => ['id','item_id','category_id','is_sure','patient_id','itemsig_id'],
            'order'   => ['item_id', 'itemsig_id', 'patient_id','category_id']
        ];
        $identification_results = $this->fetchAll($whereCahangeArr);
        if(!empty($identification_results)){
            foreach ($identification_results as $identification_result){
                $item_id     = $identification_result['item_id'];
                $itemsig_id  = $identification_result['itemsig_id'];
                $patient_id  = $identification_result['patient_id'];
                $category_id = $identification_result['category_id'];
                $is_sure     = $identification_result['is_sure'];
                if($is_sure == 0){
                    //未处理的异常
                    $item_arr[$item_id]['nodeal'][] = $identification_result['id'];
                    $itemsig_arr[$item_id][$itemsig_id]['nodeal'][] = $identification_result['id'];
                    $patient_arr[$item_id][$itemsig_id][$patient_id]['nodeal'][] = $identification_result['id'];
                    $categort_arr[$item_id][$itemsig_id][$patient_id][$category_id]['nodeal'][] = $identification_result['id'];
                }else{
                    //已处理的异常
                    $item_arr[$item_id]['deal'][] = $identification_result['id'];
                    $itemsig_arr[$item_id][$itemsig_id]['deal'][] = $identification_result['id'];
                    $patient_arr[$item_id][$itemsig_id][$patient_id]['deal'][] = $identification_result['id'];
                    $categort_arr[$item_id][$itemsig_id][$patient_id][$category_id]['deal'][] = $identification_result['id'];
                }

            }
        }
        unset($identification_results);
        return [$item_arr,$itemsig_arr,$patient_arr,$categort_arr];
    }

    /**
     * Notes: 表单锁定后添加开启CS/AE的表单内容至CS表进行异常值判断
     * User: lltyy
     * DateTime: 2024/6/27 15:52
     *
     * @param array $info
     * @return int
     */
    public function saveFormCs($info = []){
        $item_id = isset($info['item_id']) && !empty($info['item_id']) ? $info['item_id'] : 0;
        $itemsig_id = isset($info['itemsig_id']) && !empty($info['itemsig_id']) ? $info['itemsig_id'] : 0;
        $patient_id = isset($info['patient_id']) && !empty($info['patient_id']) ? $info['patient_id'] : 0;
        $checktime_id = isset($info['checktime_id']) && !empty($info['checktime_id']) ? $info['checktime_id'] : 0;
        $patientchecktime_id = isset($info['patientchecktime_id']) && !empty($info['patientchecktime_id']) ? $info['patientchecktime_id'] : 0;
        $form_datas = isset($info['form_data']) && !empty($info['form_data']) ? $info['form_data'] : [];
        if(!empty($form_datas)){
            //获取患者阶段ID
            $patientchecktime_where = 'is_del = 0 and patient_id = '.$patient_id;
            if(!empty($patientchecktime_id)){
                $patientchecktime_where .= ' and id = '.$patientchecktime_id;
            }else{
                $patientchecktime_where .= ' and checktime_id = '.$checktime_id;
            }
            $patientChecktimeData = $this->LocalService()->itemPatientchecktime->fetchOne(['where'=>$patientchecktime_where,'columns'=>['id','researchstage_id']]);
            unset($patientchecktime_where);
            $researchstage_id = !empty($patientChecktimeData) ? $patientChecktimeData['researchstage_id'] : 0;
            if(empty($patientchecktime_id)){
                $patientchecktime_id = !empty($patientChecktimeData) ? $patientChecktimeData['id'] : 0;
            }
            unset($patientChecktimeData);
            //获取患者姓名
            $user_name = $this->LocalService()->patient->getOneFieldVal('patient_name','is_del = 0 and id = '.$patient_id);
            //获取表单ID
            $form_arr = array_values(array_keys($form_datas));
            //获取表单类型【0 一对一  1 一对多】
            $form_type_arr = $this->LocalService()->itemForm->fetchCol('type','is_del = 0 and id in ('.implode(',',$form_arr).')');
            //获取患者阶段检查点管理表单ID
            $patient_form_datas = $this->LocalService()->patientForm->fetchDataByKey('is_del = 0 and patient_id = '.$patient_id.' and patientchecktime_id = '.$patientchecktime_id.' and form_id in ('.implode(',',$form_arr).')',['id','form_id'],['id'],'form_id',0);
            $time_patient_form_datas = $this->LocalService()->patientForm->fetchDataByKey('is_del = 0 and patient_id = '.$patient_id.' and checktime_id = '.$checktime_id.' and form_id in ('.implode(',',$form_arr).')',['id','form_id'],['id'],'form_id',0);
            //获取表单项目检查项信息
            $check_info = $this->LocalService()->itemCheckname->fetchDataByKey('is_del = 0 and form_id in ('.implode(',',$form_arr).') and item_id = '.$item_id,['id','form_field_id','category_id','checkname_id'],['id'],'form_field_id',0);
            //获取表单下开启CS/AE的表单内容
            $filedDatas = $this->LocalService()->itemFormField->fetchDataByKey('is_del = 0 and item_id = '.$item_id.' and form_id in ('.implode(',',$form_arr).') and is_csae = 1',['id','form_id','name','var_name','type'],'id',0);

            if(!empty($filedDatas)){
                //获取选项值
                $form_select_arr = [];
                $select_value_arr = $this->LocalService()->itemFormFieldRadio->fetchDataByKey('form_id in ('.implode(',',$form_arr).')',['value','field_id'],'field_id',0);
                if(!empty($select_value_arr)){
                    //判断获取是否有选择表单内容
                    $selectFiledArr = array_values(array_keys($filedDatas));
                    $field_select_arr = $this->LocalService()->itemFormField->fetchDataByKey('is_del = 0 and parent in ('.implode(',',$selectFiledArr).')',['id','parent','name'],'parent',1);
                    unset($selectFiledArr);
                    foreach($field_select_arr as $field_select_parent=>$field_selects){
                        foreach($field_selects as $field_select){
                            $field_select_id = $field_select['id'];
                            $field_select_value = isset($select_value_arr[$field_select_id]) && isset($select_value_arr[$field_select_id]['value']) ? $select_value_arr[$field_select_id]['value'] : '';
                            $form_select_arr[$field_select_parent][$field_select_value] = $field_select['name'];
                        }
                        unset($field_select_arr[$field_select_parent]);
                    }
                    unset($field_select_arr);
                }
                $form_select_field = !empty($form_select_arr) ? array_values(array_keys($form_select_arr)) : [];

                //**********************************源数据ID、及AE状态**********************************
//                $changResultDatas = $this->fetchAll([
//                    'where'=>'is_del = 0 and patient_id = '.$patient_id.' and checktime_id = '.$checktime_id.' and form_id in ('.implode(',',$form_arr).')',
//                    'columns'=>['id','is_normal_type','patientformcontent_id']
//                ]);
//
//                $changResultIndexDatas = ArrayHelper::index($changResultDatas,'patientformcontent_id');
                //**********************************源数据ID、及AE状态**********************************


                foreach($filedDatas as $filedId=>$filedData){
                    $form_id = $filedData['form_id'];

                    //表单类型
                    $form_type = isset($form_type_arr[$form_id]) && !empty($form_type_arr[$form_id]) ? $form_type_arr[$form_id] : 0;
                    //患者阶段检查点表单ID
                    $patient_form_id = isset($patient_form_datas[$form_id]) && isset($patient_form_datas[$form_id]['id']) && !empty($patient_form_datas[$form_id]['id']) ? $patient_form_datas[$form_id]['id'] : 0;
                    if(empty($patient_form_id)){
                        $patient_form_id = isset($time_patient_form_datas[$form_id]) && isset($time_patient_form_datas[$form_id]['id']) && !empty($time_patient_form_datas[$form_id]['id']) ? $time_patient_form_datas[$form_id]['id'] : 0;
                    }
                    //患者阶段检查点表单填写信息
                    $content_data = isset($form_datas[$form_id]) && isset($form_datas[$form_id]['content_data']) && !empty($form_datas[$form_id]['content_data']) ? $form_datas[$form_id]['content_data'] : [];
                    //表单对应的检查项分类ID
                    $check_category_id = isset($check_info[$filedId]) && isset($check_info[$filedId]['category_id']) && !empty($check_info[$filedId]['category_id']) ? $check_info[$filedId]['category_id'] : 0;
                    //表单内容对应的检查项ID
                    $checkname_id = isset($check_info[$filedId]) && isset($check_info[$filedId]['checkname_id']) && !empty($check_info[$filedId]['checkname_id']) ? $check_info[$filedId]['checkname_id'] : 0;
                    //表单内容对应的项目检查项ID
                    $item_checkname_id = isset($check_info[$filedId]) && isset($check_info[$filedId]['id']) && !empty($check_info[$filedId]['id']) ? $check_info[$filedId]['id'] : 0;
                    //echo $form_type.'=='.$filedData['name'].'=='.$filedId.'=='.$check_category_id."==".$checkname_id."==".$item_checkname_id."<br><br>";
                    if(!empty($content_data) && !empty($check_category_id) && !empty($checkname_id) && !empty($item_checkname_id)){

                        if($form_type == 1){//一对多
                            foreach($content_data as $content_key=>$content){
                                $patientformcontent_id = isset($content['patientformcontent_id']) && !empty($content['patientformcontent_id']) ? $content['patientformcontent_id'] : 0;
                                $content_value = isset($content[$filedId]) && $content[$filedId] != '' ? trim($content[$filedId]) : '';
                                $is_normal_type = 0;
                                $content_childData = isset($content['childData']) && !empty($content['childData']) ? json_decode($content['childData'],true) : [];
                                if(!empty($content_childData)){
                                    if(isset($content_childData[$filedId]) && !empty($content_childData[$filedId])){
                                        foreach($content_childData as $content_judgekey=>$content_judge){
                                            if($content_judge['field_id'] == $filedId){
                                                $content_value = isset($content[$content_judgekey]) && $content[$content_judgekey] != '' ? trim($content[$content_judgekey]) : '';
                                                $is_normal_type = $content_judge['normal_type'];
                                            }
                                        }
                                    }
                                }
                                unset($content_childData);
                                if($content_value != '' && !empty($patientformcontent_id)){
                                    //获取选项值
                                    if(in_array($filedId,$form_select_field)){
                                        $content_value_arr = explode(',',$content_value);
                                        $content_value_show = [];
                                        foreach($content_value_arr as $content_valueid){
                                            if(isset($form_select_arr[$filedId]) && isset($form_select_arr[$filedId][$content_valueid]) && !empty($form_select_arr[$filedId][$content_valueid])){
                                                $content_value_show[] = $form_select_arr[$filedId][$content_valueid];
                                            }
                                        }
                                        $content_value = !empty($content_value_show) ? implode('、',$content_value_show) : '';
                                        unset($content_value_arr);
                                        unset($content_value_show);
                                    }

                                    //源数据ID、及AE状态
//                                    $previousResult = $this->fetchOne([
//                                        'where'=>'is_del = 0 and patient_id = '.$patient_id.' and checktime_id = '.$checktime_id.' and form_id = '.$form_id.' and item_checkname_id = '.$item_checkname_id.' and patientformcontent_id = '.$patientformcontent_id,
//                                        'columns'=>['id','is_normal_type']
//                                    ]);

                                    //删除原数据重新新增
                                    $this->update(['is_del'=>1],'is_del = 0 and patient_id = '.$patient_id.' and checktime_id = '.$checktime_id.' and form_id = '.$form_id.' and item_checkname_id = '.$item_checkname_id.' and patientformcontent_id = '.$patientformcontent_id);
                                    $save_cs = [
                                        'is_normal_type'=>$is_normal_type,
                                        'lock_state_small'=>1,
                                        'flag_color'=>1,
                                        'result'=>$content_value,
                                        'item_name'=>$filedData['name'],
                                        'check_type'=>5,
                                        'patientworkannex_id'=>'',
                                        'checkname_id'=>$checkname_id,
                                        'item_id'=>$item_id,
                                        'itemsig_id'=>$itemsig_id,
                                        'patient_id'=>$patient_id,
                                        'checktime_id'=>$checktime_id,
                                        'researchstage_id'=>$researchstage_id,
                                        'user_name'=>$user_name,
                                        'item_variable'=>$filedData['var_name'],
                                        'form_id'=>$form_id,
                                        'category_id'=>$check_category_id,
                                        'lock_state'=>1,
                                        'patient_form_id'=>$patient_form_id,
                                        'item_checkname_id'=>$item_checkname_id,
                                        'item_name_old'=>$filedData['name'],
                                        'annex_path'=>'#',
                                        'report_type'=>0,
                                        'patientformcontent_id'=>$patientformcontent_id
                                    ];
                                    //echo "<pre>";
                                    //print_R($save_cs);exit;
                                    $currentSaveId = $this->save($save_cs);

//                                    $previousResult = $changResultIndexDatas[$patientformcontent_id];
//                                    if($previousResult['is_normal_type'] == 2 && $is_normal_type != 2){
//                                        $this->changeNormalType($previousResult,$is_normal_type,$currentSaveId);
//                                    }
                                    //释放空间
                                    unset($save_cs);
                                    unset($is_normal_type);
                                }
                                //释放空间
                                unset($content_value);
                                unset($patientformcontent_id);
                            }
                        }else{//一对一
                            $patientformcontent_id = isset($content_data['patientformcontent_id']) && !empty($content_data['patientformcontent_id']) ? $content_data['patientformcontent_id'] : 0;
                            $content_value = isset($content_data[$filedId]) && $content_data[$filedId] != '' ? $content_data[$filedId] : '';
                            $is_normal_type = 0;
                            $content_data_childData = isset($content_data['childData']) && !empty($content_data['childData']) ? json_decode($content_data['childData'],true) : [];

                            if(!empty($content_data_childData)){
                                foreach($content_data_childData as $content_data_judgekey=>$content_data_judge){
                                    if($content_data_judge['field_id'] == $filedId){
                                        $content_value = isset($content_data[$content_data_judgekey]) && $content_data[$content_data_judgekey] != '' ? trim($content_data[$content_data_judgekey]) : '';
                                        $is_normal_type = $content_data_judge['normal_type'];
                                    }
                                }
                            }
                            unset($content_data_childData);

                            if($content_value != '' && !empty($patientformcontent_id)){
                                //获取选项值
                                if(in_array($filedId,$form_select_field)){
                                    $content_value_arr = explode(',',$content_value);
                                    $content_value_show = [];
                                    foreach($content_value_arr as $content_valueid){
                                        if(isset($form_select_arr[$filedId]) && isset($form_select_arr[$filedId][$content_valueid]) && !empty($form_select_arr[$filedId][$content_valueid])){
                                            $content_value_show[] = $form_select_arr[$filedId][$content_valueid];
                                        }
                                    }
                                    $content_value = !empty($content_value_show) ? implode('、',$content_value_show) : '';
                                    unset($content_value_arr);
                                    unset($content_value_show);
                                }

                                //源数据ID、及AE状态
//                                $previousResult = $this->fetchOne([
//                                    'where'=>'is_del = 0 and patient_id = '.$patient_id.' and checktime_id = '.$checktime_id.' and form_id = '.$form_id.' and item_checkname_id = '.$item_checkname_id.' and patientformcontent_id = '.$patientformcontent_id,
//                                    'columns'=>['id','is_normal_type']
//                                ]);
                                //删除原数据重新新增
                                $this->update(['is_del'=>1],'is_del = 0 and patient_id = '.$patient_id.' and checktime_id = '.$checktime_id.' and form_id = '.$form_id.' and item_checkname_id = '.$item_checkname_id.' and patientformcontent_id = '.$patientformcontent_id);
                                $save_cs = [
                                    'is_normal_type'=>$is_normal_type,
                                    'lock_state_small'=>1,
                                    'flag_color'=>1,
                                    'result'=>$content_value,
                                    'item_name'=>$filedData['name'],
                                    'check_type'=>5,
                                    'patientworkannex_id'=>'',
                                    'checkname_id'=>$checkname_id,
                                    'item_id'=>$item_id,
                                    'itemsig_id'=>$itemsig_id,
                                    'patient_id'=>$patient_id,
                                    'checktime_id'=>$checktime_id,
                                    'researchstage_id'=>$researchstage_id,
                                    'user_name'=>$user_name,
                                    'item_variable'=>$filedData['var_name'],
                                    'form_id'=>$form_id,
                                    'category_id'=>$check_category_id,
                                    'lock_state'=>1,
                                    'patient_form_id'=>$patient_form_id,
                                    'item_checkname_id'=>$item_checkname_id,
                                    'item_name_old'=>$filedData['name'],
                                    'annex_path'=>'#',
                                    'report_type'=>0,
                                    'patientformcontent_id'=>$patientformcontent_id
                                ];
                                //echo "<pre>";
                                //print_R($save_cs);exit;
                                $currentSaveId = $this->save($save_cs);

//                                $previousResult = $changResultIndexDatas[$patientformcontent_id];
//                                if($previousResult['is_normal_type'] == 2 && $is_normal_type != 2){
//                                    $this->changeNormalType($previousResult,$is_normal_type,$currentSaveId);
//                                }

                                //释放空间
                                unset($save_cs);
                                unset($is_normal_type);
                            }
                            //释放空间
                            unset($content_value);
                            unset($patientformcontent_id);
                        }
                    }

                    //释放空间
                    unset($filedDatas[$filedId]);
                    unset($form_id);
                    unset($form_type);
                    unset($patient_form_id);
                    unset($content_data);
                    unset($content_normal);
                    unset($check_category_id);
                    unset($checkname_id);
                    unset($item_checkname_id);
                }
            }
            //释放空间
            unset($filedDatas);
            unset($check_info);
            unset($patient_form_datas);
            unset($time_patient_form_datas);
            unset($form_type_arr);
            unset($form_arr);
            unset($user_name);
            unset($researchstage_id);
        }
        //释放空间
        unset($form_datas);
        unset($patientchecktime_id);
        unset($checktime_id);
        unset($patient_id);
        unset($itemsig_id);
        unset($item_id);

        return 1;
    }


    /**
     * Notes : 删除AE、转移AE
     * @param $previousResult
     * @param $currentStatus
     * @param $id
     * @return bool
     * Author:唐伯虎不虎
     * Date:2024/11/5 10:08
     */
    public function changeNormalType($postData)
    {
        $patient_id = $postData['patient_id'];
        $checktime_id = $postData['checktime_id'];
        $form_id = $postData['form_id'];
        $item_id = $postData['item_id'];

        $checkname = $this->LocalService()->itemCheckname->fetchCol('form_field_id',"item_id = $item_id and form_field_id != ''");

        $checkname = array_flip($checkname);

        $changeResultWhere = 'is_del = 0 and patient_id = '.$patient_id.' and checktime_id = '.$checktime_id.' and form_id ='.$form_id;
        if(isset($postData['patientformcontent_id']) && !empty($postData['patientformcontent_id'])){
            $changeResultWhere .= ' and patientformcontent_id in ('.$postData['patientformcontent_id'].')';
        }
        $changResultDatas = $this->fetchAll([
            'where'=>$changeResultWhere,
            'columns'=>['id','is_normal_type','patientformcontent_id','item_checkname_id','result']
        ]);
        unset($changeResultWhere);

        $changResultIndexDatas = ArrayHelper::index($changResultDatas,'item_checkname_id');

        $childData = json_decode($postData['childData'],true);
        foreach($childData as $k=>$v){
            $item_checkname_id = $checkname[$v['field_id']];

            $previousResult = $changResultIndexDatas[$item_checkname_id];

            if($previousResult['is_normal_type'] == 2 && $v['normal_type'] != 2){
//                $whereItemCsaeCheck['where'] = 'is_del=0 and (ae_type = 5 or ae_type = 6 ) and patient_change_id ='.$previousResult['id'];
//                $itemCsaeCheckData = $this->LocalService()->itemCsae->fetchCol('item_name',$whereItemCsaeCheck['where']);
//                if (!empty($itemCsaeCheckData)){
//                    throw new \Application\Service\Exceptions\InvalidArgumentException("Ae数据已存在，请先删除Ae数据!", StatusCode::E_FIELD_VALIDATOR['code']);
//                }
                if(isset($previousResult['id']) && !empty($previousResult['id'])) {
                    $csaeId = $this->LocalService()->itemCsae->getOneFieldVal('id', 'patient_change_id =' . $previousResult['id'] . ' and is_del = 0');

                    if (!empty($csaeId)) {
                        $allContentId = $this->LocalService()->itemCsaeRelation->fetchAll([
                            'columns' => ['content_id'],
                            'where' => ['csae_id' => $csaeId, 'is_del' => 0]
                        ]);

                        SDMHelper::app()->ae->discardAENewAE($csaeId, ArrayHelper::getColumn($allContentId, 'content_id'));
                        //删除不等于2的cs
                        $this->LocalService()->itemCsae->update(['is_del' => 1], 'patient_change_id =' . $previousResult['id'] . ' and is_del = 0');
                    }
                }

            }else{
                if(isset($previousResult['id']) && !empty($previousResult['id'])){
                    $this->LocalService()->itemCsae->update(['result'=>$postData[$v['field_id']]], 'patient_change_id ='.$previousResult['id']);
                }
            }

            if($previousResult['is_normal_type'] != $v['normal_type'] || $previousResult['result'] != $postData[$v['field_id']]){
                if(isset($previousResult['id']) && !empty($previousResult['id'])) {
                    $updateResult = $this->update(['result' => $postData[$v['field_id']], 'is_normal_type' => $v['normal_type'], 'is_sure' => 0], ['id' => $previousResult['id'], 'is_del' => 0]);
                }
                /* if($updateResult){
                    $this->LocalService()->log->saveFileLog($previousResult['id'],'ItemIdentificationresultchangeif',['result'=>$postData[$v['field_id']],'is_normal_type'=>$v['normal_type'],'is_sure'=>0],1,'回复质疑修改异常值判断',$item_id);
                }*/
            }

        }

        return true;
    }



    /**
     * Notes: 监察解锁后 删除 异常值判断数据
     * User: lltyy
     * DateTime: 2024/6/28 15:34
     *
     * @param array $info
     * @return int
     */
    public function deleteFormCs($info = []){
        $item_id = isset($info['item_id']) && !empty($info['item_id']) ? $info['item_id'] : 0;
        $patient_id = isset($info['patient_id']) && !empty($info['patient_id']) ? $info['patient_id'] : 0;
        $checktime_id = isset($info['checktime_id']) && !empty($info['checktime_id']) ? $info['checktime_id'] : 0;
        $form_id_arr = isset($info['form_ids']) && !empty($info['form_ids']) ? $info['form_ids'] : [];
        if(!empty($form_id_arr)){
            //获取表单类的项目检查项ID
            $item_checkname_arr = $this->LocalService()->itemCheckname->fetchCol('id','is_del = 0 and form_id in ('.implode(',',$form_id_arr).') and item_id = '.$item_id);
            $item_checkname_arr = array_values($item_checkname_arr);
            if(!empty($item_checkname_arr)){
                //查找异常值判断数据ID
                $patient_change_id_arr = $this->fetchCol('id','is_del = 0 and patient_id = '.$patient_id.' and form_id in ('.implode(',',$form_id_arr).') and checktime_id = '.$checktime_id.' and item_checkname_id in ('.implode(',',$item_checkname_arr).')');
                $patient_change_id_arr = array_values($patient_change_id_arr);
                //删除异常值判断数据
                if(!empty($patient_change_id_arr)){
                    $this->update(['is_del'=>1],'id in ('.implode(',',$patient_change_id_arr).')');
                    $this->LocalService()->itemCsae->update(['is_del'=>1],'is_del = 0 and patient_change_id in ('.implode(',',$patient_change_id_arr).')');
                }
            }
            unset($item_checkname_arr);
        }
        unset($form_id_arr);
        return 1;
    }

    /**
     * Notes: 判断CS表单是否存在 AE数据
     * User: lltyy
     * DateTime: 2024/6/28 17:26
     *
     * @param array $info
     * @return array
     */
    public function checkFormAe($info = []){
        $is_haveae = 0;
        $have_ae_category = [];
        $item_id = isset($info['item_id']) && !empty($info['item_id']) ? $info['item_id'] : 0;
        $patient_id = isset($info['patient_id']) && !empty($info['patient_id']) ? $info['patient_id'] : 0;
        $checktime_id = isset($info['checktime_id']) && !empty($info['checktime_id']) ? $info['checktime_id'] : 0;
        $form_id_arr = isset($info['form_ids']) && !empty($info['form_ids']) ? $info['form_ids'] : [];
        $is_delete = isset($info['is_delete']) && !empty($info['is_delete']) ? $info['is_delete'] : 0;
        if(!empty($form_id_arr)){
            //获取表单类的项目检查项ID
            $item_checkname_arr = $this->LocalService()->itemCheckname->fetchCol('id',['is_del' => 0,'form_id' => StringHelper::toArray($form_id_arr),'item_id'=>$item_id]);
            $item_checkname_arr = array_values($item_checkname_arr);
            if(!empty($item_checkname_arr)){
                //查找异常值判断数据ID
                $patient_change_id_arr = $this->fetchCol('id',['is_del' => 0,'patient_id' => $patient_id,'form_id' => StringHelper::toArray($form_id_arr),'checktime_id' => $checktime_id,'item_checkname_id' => StringHelper::toArray($item_checkname_arr)]);
                $patient_change_id_arr = array_values($patient_change_id_arr);
                //删除异常值判断数据
                if(!empty($patient_change_id_arr)){
                    $ae_category_arr = $this->LocalService()->itemCsae->fetchCol('category_id',['is_del' => 0,'is_ae_sure' => 1,'patient_change_id' =>StringHelper::toArray($patient_change_id_arr)]);
                    $ae_category_arr = array_values(array_unique($ae_category_arr));
                    if(!empty($ae_category_arr)){
                        $have_ae_category = $this->LocalService()->dictionaryCheckcategory->fetchCol('category_name',['is_del' => 0,'id'=>StringHelper::toArray($ae_category_arr)]);
                        $is_haveae = 1;
                    }else{
                        //删除异常值信息
                        if($is_delete == 1){
                            $this->update(['is_del'=>1],['id'=>StringHelper::toArray($patient_change_id_arr)]);
                            $this->LocalService()->itemCsae->update(['is_del'=>1],['is_del' => 0,'patient_change_id' =>StringHelper::toArray($patient_change_id_arr)]);
                        }
                    }
                    unset($ae_category_arr);
                }
                unset($patient_change_id_arr);
            }
            unset($item_checkname_arr);
        }
        unset($form_id_arr);
        $mes = $is_haveae == 1 ? '表单【'.implode('、',$have_ae_category).'】存在AE数据，请先删除AE数据再进行解锁操作！' : '';
        unset($have_ae_category);
        return ['code'=>$is_haveae,'mes'=>$mes];
    }

    /**
     * Notes: 检测未查指标并发送未查质疑
     * User: llbjj
     * DateTime: 2024/9/20 10:43
     *
     */
    public function checkNoIdentification(int $patientFormId, int $patientFormContentId, bool $isSendErrorLogic = true) {
        $patientFormData = $this->LocalService()->patientForm->fetchOne([
            'where' => [ 'id' => $patientFormId]
        ]);
        if( empty($patientFormData) ) throw new \Application\Service\Exceptions\InvalidArgumentException('受试者表单不存在！');

        $checkCategoryId = $this->LocalService()->itemForm->getOneFieldVal('checklist_id', ['id' => $patientFormData['form_id']]);

        if($checkCategoryId) {
            // 获取本表单所有需要的指标
            $itemChecknameList = ArrayHelper::index($this->LocalService()->itemCheckname->fetchAll([
                'where' => [
                    'category_id' => $checkCategoryId,
                    'item_id' => $patientFormData['item_id'],
                    'is_del' => 0
                ],
                'columns' => ['id', 'name', 'unit', 'reference_range_max' => 'max_val', 'reference_range_min' => 'min_val']
            ]), 'id');

            $itemChecknameIdList = array_column($itemChecknameList, 'id');

            // 获取已存指标
            $changeList = $this->fetchAll([
                'where' => ['patient_form_id' => $patientFormId, 'patientformcontent_id' => $patientFormContentId],
                'column' => ['id', 'item_checkname_id', 'is_identification', 'collect_date', 'is_annul']
            ]);

            $changeItemChecknameIdList = [];
            $noIdentificationIdList = [];
            $collect_date = '';
            $lock_state = 0;
            $isAnnulList = [];
            if(!empty($changeList)) {
                foreach ($changeList as &$change) {
                    if($change['is_identification']) {
                        // 未查
                        $noIdentificationIdList[$change['item_checkname_id']] = &$change['id'];
                    }else {
                        // 已查
                        $changeItemChecknameIdList[$change['id']] = &$change['item_checkname_id'];
                    }

                    if($collect_date == '' && $change['collect_date']) $collect_date = strtotime($change['collect_date']);
                    if(!$lock_state) $lock_state = $change['lock_state'];
                    if($change['is_annul']) $isAnnulList[] = $change['id'];
                }
            }

            // 未查指标
            $noIdentificationItemChecknameIdList = array_diff($itemChecknameIdList, $changeItemChecknameIdList);
            if(!empty($noIdentificationItemChecknameIdList)) {
                // 获取自动发送质疑黑名单
                $blackChecknameIdArr = $this->LocalService()->itemLogicErrorReportBlack->fetchCol('item_checkname_id', [
                   'patient_form_id' => $patientFormId,
                   'is_del' => 0,
                   'patientformcontent_id' => $patientFormContentId ?? 0,
                ]);

                foreach ($noIdentificationItemChecknameIdList as $item_checkname_id) {
                    // 存入数据库
                    $resultChangeId = $this->save([
                        'id' => $noIdentificationIdList[$item_checkname_id] ?? 0,
                        'item_checkname_id' => $item_checkname_id,
                        'patient_form_id' => $patientFormId,
                        'patientformcontent_id' => $patientFormContentId ?? 0,
                        'form_id' => &$patientFormData['form_id'],
                        'item_id' => &$patientFormData['item_id'],
                        'patient_id' => &$patientFormData['patient_id'],
                        'itemsig_id' => &$patientFormData['itemsig_id'],
                        'checktime_id' => &$patientFormData['checktime_id'],
                        'is_identification' => 1,
                        'item_name' => &$itemChecknameList[$item_checkname_id]['name'],
                        'unit' => &$itemChecknameList[$item_checkname_id]['unit'],
                        'reference_range_max' => &$itemChecknameList[$item_checkname_id]['reference_range_max'],
                        'reference_range_min' => &$itemChecknameList[$item_checkname_id]['reference_range_min'],
                        'category_id' => $checkCategoryId,
                        'collect_date' => $collect_date,
                        'lock_state' => $lock_state,
                        'is_del' => in_array($noIdentificationIdList[$item_checkname_id] ?? 0, $isAnnulList) ? 0 : 1,
                        'result' => '',
                    ]);

                    // 在黑名单中存在就不要自动发送质疑
                    if(!empty($blackChecknameIdArr) && in_array($item_checkname_id, $blackChecknameIdArr)) continue;

                    // 发送质疑
                    if($isSendErrorLogic) SDMHelper::app()->logic->setReportError('is_identification', $noIdentificationIdList[$item_checkname_id] ?? $resultChangeId, "[ {$itemChecknameList[$item_checkname_id]['name']} ] 未查");
                }
            }
        }
    }

}