<?php

namespace Application\Service\DB\Item;

use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\IsNotNull;
use Laminas\Db\Sql\Predicate\IsNull;
use Laminas\Db\Sql\Predicate\NotIn;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Db\Sql\Where;

class Patientchecktime extends \Application\Service\DB\AbstractDb {
    public function __construct($dbAdapter, ContainerInterface $container) {
        $this->tableName = 'yikeen_item_patientchecktime';
        parent::__construct($dbAdapter, $container);
    }

    // 修改锚点日期
    public function EditAnchorDate($item_id,$patient_id,$anchor_id,$date){
        if(empty($item_id)||empty($patient_id)||empty($anchor_id)||empty($date)){
            return false;
        }
        $anchor_date=strtotime($date);
        $where = [
            'is_del' => 0,
            'item_id' => $item_id,
            'patient_id' => $patient_id,
            'anchor_id' => $anchor_id,
        ];
        $dateDatas=$this->fetchAll(['where'=>$where,'order'=>'check_order','columns'=>['checktime_id','check_order','anchor_date']]);
        if(!empty($dateDatas)){
            $patientchecktime = [];
            foreach ($dateDatas as $k=>$v){
                $patientchecktime[$v['checktime_id']] = $v;
            }

            //查询检查点的时间类型
            $Checktimewhere['where'] = [
                'is_del' => 0,
                'id' => array_keys($patientchecktime)
            ];
            $checktimeDatas=$this->LocalService()->itemChecktime->fetchAll($Checktimewhere);
            foreach ($checktimeDatas as $key=>$val){
                if($val['field_id'] != $anchor_id) $anchor_date = $patientchecktime[$v['id']]['anchor_date'];
                $time_unit='';
                switch ($val['time_unit']){
                    case 0 :$time_unit='day';break;
                    case 1 :$time_unit='week';break;
                    case 2 :$time_unit='month';break;
                    case 3 :$time_unit='year';break;
                }
                if($val['start_time']>0){
                    $plan_start_date=strtotime(+($val['start_time']-1).' '.$time_unit,$anchor_date);
                }else{
                    $start_time=ltrim($val['start_time'],'-');
                    $plan_start_date=strtotime(-$start_time.' '.$time_unit,$anchor_date);
                }
                if($val['end_time']>0){
                    $plan_end_date=strtotime(+($val['end_time']-1).' '.$time_unit,$anchor_date);
                }else{
                    $end_time=ltrim($val['end_time'],'-');
                    $plan_end_date=strtotime(-$end_time.' '.$time_unit,$anchor_date);
                }
                if($key == 0){
                    //获取上一个受试者检查点信息
                    $prevchecktimeWhere['where'] = [
                        'is_del' => 0,
                        'patient_id' => $patient_id,
                        new Operator('anchor_date', Operator::OP_NE, ''),
                        new Operator('check_order', Operator::OP_LT, $dateDatas[0]['check_order']),
                    ];
                    $prevchecktimeWhere['order'] = 'check_order desc';
                    $prevchecktimeWhere['columns'] = ['id'];
                    $prevchecktime = $this->fetchOne($prevchecktimeWhere);
                    if(!empty($prevchecktime)){
                        $this->update(['plan_end_date'=>$plan_start_date],"id = ".$prevchecktime['id']);
                    }
                }
                $result=$this->update(
                    [
                        'anchor_date'=>$anchor_date,
                        'plan_start_date'=>$plan_start_date,
                        'plan_end_date'=>$plan_end_date
                    ],[
                        'item_id' => $item_id,
                        'patient_id' => $patient_id,
                        'checktime_id' => $val['id'],
                ]);
            }

            return true;
        }else{
            return true;
        }
    }

    //修改当前数据为当前检查点
    public function EditPatientChecktimeStatus($item_id,$patient_id){
        if(empty($item_id)||empty($patient_id)){
            return false;
        }
        $log_oprt_type = php_sapi_name() === 'cli' ? 3 : 1; // 日志的操作类型

        //判断当前有没有脱离完成表单的操作

        $where['order']=['check_order asc'];
        $where['where']= [
            'is_del' => 0,
            'item_id' => $item_id,
            'patient_id' => $patient_id,
            new Operator('leave_type', Operator::OP_GT, 0),
            new Operator('is_skip', Operator::OP_NE, 1),
        ];
        $PatientchecktimeData = $this->fetchOne($where);

        //查询最新一条的锚点id
        $anchorwhere['order']=['check_order desc'];
        $anchorwhere['where'] = [
            'is_del' => 0,
            'item_id' => $item_id,
            'patient_id' => $patient_id,
            new Operator('anchor_date', Operator::OP_NE, ''),
        ];
        $anchorwhere['columns']=['anchor_id'];
        $last_anchorid = $this->fetchCol('anchor_id',$anchorwhere['where']);

        $nowChecktimeId = $this->getOneFieldVal('checktime_id',[
            'patient_id' => $patient_id,
            'is_now_state' => 1,
        ]);

        if(empty($PatientchecktimeData) || $PatientchecktimeData['checktime_id'] != $nowChecktimeId){
            $last_anchorid = array_values(array_unique($last_anchorid));

            $last_anchorid = $last_anchorid[count($last_anchorid) - 1];

            $time=strtotime(date('Y-m-d'));
            //根据当前时间匹配
            $where['where'] = [
                'is_del' => 0,
                'item_id' => $item_id,
                'patient_id' => $patient_id,
                new Operator('plan_start_date', Operator::OP_LTE, $time),
                new Operator('plan_end_date', Operator::OP_GTE, $time),
                new IsNotNull('anchor_date'),
                new Operator('is_skip', Operator::OP_NE, 1),
            ];

            $where['order']=['check_order asc'];
            $PatientchecktimeData=$this->fetchOne($where);

            //匹配最新过期的一条
            if(empty($PatientchecktimeData)){
                $where['order']=['plan_end_date desc'];
                $where['where']= [
                    'is_del' => 0,
                    'item_id' => $item_id,
                    'patient_id' => $patient_id,
                    new Operator('plan_end_date', Operator::OP_LT, $time),
                    new Operator('plan_start_date', Operator::OP_GT, 1000000),
                    new IsNotNull('anchor_date'),
                    new Operator('is_skip', Operator::OP_NE, 1),
                ];
                if(!empty($last_anchorid)){
                    $where['where']['anchor_id'] = $last_anchorid;;
                }

                $PatientchecktimeData=$this->fetchOne($where);
            }
        }

        if(!empty($PatientchecktimeData)){
            // 受试者名称
            $patient_number_name = $this->LocalService()->patient->getOneFieldVal('patient_number_name', [
                'id' => $patient_id,
            ]);
            $Patientchecktimewhere['columns']=['id'];
            $Patientchecktimewhere['where']= [
                'is_del' => 0,
                'item_id' => $item_id,
                'patient_id' => $patient_id,
                'is_now_state' => 1,
            ];
            $PatientchecktimeInfo=$this->fetchOne($Patientchecktimewhere);
            //是否为当前检查点
            if($PatientchecktimeInfo['id']==$PatientchecktimeData['id']){
                return true;
            }
            else{
                //修改不是当前检查点
                if(!empty($PatientchecktimeInfo)){
                    $result=$this->update(['is_now_state'=>0],[
                        'id' => $PatientchecktimeInfo['id']
                    ]);
                    if(!empty($result)){
                        $this->LocalService()->log->saveFileLog($PatientchecktimeInfo['id'],'itemPatientchecktime',['is_now_state'=>0], $log_oprt_type,"受试者{$patient_number_name}离开检查点",$item_id);
                    }
                }
            }

            //修改当前数据为当前检查点
            $result=$this->update(['is_now_state'=>1],[
                'id' => $PatientchecktimeData['id']
            ]);

            //查询是否是计划外检查点
            $isUnplanned = $this->LocalService()->itemChecktime->getOneFieldVal('patient_id',[
                'id' => $PatientchecktimeData['checktime_id']
            ]);
            //如果当前检查点是计划外检查点则更改受试者表字段
            $checkid_status = !empty($isUnplanned) ? 1 : 0;

            $this->LocalService()->patient->update(['checkid_status'=>$checkid_status],[
                'id' => $PatientchecktimeData['patient_id']
            ]);

            //修改受试者当前检查点
            $this->LocalService()->patient->update([
                'patient_check_id'=>$PatientchecktimeData['checktime_id'],
                'patient_stage_id'=>$PatientchecktimeData['researchstage_id']
            ],[
                'id' => $PatientchecktimeData['patient_id']
            ]);
            if(!empty($result)){
                $this->LocalService()->log->saveFileLog($PatientchecktimeData['id'],'itemPatientchecktime',['is_now_state'=>1], $log_oprt_type,"受试者{$patient_number_name}进入检查点",$item_id);
                return true;
            }else{
                return false;
            }
        }
    }
    //所有受试者 更新当前检查点
    public function AllPatient(){
        //受试者数据
        $Patientwhere['where']= [
            'is_del' => 0,
            'patient_status' => 9,
        ];
        $Patientwhere['columns']=['id','item_id'];
        $patientInfo=$this->LocalService()->patient->fetchAll($Patientwhere);
        if(!empty($patientInfo)){
            foreach ($patientInfo as $k=>$v){
                $this->EditPatientChecktimeStatus($v['item_id'],$v['id']);
            }
        }
    }

    public function upchecktimeeditpatientStatus($arr)
    {
        $item_id = $arr['item_id'];
        $patientInfo = $arr['patientInfo'];
        foreach ($patientInfo as $k=>$v){
            $this->EditPatientChecktimeStatus($item_id,$v['id']);
        }
    }

    //更新历史数据【已经脱离完成的受试者更新隶属检查点】
    public function historyDataPatient(){
        //受试者数据
        $Patientwhere['where']= [
            'is_del' => 0,
            new Operator('patient_status', Operator::OP_NE, 9),
        ];
        $Patientwhere['columns']=['id','item_id'];
        $patientInfo=$this->LocalService()->patient->fetchAll($Patientwhere);
        if(!empty($patientInfo)){
            foreach ($patientInfo as $k=>$v){
                $this->EditPatientChecktimeStatus($v['item_id'],$v['id']);
            }
        }
    }
    //是否可以脱离
    public function Look($patient_id,$id,$item_id){
        $patientStatus = $this->LocalService()->patient->getOneFieldVal('patient_status', ['id' => $patient_id]);
        if($patientStatus != 9) return ['type'=>3, 'msg'=>'当前受试者已经操作中止/筛败或完成'];

        //获取排序值
        $Patientchecktimewhere['where']= [
            'is_del' => 0,
            'id' => $id,
        ];
        $Patientchecktimewhere['columns']= ['id','check_order','researchstage_id','plan_start_date','plan_end_date','leave_type','checktime_name'];
        $PatientchecktimeData=$this->fetchOne($Patientchecktimewhere);
        if($PatientchecktimeData['leave_type']!=null && $PatientchecktimeData['leave_type'] != 0) return ['type'=>3, 'msg'=>'当前检查点已经操作中止/筛败或完成'];
        //阶段数据
        if(!empty($PatientchecktimeData['researchstage_id'])){
            $stageMap['where'] = [
                'is_del' => 0,
                'id' => $PatientchecktimeData['researchstage_id'],
            ];
            $ResearchstageData=$this->LocalService()->itemResearchstage->fetchOne($stageMap);
        }else{
            $ResearchstageData['is_show']=0;
            $ResearchstageData['stage_id']=0;
        }
        //查询当前检查点之后的检查点
        $Afterwhere = [
            'is_del' => 0,
            'patient_id' => $patient_id,
            'item_id' => $item_id,
            new Operator('check_order', Operator::OP_GT, $PatientchecktimeData['check_order']),
        ];
        $PatientchecktimeDatas=$this->getCount($Afterwhere);
        //既可以脱离也可以完成也可以失败 $ResearchstageData['is_show']==0
        if($PatientchecktimeDatas=='0'&&strlen($PatientchecktimeData['plan_start_date'])=='10'&&strlen($PatientchecktimeData['plan_end_date'])=='10'&&($PatientchecktimeData['leave_type']=='' || $PatientchecktimeData['leave_type']==0)&&$ResearchstageData['stage_id']==1){
            return ['type'=>1, 'msg'=>''];
        }
        //既可以脱离也可以完成 $ResearchstageData['is_show']==0
        if($PatientchecktimeDatas=='0'&&strlen($PatientchecktimeData['plan_start_date'])=='10'&&strlen($PatientchecktimeData['plan_end_date'])=='10'&&($PatientchecktimeData['leave_type']=='' || $PatientchecktimeData['leave_type']==0)){
            return ['type'=>4, 'msg'=>''];
        }
        if(strlen($PatientchecktimeData['plan_start_date'])<10||strlen($PatientchecktimeData['plan_end_date']<10)){
            return ['type'=>3, 'msg'=>'无窗口期不可中止/筛败/完成'];
        }

        //查询当前项目下所有检查点
        $checktimeDatas = $this->LocalService()->itemChecktime->fetchCol('check_name',[
            'is_del' => 0,
            'item_id' => $item_id,
        ]);

        //查询独立访视检查点
        $is_isolate = $this->LocalService()->itemChecktime->fetchCol('id',[
            'is_del' => 0,
            'item_id' => $item_id,
            'is_isolate' => 1,
        ]);

        $is_isolateId = '';
        $patientcheckcontent_isolateID = '';
        if(!empty($is_isolate)){
            $is_isolateId = implode(',',$is_isolate);
            $patientcheckcontent_isolate = $this->LocalService()->itemChecktime->fetchCol('patientchecktime_id',[
                'is_del' => 0,
                'item_id' => $item_id,
                'is_isolate' => 1,
                new Operator('patientchecktime_id', Operator::OP_GT, 0),
            ]);
            if(!empty($patientcheckcontent_isolate)){
                $patientcheckcontent_isolateID = implode(',',$patientcheckcontent_isolate);
            }
        }
        //查询当前项目下所有阶段
        $stageDatas = $this->LocalService()->itemResearchstage->fetchCol('stage_name',[
            'is_del' => 0,
            'item_id' => $item_id,
        ]);

        $patientchecktimeDatas = $this->fetchAll(['where' => [
            'patient_id' => $patient_id,
            'item_id' => $item_id,
        ],'columns'=>['researchstage_id','checktime_id']]);

        $patientchecktimeStage = [];
        foreach($patientchecktimeDatas as $k=>$v){
            $patientchecktimeStage[$v['checktime_id']] = $v['researchstage_id'];
        }

        //查询当前检查点之后的检查点
        $AfterMap['where'] = [
            'is_del' => 0,
            'item_id' => $item_id,
            'patient_id' => $patient_id,
            new Operator('check_order', Operator::OP_GT, $PatientchecktimeData['check_order']),
        ];
        $AfterDatas=$this->fetchAll($AfterMap);
        if(!empty($AfterDatas)){
            //条目信息 计划内
            $within_map['where'] = [
                'is_del' => 0,
                'item_id' => $item_id,
                'check_id' => array_column($AfterDatas, 'checktime_id')
            ];
            $CheckcontentDatas = $this->LocalService()->itemCheckcontent->fetchAll($within_map);
            //条目信息 计划外
            $outer_map['where']= [
                'is_del' => 0,
                'item_id' => $item_id,
                'patientchecktime_id' => array_column($AfterDatas, 'id')
            ];

            if($patientcheckcontent_isolateID != '') $outer_map['where'] .= " and patientchecktime_id not in ($patientcheckcontent_isolateID)";
            $PatientCheckcontentDatas = $this->LocalService()->itemPatientcheckcontent->fetchAll($outer_map);
            $within_data=[];
            $outer_data=[];
            if(!empty($CheckcontentDatas)){
                $PatientFormContentMap['where'] = [
                    'is_del' => 0,
                    'checktime_id' => array_column($CheckcontentDatas, 'check_id'),
                    'item_id' => $item_id,
                    'patient_id' => $patient_id,
                    'form_id' => array_column($CheckcontentDatas, 'form_id'),
                ];
                if($is_isolateId != '') $PatientFormContentMap['where'][] = new NotIn('checktime_id', $is_isolate);
                $PatientFormContentMap['columns'] = ['patient_id','checktime_id','form_id'];
                $data=$this->LocalService()->patientFormContent->fetchAll($PatientFormContentMap);

                //失活数据
                $inactiveDatas = [];
                $PatientFormContentMap['where']['is_inactive'] = 1;
                $patientFormDatas = $this->LocalService()->patientForm->fetchAll($PatientFormContentMap);
                if(!empty($patientFormDatas)){
                    foreach($patientFormDatas as $k=>$v){
                        $Index = $v['patient_id'].'-'.$v['checktime_id'].'-'.$v['form_id'];
                        $inactiveDatas[$Index] = 1;
                    }
                }
                if(!empty($data)){
                    foreach ($data as $key=>$val){
                        $Index = $val['patient_id'].'-'.$val['checktime_id'].'-'.$val['form_id'];
                        if(isset($inactiveDatas[$Index])) {
                            unset($data[$key]);
                            continue;
                        }
                        $stage_id = $patientchecktimeStage[$val['checktime_id']];
                        if(!empty($stage_id)){
                            $stage_name = $stageDatas[$stage_id];
                        }
                        if(!empty($stage_name)){
                            $within_data[$key]['checktime_name'] = $checktimeDatas[$val['checktime_id']];
                        }else{
                            $within_data[$key]['checktime_name'] = $checktimeDatas[$val['checktime_id']];
                        }
                    }
                    $within_data=$data;
                }
            }

            if(!empty($PatientCheckcontentDatas)){
                foreach ($PatientCheckcontentDatas as $Pk=>$Pv){
                    $PatientFormContentwhere['where'] = [
                        'is_del' => 0,
                        'checktime_id' => $Pv['patientchecktime_id'],
                        'item_id' => $item_id,
                        'patient_id' => $patient_id,
                        'form_id' => $Pv['form_id'],
                    ];
                    $info=$this->LocalService()->patientFormContent->fetchOne($PatientFormContentwhere);
                    if(!empty($outer_data)){
                        $outer_data[$Pk]=$info;
                        $outer_data[$Pk]['checktime_name']=$this->getOneFieldVal('checktime_name', [
                            'id' => $Pv['patientchecktime_id']
                        ]);
                    }
                }
            }

            $within_data=$this->LocalService()->itemChecktime->unique_2d_array_by_key($within_data,'checktime_name');

            $outer_data=$this->LocalService()->itemChecktime->unique_2d_array_by_key($outer_data,'checktime_name');
            $new_data=array_merge($within_data,$outer_data);
            if(!empty($new_data)){
                $checktime_name='';
                foreach ($new_data as $key=>$val){
                    if($val['checktime_name'] ?? '') $checktime_name.=$val['checktime_name'].'/';
                }
                $checktime_name=trim($checktime_name,'/');
                return ['type'=>3, 'msg'=>$checktime_name.'下有表单数据不可中止/筛败/完成'];
            }
        }
        if(strlen($PatientchecktimeData['plan_start_date'])=='10'&&strlen($PatientchecktimeData['plan_end_date'])=='10'&&($PatientchecktimeData['leave_type']=='' || $PatientchecktimeData['leave_type']==0)){
            if($ResearchstageData['stage_id']==1){
                return ['type'=>5, 'msg'=>''];
            }else{
                return ['type'=>2, 'msg'=>''];
            }
        }
    }
    public function PatientChecktimeAdd($new_item_id,$old_item_id){
        $yikeen = new \mysqli('localhost','root','root3306',"mc5");

        $yikeen->set_charset('utf8') or die('设置字符集失败：'.$yikeen->error);

        $sql='select * from oa_item_patientchecktime where item_id='.$old_item_id.' and is_del=0';

        $result = $yikeen->query($sql);

        $PatientChecktimeDatas=[];

        while($row = $result->fetch_assoc())
        {
            $PatientChecktimeDatas[]=$row;
        }
        $checktime_name='';
        foreach ($PatientChecktimeDatas as $k=>$v){
            if(empty($v['checktime_id'])){
                $checktime_name=$v['checktime_name'];
            }else{
                $checktime_name=null;
            }
            $insert_arr=[
                'item_id'=>$new_item_id, 'patient_id'=>$v['patient_id'], 'checktime_id'=>$v['checktime_id'],
                'itemsig_id'=>$v['itemsig_id'], 'plan_start_date'=>$v['plan_start_date'],'plan_end_date'=>$v['plan_end_data'],
                'leave_type'=>$v['leave_type'], 'leave_date'=>$v['leave_date'],'anchor_id'=>$v['anchor_id'],
                'anchor_date'=>$v['anchor_date'], 'stage_remark'=>$v['stage_remark'], 'is_now_state'=>$v['is_now_state'],
                'is_del'=>$v['is_del'], 'is_no_booked'=>$v['is_no_booked'],'researchstage_id'=>$v['researchstage_id'],
                'checktime_name'=>$checktime_name, 'check_order'=>$v['check_order'],'is_affect_whole'=>$v['is_affect_whole'],
                'yes_booked_time'=>$v['yes_booked_time'],'no_booked_time'=>$v['no_booked_time'],
            ];
            $result=$this->insert($insert_arr);
            if(!empty($v['checktime_id'])){
                $checktime_data=$this->LocalService()->itemChecktime->fetchOne(['where'=>'old_checktime_id='.$v['checktime_id'].' and item_id='.$new_item_id]);
                $this->update(['checktime_id'=>$checktime_data['id']],'id='.$result);
            }else{
                $checktime_data['id']=$v['checktime_id'];
            }
            if(!empty($v['researchstage_id'])){
                $stage_data=$this->LocalService()->itemResearchstage->fetchOne(['where'=>'old_stage_id='.$v['researchstage_id'].' and item_id='.$new_item_id]);
                $this->update(['researchstage_id'=>$stage_data['id']],'id='.$result);
            }else{
                $stage_data['id']=$v['researchstage_id'];
            }
            if($v['is_now_state']==1){
                $this->LocalService()->patient->update(
                    [
                        'patient_check_id'=>$checktime_data['id'],
                        'patient_stage_id'=>$stage_data['id'],
                    ],'id='.$v['patient_id']
                );
            }
        }
    }
    //删除对应检查点
    public function DelChecktime($random_id,$patient_id,$item_id){
        if(empty($random_id) || empty($patient_id) || empty($item_id)){
            return false;
        }
        //删除检查点 重新判定当前隶属检查点
        $this->EditPatientChecktimeStatus($item_id,$patient_id);
        //查询方案下的检查点
        $checktime_data=$this->LocalService()->itemChecktime->fetchAll(['where'=> [
            'random_id' => $random_id,
            'item_id' => $item_id,
            'is_del' => 0,
        ]]);
        if(!empty($checktime_data)){
            foreach ($checktime_data as $key=>$val){
                $this->update(['is_del'=>'1'],[
                    'item_id' => $item_id,
                    'patient_id' => $patient_id,
                    'checktime_id' => $val['id'],
                ]);
            }
            return true;
        }else{
            return true;
        }
    }

    /**
     *获取该中心下的受试者阶段、检查点、状态受试者数据
     * User: lltyy
     * DateTime: 2022/9/8 9:15
     * $item_id //项目ID
     * $itemsig_id //项目中心ID
     * $stage_id //研究阶段ID
     * 1、$patient_count['checktime']: 检查点受试者数
     * 2、$patient_count['stage']: 研究阶段受试者数
     * 3、$patient_count['leave']: 筛败(leave_type = 2)、脱落(leave_type = 1)、终止(leave_type = 4)、完成(leave_type = 3)、进行中(leave_type = 9)
     * 4、SAE：获取有填写SAE数据的受试者（-1）
     */
    public function getPatientCount($arr=[]){
        $item_id = isset($arr['item_id']) ? $arr['item_id'] : 0;//副项目ID
        $itemsig_id = isset($arr['itemsig_id']) ? $arr['itemsig_id'] : 0;//中心ID
        $stage_id = isset($arr['stage_id']) ? $arr['stage_id'] : 0;//研究阶段ID
        $patient_count = [+
            'checktime'=>[],
            'stage'=>[],
            'leave'=>[],
            'type'=>[]
        ];

        $patient_checktime_where = [
            'is_del' => 0,
        ];
        if(!empty($item_id)){
            $patient_checktime_where['item_id'] = $item_id;
        }
        if(!empty($itemsig_id)){
            $patient_checktime_where['itemsig_id'] = $itemsig_id;
        }
        if(!empty($stage_id)){
            $patient_checktime_where['researchstage_id'] = $stage_id;
        }
        $patient_checktime_where_arr = [
            'where'=>$patient_checktime_where,
            'columns'=>['patient_id','researchstage_id','leave_type','checktime_id','is_now_state'],
            'order'=>['check_order']
        ];
        $patient_checktimes = $this->LocalService()->itemPatientchecktime->fetchAll($patient_checktime_where_arr);
        $leave_type_patient = [];
        $patient_arr = [
            'over'=>[],//脱落，完成、筛败、终止
            'now'=>[]//进行中
        ];
        if(!empty($patient_checktimes)){
            foreach($patient_checktimes as $patient_checktime){
                $patient_checktime_id = $patient_checktime['checktime_id'];
                $patient_researchstage_id = $patient_checktime['researchstage_id'];
                $patient_leave_type = $patient_checktime['leave_type'];
                $patient_id = $patient_checktime['patient_id'];
                if(!isset($patient_leave_type)){
                    $patient_leave_type = 9;
                }
                if($patient_checktime['is_now_state'] == 1){
                    if(isset($patient_checktime_id)){
                        //检查点受试者数
                        $patient_count['checktime'][$patient_checktime_id] = isset($patient_count['checktime'][$patient_checktime_id]) && !empty($patient_count['checktime'][$patient_checktime_id]) ? $patient_count['checktime'][$patient_checktime_id] : 0;
                        $patient_count['checktime'][$patient_checktime_id] += 1;
                    }

                    if(isset($patient_researchstage_id) && !empty($patient_researchstage_id)) {
                        //研究阶段受试者数
                        $patient_count['stage'][$patient_researchstage_id] = isset($patient_count['stage'][$patient_researchstage_id]) && !empty($patient_count['stage'][$patient_researchstage_id]) ? $patient_count['stage'][$patient_researchstage_id] : 0;
                        $patient_count['stage'][$patient_researchstage_id] += 1;
                    }
                }
                if(isset($patient_leave_type)) {
                    if(in_array($patient_leave_type,[1,2,3,4])){
                        $leave_type_patient[$patient_leave_type][$patient_id] = $patient_id;
                        $patient_arr['over'][$patient_id] = $patient_id;
                    }else{
                        $patient_arr['now'][$patient_id] = $patient_id;
                    }
                    $patient_count['type'][$patient_leave_type] = $patient_leave_type;
                }
            }
        }
        if(!empty($patient_arr['now'])){
            if(!empty($patient_arr['over'])){
                foreach($patient_arr['now'] as $patient_now){
                    if(!in_array($patient_now,$patient_arr['over'])){
                        $leave_type_patient[9][$patient_now] = $patient_now;
                    }
                }
            }else{
                $leave_type_patient[9] = $patient_arr['now'];
            }
        }
        if(!empty($patient_count['type'])){
            foreach($patient_count['type'] as $type){
                //筛败、脱落、完成、进行中受试者数
                $count = isset($leave_type_patient[$type]) && !empty($leave_type_patient[$type]) ? count($leave_type_patient[$type]) : 0;
                $patient_count['leave'][$type] = $count;
            }
        }
        return $patient_count;
    }

    /**
     *获取指定项目中心下的当前隶属阶段检查点的受试者数
     * User: lltyy
     * DateTime: 2022/9/8 9:15
     *
     * $item_id //项目ID
     * $itemsig_id //项目中心ID
     * $count_enter //统计入口【0 real端进度汇总 1 小程序汇总统计】
     * 1、$patient_count['stage']: 研究阶段受试者数
     * 2、$patient_count['leave']: 筛败(leave_type = 2)、脱落(leave_type = 1)、终止(leave_type = 4)、完成(leave_type = 3)、进行中(leave_type = 9)
     * 3、SAE：获取有填写SAE数据的受试者
     * 4、终点事件：获取有填写终点事件表单数据的受试者(leave_type = -2)
     */
    public function GetItemSigResearchstagePatient($arr=[]){
        $item_id = isset($arr['item_id']) ? $arr['item_id'] : 0;//副项目ID
        $itemsig_id = isset($arr['itemsig_id']) ? $arr['itemsig_id'] : 0;//中心ID
        $count_enter = isset($arr['count_enter']) ? $arr['count_enter'] : 0;//统计入口【0 real端进度汇总 1 小程序汇总统计】

        //获取该中心下的受试者阶段、检查点、状态受试者数据
        $patient_count = $this->getPatientCount(['item_id'=>$item_id,'itemsig_id'=>$itemsig_id]);

        //返回所有数据
        $data = [];
        if(empty($count_enter)){
            $data[0] = [
                'id'=>'09',
                'stage_name'=>'进行中',
                'is_stage'=>0,
                'count'=>isset($patient_count['leave'][9]) && !empty($patient_count['leave'][9]) ? $patient_count['leave'][9] : 0
            ];
        }

        //获取该副项目下设置的研究阶段数据
        $item_researchstage_where = ['is_del' => 0];
        if(!empty($item_id)){
            $item_researchstage_where['item_id'] = $item_id;
        }
        $item_researchstage_where_arr = [
            'where'=>$item_researchstage_where,
            'columns'=>['id','stage_name'],
            'order'=>'stage_order'
        ];
        $item_researchstages = $this->LocalService()->itemResearchstage->fetchAll($item_researchstage_where_arr);
        if(!empty($item_researchstages)){
            foreach($item_researchstages as $key=>$item_researchstage){
                $item_researchstage_id = $item_researchstage['id'];
                $stage_data = $item_researchstage;
                if(empty($count_enter)) {
                    $stage_data['is_stage'] = 1;
                }
                $stage_data['count'] = isset($patient_count['stage'][$item_researchstage_id]) && !empty($patient_count['stage'][$item_researchstage_id]) ? $patient_count['stage'][$item_researchstage_id] : 0;
                $data[] = $stage_data;
            }
        }

        //筛败(leave_type = 2)、脱落(leave_type = 1)、终止(leave_type = 4)、完成(leave_type = 3)、进行中(leave_type = 9)
        $leave_arr = [
            '02'=>'筛败',
//            '01'=>'脱落',
            '04'=>'中止',
            '03'=>'完成'
        ];
        if(!empty($leave_arr)){
            foreach($leave_arr as $leave_key=>$leave_name){
                $leave_key_int = intval($leave_key);
                $leave_data = [
                    'id'=>$leave_key,
                    'stage_name'=>$leave_name,
                    'count'=>isset($patient_count['leave'][$leave_key_int]) && !empty($patient_count['leave'][$leave_key_int]) ? $patient_count['leave'][$leave_key_int] : 0
                ];
                if(empty($count_enter)) {
                    $leave_data['is_stage'] = 0;
                }
                $data[] = $leave_data;
            }
        }


        //SAE
        if(empty($count_enter)) {
            $sae_data = [
                'id' => '-1',
                'stage_name' => 'SAE',
                'is_stage' => 0,
                'count' => 0
            ];

            //获取该项目下的SAE类表单
            $sae_form_where = ['is_del'=>0];
            if (!empty($item_id)) {
                $sae_form_where['item_id'] = $item_id;
            }
            $sae_formid_arr = $this->LocalService()->itemForm->getGroupForm($sae_form_where, [
                'is_del' => 0,
                'code' => 'SAE',
            ]);
            if (isset($sae_formid_arr) && !empty($sae_formid_arr)) {
                //获取SAE受试者数据
                $sae_form_patient_where = [
                    'is_del' => 0,
                    'form_id' => $sae_formid_arr,
                ];
                if (!empty($item_id)) {
                    $sae_form_patient_where['item_id'] = $item_id;
                }
                if (!empty($itemsig_id)) {
                    $sae_form_patient_where['itemsig_id'] = $itemsig_id;
                }
                $sae_data['count'] = $this->LocalService()->patientFormContent->getCount($sae_form_patient_where);
            }
            $sae_data['count'] = isset($sae_data['count']) && !empty($sae_data['count']) ? $sae_data['count'] : 0;
            $data[] = $sae_data;
        }

        //终点事件
        if(empty($count_enter)) {
            $endform_data = [
                'id' => '-2',
                'stage_name' => '终点事件',
                'is_stage' => 0,
                'count' => 0
            ];

            //获取该项目下的终点事件表单
            $endFormArr = $this->LocalService()->itemForm->fetchCol('id',[
                'is_del' => 0,
                'var_name' => 'MACCE',
                'item_id' => $item_id,
            ]);
            $endFormArr = array_values($endFormArr);

            //获取终点事件人数
            if(!empty($endFormArr) && !empty($itemsig_id) && !empty($item_id)){
                $endFormCountArr = $this->LocalService()->patientFormContent->fetchFormPatient([
                    'item_id'=>[$item_id],
                    'itemsig_id'=>[$itemsig_id],
                    'form_id'=>$endFormArr,
                    'key'=>['itemsig_id']
                ]);
                if(!empty($endFormCountArr)){
                    foreach($endFormCountArr as $endFormCountKey=>$endFormCount){
                        $endform_data['count'] += count($endFormCount);
                        unset($endFormCountArr[$endFormCountKey]);
                    }
                }
                unset($endFormCountArr);
            }
            unset($endFormArr);
            $data[] = $endform_data;
            unset($endform_data);
        }

        return $data;
    }

    /**
     * Notes:获取符合要求的受试者检查点信息
     * User: lltyy
     * DateTime: 2022/9/8 9:15
     *
     * @param array $arr
     *          item_id 副项目ID
     *          itemsig_id 项目中心ID
     *          patient_id_arr 受试者ID数组
     *          checktime_id_arr 检查点ID数组
     *          form_code_arr  表单类型Code数组
     *          patientform_array_key  受试者表单返回键值类型【0 受试者ID 1 受试者检查点ID】
     * @param $where //受试者检查点条件
     * @param $select_columns //受试者检查点字段信息
     * @return mixed
     */
    public function getPatientChecktimeDatas($arr=[],$where,$select_columns=[]){
        $form_count = 0;//是否获取表单数据【0 否 1 是】
        $columns = [];
        if(in_array('form_count',$select_columns)){
            $form_count = 1;
            $form_count_key = array_keys($select_columns,'form_count');
            unset($select_columns[$form_count_key[0]]);
        }
        if(in_array('form_info',$select_columns)){
            $form_count = 2;
            $form_count_key = array_keys($select_columns,'form_info');
            unset($select_columns[$form_count_key[0]]);
        }

        //获取受试者检查点信息
        $datas = [];
        $where_arr = [
            'where'=>$where,
            'columns'=>$select_columns,
            'order'=>['check_order']
        ];
        $datas = $this->fetchAll($where_arr);
        if(in_array($form_count,[1,2]) && !empty($datas)){

            //获取随机分组、贯穿全程类、常规类、检查类（OCR识别）表单ID
            $item_form_where = [
                'is_del' => 0,
            ];
            if(!empty($item_id)){
                $item_form_where['item_id'] = $item_id;
            }

            $group_form_where = [
                'is_del' => 0,
            ];
            $form_code_arr = isset($arr['form_code_arr']) ? $arr['form_code_arr'] : [];
            if(!empty($form_code_arr)){
                $group_form_where['code'] = $form_code_arr;
            }
            $item_form_arr = $this->LocalService()->itemForm->getGroupForm($item_form_where,$group_form_where);

            $patientFormArr = $this->LocalService()->patientForm->getFormCountByPatient($arr);

            $content_arr = $arr;
            $content_arr['form_id_arr'] = $item_form_arr;
            $checktimeFormArr = $this->LocalService()->itemCheckcontent->getFormByChecktime($content_arr);
            $patientCheckcontentFormArr = $this->LocalService()->itemPatientcheckcontent->getFormByPatientchecktime($content_arr);
            foreach($datas as $key=>$data){
                $patientchecktime_id = $data['id'];
                $patient_id = $data['patient_id'];
                $checktime_id = $data['checktime_id'];

                $overCount = isset($patientFormArr['over'][$patientchecktime_id]) && !empty($patientFormArr['over'][$patientchecktime_id]) ? $patientFormArr['over'][$patientchecktime_id] : 0;

                $patientForm = isset($patientFormArr['form'][$patientchecktime_id]) && !empty($patientFormArr['form'][$patientchecktime_id]) ? $patientFormArr['form'][$patientchecktime_id] : [];
                $patientoverForm = isset($patientFormArr['over_form'][$patientchecktime_id]) && !empty($patientFormArr['over_form'][$patientchecktime_id]) ? $patientFormArr['over_form'][$patientchecktime_id] : [];
                $checktimeForm = $checktimeRequiredForm = [];
                if(!empty($checktime_id)){//计划内检查点
                    $checktimeForm = isset($checktimeFormArr['all'][$checktime_id]) && !empty($checktimeFormArr['all'][$checktime_id]) ? $checktimeFormArr['all'][$checktime_id] : [];
                    $checktimeRequiredForm = isset($checktimeFormArr['select'][$checktime_id]) && !empty($checktimeFormArr['select'][$checktime_id]) ? $checktimeFormArr['select'][$checktime_id] : [];
                }else{//计划外检查点
                    $checktimeForm = isset($patientCheckcontentFormArr['all'][$patientchecktime_id]) && !empty($patientCheckcontentFormArr['all'][$patientchecktime_id]) ? $patientCheckcontentFormArr['all'][$patientchecktime_id] : [];
                    $checktimeRequiredForm = isset($patientCheckcontentFormArr['select'][$patientchecktime_id]) && !empty($patientCheckcontentFormArr['select'][$patientchecktime_id]) ? $patientCheckcontentFormArr['select'][$patientchecktime_id] : [];
                }

                //表单总数
                $allCount = count($checktimeForm);
                $allForm = empty($checktimeForm) ? [] : $checktimeForm;
                $overForm = empty($patientoverForm) ? [] : $patientoverForm;
                if(!empty($patientForm)){
                    $allCount = count($patientForm);
                    $allForm = empty($patientForm) ? [] : $patientForm;
                    if(!empty($checktimeForm)){
                        $allCount = $overCount;
                        foreach($checktimeForm as $checktimeFormId){
                            if(!in_array($checktimeFormId,$patientForm)){
                                $allCount += 1;
                                $allForm[$checktimeFormId] = $checktimeFormId;
                            }
                        }
                    }
                }

                //表单必做数
                $requiredCount = count($checktimeRequiredForm);
                $requiredForm = empty($checktimeRequiredForm) ? [] : $checktimeRequiredForm;
                if(!empty($patientoverForm)){
                    foreach($patientoverForm as $patientoverFormId){
                        if(!in_array($patientoverFormId,$checktimeRequiredForm) && !in_array($patientoverFormId,$checktimeForm)){
                            $requiredCount += 1;
                            $requiredForm[$patientoverFormId] = $patientoverFormId;
                        }
                    }
                }
                if($form_count == 1){
                    $datas[$key]['form_over_count'] = $overCount;//表单完成数
                    $datas[$key]['form_all_count'] = $allCount;//表单总数
                    $datas[$key]['form_required_count'] = $requiredCount;//表单必做数
                }else{
                    $datas[$key]['form_all_info'] = $allForm;//总表单信息
                    $datas[$key]['form_ove_info'] = $overForm;//完成表单信息
                    $datas[$key]['form_required_info'] = $requiredForm;//必做表单信息
                }
            }
        }
        return $datas;
    }

    public function getnewPatientChecktimeDatas($arr=[],$where,$select_columns=[]){
        $form_count = 0;//是否获取表单数据【0 否 1 是】
        $columns = [];
        if(in_array('form_count',$select_columns)){
            $form_count = 1;
            $form_count_key = array_keys($select_columns,'form_count');
            unset($select_columns[$form_count_key[0]]);
        }
        if(in_array('form_info',$select_columns)){
            $form_count = 2;
            $form_count_key = array_keys($select_columns,'form_info');
            unset($select_columns[$form_count_key[0]]);
        }

        //获取受试者检查点信息
        $datas = [];
        $where_arr = [
            'where'=>$where,
            'columns'=>$select_columns,
            'order'=>['check_order']
        ];
        $datas = $this->fetchAll($where_arr);

        if(in_array($form_count,[1,2]) && !empty($datas)){
            $item_id = isset($arr['item_id']) ? $arr['item_id'] : 0;//副项目ID
            $itemsig_id = isset($arr['itemsig_id']) ? $arr['itemsig_id'] : 0;
            //获取随机分组、贯穿全程类、常规类、检查类（OCR识别）表单ID
            $item_form_where = [
                'is_del' => 0,
            ];
            if(!empty($item_id)){
                $item_form_where['item_id'] = $item_id;
            }

            $group_form_where = [
                'is_del' => 0,
            ];
            $form_code_arr = isset($arr['form_code_arr']) ? $arr['form_code_arr'] : [];
            if(!empty($form_code_arr)){
                $group_form_where['code'] = $form_code_arr;
            }
            $item_form_arr = $this->LocalService()->itemForm->getGroupForm($item_form_where,$group_form_where);

            $patientFormArr = $this->LocalService()->patientForm->getFormCountByPatient($arr);
            //print_r($patientFormArr);die;
            $content_arr = $arr;
            $content_arr['form_id_arr'] = $item_form_arr;
            $checktimeFormArr = $this->LocalService()->itemCheckcontent->getFormByChecktime($content_arr);
            $patientCheckcontentFormArr = $this->LocalService()->itemPatientcheckcontent->getFormByPatientchecktime($content_arr);

            //查询当前检查点以及表单
            $checkcontentWhere['where'] = [
                'is_del' => 0,
                'item_id' => $item_id,
            ];
            $checkcontentWhere['columns'] = ['id', 'form_id', 'check_id','associated_ishide'];
            $checkcontentWhere['order'] = 'order';
            $checkcontent = $this->LocalService()->itemCheckcontent->fetchAll($checkcontentWhere);
            foreach($checkcontent as $k=>$v){
                if($v['associated_ishide'] == 1){
                    $associated_ishide[] = $v['form_id'];
                }
            };

                $str = array_unique(array_column($checkcontent,'form_id'));

                $relation_forms = [
                    'relation_ids' => [],
                    'relation_form_ids' => [],
                ];
                //被关联表单数组
               //查询当前表单是不是为二级 如果是 查询一级表单是否做过 未做过不显示
                if(!empty($str)){
                    $FormRelationwhere['where'] = [
                        'is_del' => 0,
                        'relation_form_id' => $str,
                    ];
                    if(!empty($associated_ishide)){
                        $FormRelationwhere['where'][] = new NotIn('relation_form_id', $associated_ishide);
                    }
                    $FormRelationwhere['columns'] = ['form_id','relation_form_id'];
                    $FormRelationDatas=$this->LocalService()->itemFormRelation->fetchAll($FormRelationwhere);
                    if(!empty($FormRelationDatas)){
                        foreach ($FormRelationDatas as $FormRelationData){
                            $relation_forms['relation_ids'][] = $FormRelationData['relation_form_id'];
                            $relation_forms['relation_form_ids'][$FormRelationData['relation_form_id']] = $FormRelationData['form_id'];
                        }
                    }
                    unset($FormRelationDatas);
                }
                unset($checkcontent);
               //查询关联表单是否填写
               $patientchecktimeform_datas = $this->LocalService()->itemPatientChecktimeForm->fetchAll([
                   'where' => [
                       'is_del' => 0,
                       'item_id' => $item_id,
                   ],
                   'columns'=>['id','form_id','checktime_id','patient_id','item_id','itemsig_id']
               ]);

               $patientchecktime_forms = [];  //表单填写信息
               if(!empty($patientchecktimeform_datas)){
                   foreach ($patientchecktimeform_datas as $patientchecktimeform_data){
                       $patientchecktime_forms[$patientchecktimeform_data['item_id']][$patientchecktimeform_data['itemsig_id']][$patientchecktimeform_data['checktime_id']][$patientchecktimeform_data['form_id']][$patientchecktimeform_data['patient_id']][] =$patientchecktimeform_data['id'];
                   }
               }

               unset($patientchecktimeform_datas);

            foreach($datas as $key=>$data){
                $patientchecktime_id = $data['id'];
                $patient_id = $data['patient_id'];
                $checktime_id = $data['checktime_id'];
                $overCount = isset($patientFormArr[$patient_id][$checktime_id]['over']) && !empty($patientFormArr[$patient_id][$checktime_id]['over']) ? $patientFormArr[$patient_id][$checktime_id]['over'] : 0;
                $patientForm = isset($patientFormArr[$patient_id][$checktime_id]['form']) && !empty($patientFormArr[$patient_id][$checktime_id]['form']) ? $patientFormArr[$patient_id][$checktime_id]['form'] : [];
                $patientoverForm = isset($patientFormArr[$patient_id][$checktime_id]['over_form']) && !empty($patientFormArr[$patient_id][$checktime_id]['over_form']) ? $patientFormArr[$patient_id][$checktime_id]['over_form'] : [];
                $checktimeForm = $checktimeRequiredForm = [];
                if(!empty($checktime_id)){//计划内检查点
                    $checktimeForm = isset($checktimeFormArr['all'][$checktime_id]) && !empty($checktimeFormArr['all'][$checktime_id]) ? $checktimeFormArr['all'][$checktime_id] : [];
                    $checktimeRequiredForm = isset($checktimeFormArr['select'][$checktime_id]) && !empty($checktimeFormArr['select'][$checktime_id]) ? $checktimeFormArr['select'][$checktime_id] : [];
                }else{//计划外检查点
                    $checktimeForm = isset($patientCheckcontentFormArr['all'][$patientchecktime_id]) && !empty($patientCheckcontentFormArr['all'][$patientchecktime_id]) ? $patientCheckcontentFormArr['all'][$patientchecktime_id] : [];
                    $checktimeRequiredForm = isset($patientCheckcontentFormArr['select'][$patientchecktime_id]) && !empty($patientCheckcontentFormArr['select'][$patientchecktime_id]) ? $patientCheckcontentFormArr['select'][$patientchecktime_id] : [];
                }

                $allCount = count($checktimeForm);
                $allForm = empty($checktimeForm) ? [] : $checktimeForm;
                $overForm = empty($patientoverForm) ? [] : $patientoverForm;

                //表单必做数
                $requiredCount = count($checktimeRequiredForm);
                $requiredForm = empty($checktimeRequiredForm) ? [] : $checktimeRequiredForm;
                if(!empty($patientoverForm)){
                    foreach($patientoverForm as $patientoverFormId){
                        if(!in_array($patientoverFormId,$checktimeRequiredForm) && !in_array($patientoverFormId,$checktimeForm)){
                            $requiredCount += 1;
                            $requiredForm[$patientoverFormId] = $patientoverFormId;
                        }
                    }
                }

                //如果是个被关联的表单 并且主表单未填写或者是主表单填写的值未触发  则不应该显示这个被关联的表单
                if(!empty($requiredForm)) {
                    foreach ($requiredForm as $requiredFormid) {
                        if(in_array($requiredFormid,$relation_forms['relation_ids'])){
                            $relation_forminfos = isset($patientchecktime_forms[$item_id][$itemsig_id][$checktime_id][$requiredFormid][$patient_id]) && !empty($patientchecktime_forms[$item_id][$itemsig_id][$checktime_id][$requiredFormid][$patient_id]) ? $patientchecktime_forms[$item_id][$itemsig_id][$checktime_id][$requiredFormid][$patient_id] : [];
                            if(empty($relation_forminfos)){
                                 unset($requiredForm[$requiredFormid]);
                            }
                        }
                    }
                }

                if($form_count == 1){
                    $datas[$key]['form_over_count'] = $overCount;//表单完成数
                    $datas[$key]['form_all_count'] = $allCount;//表单总数
                    $datas[$key]['form_required_count'] = $requiredCount;//表单必做数
                }else{
                    $datas[$key]['form_all_info'] = $allForm;//总表单信息
                    $datas[$key]['form_ove_info'] = $overForm;//完成表单信息
                    $datas[$key]['form_required_info'] = $requiredForm;//必做表单信息
                }
            }
        }
        return $datas;
    }

    /**
     * Notes: 获取对应中止状态下的order值
     * @param
     * @return
     * @author haojinhua
     * @date 2024-12-19
     */
    public function getcheckOrderDatas($where){
        $res = [];
        $where_arr = [
            'where'=>$where,
            'columns'=>['id','patient_id','check_order'],
            'order'=>['check_order']
        ];
        $datas = $this->fetchAll($where_arr);
        if(!empty($datas)){
            foreach ($datas as $data){
                $res[$data['patient_id']] = $data['check_order'];
            }
        }
        unset($datas);
        return $res;
    }

    /**
     * Notes:获取指定键值下的受试者检查点信息
     * User: lltyy
     * DateTime: 2022/9/21 14:53
     *
     * @param $where //查询条件
     * @param array $columns //查询字段
     * @param array $order //排序值
     * @param array $key_arr //键值数组【键值=>数据类型（0 单笔 1 多笔）】
     * @return array
     * @return array
     */
    public function getPatientChecktimeByKey($where,$columns=[],$order=[],$key_arr=[]){
        $datas = [];
        $where_cond = [
            'where'=>$where,
            'columns'=>$columns,
            'order'=>$order
        ];
        $patientchecktimes = $this->fetchAll($where_cond);
        if(!empty($patientchecktimes)){
            foreach($patientchecktimes as $patientchecktime){
                foreach($key_arr as $key=>$data_type){
                    $key_id = $patientchecktime[$key];
                    if($data_type == 1){
                        $datas[$key][$key_id][] = $patientchecktime;
                    }else{
                        $datas[$key][$key_id] = $patientchecktime;
                    }
                }
            }
        }
        return $datas;
    }

    /**
     * Notes:根据受试者脱离状态变更受试者试验总结类检查点名称
     * @param $patient_id
     * @param $item_id
     */
    public function getpatientTestsummaryNam($patient_id)
    {
        //查询当前受试者状态
        $patientWhere['where'] = [
            'is_del' => 0,
            'id' => $patient_id,
        ];
        $patientWhere['columns'] = ['patient_status'];
        $patientinfo = $this->LocalService()->patient->fetchOne($patientWhere);
        if($patientinfo['patient_status'] == 9){
            return "试验总结检查点";
        }
        if($patientinfo['patient_status'] == 1){
            $checkName = "试验脱落";
        }elseif($patientinfo['patient_status'] == 2){
            $checkName = "试验筛败";
        }elseif($patientinfo['patient_status'] == 3){
            $checkName = "试验完成";
        }elseif($patientinfo['patient_status'] == 4) {
            $checkName = "试验中止";
        }
        return $checkName;
    }

    //变更受试者锚点ID
    public function updatepatientanchor($checktime_id,$anchor_id)
    {
        $this->update(['anchor_id'=>$anchor_id],['checktime_id'=>$checktime_id,'is_del'=>0]);
    }

    public function updatePatientchecktime($item_id){
        //受试者数据
        $Patientwhere['where']= [
            'is_del' => 0,
            'patient_status' => 9,
            'item_id' => $item_id,
        ];
        $Patientwhere['columns']=['id','item_id'];
        $patientInfo=$this->LocalService()->patient->fetchAll($Patientwhere);
        if(!empty($patientInfo)){
            foreach ($patientInfo as $k=>$v){
                $this->EditPatientChecktimeStatus($v['item_id'],$v['id']);
            }
        }
    }



    public function handleanchortime($arr)
    {
        $checktime_id = $arr['checktime_id'];
        $anchor_id = $arr['anchor_id'];
        $unit = $arr['unit'];
        $start_time = $arr['start_time'];
        $end_time = $arr['end_time'];
        //查询当前项目所有的受试者检查点
        $patientchecktimeWhere['where'] = [
            'checktime_id' => $checktime_id,
            'is_del' => 0,
            new Operator('anchor_id', Operator::OP_NE, $anchor_id),
        ];
        $patientchecktimeWhere['columns'] = ['id','item_id','patient_id','anchor_id','anchor_date','check_order'];
        $patientchecktimeWhere['order'] = 'patient_id';
        $patientchecktimeDatas = $this->fetchAll($patientchecktimeWhere);
        if(empty($patientchecktimeDatas)) return true;

        foreach($patientchecktimeDatas as $k=>$v){
            //获取当前受试者锚点ID指定日期
            $info = $this->fetchOne(['where'=>[
                'patient_id' => $v['patient_id'],
                'is_del' => 0,
                'anchor_id' => $anchor_id,
            ],'columns'=>['anchor_date']]);
            //如果没有填写过则跳过
            if(empty($info)) continue;

            $time_unit='';
            switch ($unit){
                case 0 :$time_unit='day';break;
                case 1 :$time_unit='week';break;
                case 2 :$time_unit='month';break;
                case 3 :$time_unit='year';break;
            }

            if($start_time>0){
                $plan_start_date=strtotime(+($start_time-1).' '.$time_unit,$info['anchor_date']);
            }else{
                $start_time1=ltrim($start_time,'-');
                $plan_start_date=strtotime(-$start_time1.' '.$time_unit,$info['anchor_date']);
            }
            if($end_time>0){
                $plan_end_date=strtotime(+($end_time-1).' '.$time_unit,$info['anchor_date']);
            }else{
                $end_time1=ltrim($end_time,'-');
                $plan_end_date=strtotime(-$end_time1.' '.$time_unit,$info['anchor_date']);
            }
            //获取上一个受试者检查点信息
            $prevchecktimeWhere['where'] = [
                'is_del' => 0,
                'patient_id' => $v['patient_id'],
                new Operator('check_order', Operator::OP_LT, $v['check_order']),
            ];
            $prevchecktimeWhere['order'] = 'check_order desc';
            $prevchecktimeWhere['columns'] = ['id'];
            $prevchecktime = $this->fetchOne($prevchecktimeWhere);

            if(!empty($prevchecktime)){
                $this->update(['plan_end_date'=>$plan_start_date],[
                    'id' => $prevchecktime['id']
                ]);
            }
            $result=$this->update(
                [
                    'anchor_date'=>$info['anchor_date'],
                    'plan_start_date'=>$plan_start_date,
                    'plan_end_date'=>$plan_end_date
                ],[
                    'id' => $v['id']
            ]);
        }
    }

    public function itemanchor()
    {
        $this->EditPatientChecktimeStatus(1085,5599);
    }


    /**
     * 获取上一个锚点下最后一个检查点
     */
    public function _getPropAnchorChecktime($item_id)
    {
        $Checktimewhere['where'] = [
            'is_del' => 0,
            'item_id' => $item_id,
        ];
        $checktimeDatas=$this->LocalService()->itemChecktime->fetchAll($Checktimewhere);

        foreach($checktimeDatas as $k=>$v){
            var_dump($v);die;
        }
    }

    /**
     * Notes: 获取当日预约的患者数已进入窗口期未预约的患者数
     * User: lltyy
     * DateTime: 2024/11/18 8:17
     *
     * @param array $info
     * @return array
     */
    public function fetchMakeSigPatient(array $info = []){
        //当前日期时间戳
        $now_date = isset($info['now_date']) && $info['now_date'] != '' ? strtotime($info['now_date'].' 00:00:00') : strtotime(date('Y-m-d').' 00:00:00');
        $return_type = isset($info['return_type']) && !empty($info['return_type']) ? $info['return_type'] : 0;//返回类型 0 中心项目患者
        $item_id = isset($info['item_id']) && !empty($info['item_id']) ? $info['item_id'] : 0;//副项目ID
        $itemsig_id = isset($info['itemsig_id']) && !empty($info['itemsig_id']) ? $info['itemsig_id'] : 0;//项目中心ID

        //获取患者检查点信息
        $arr = [];
        $where = (new Where())->equalTo('is_del', 0)
                        ->nest()
                            ->equalTo('make_time', $now_date)
                            ->or
                            ->nest()
                                ->equalTo('is_now_state', 1)
                                ->nest()
                                    ->isNull('make_time')
                                    ->or
                                    ->equalTo('make_time', 0)
                                    ->or
                                    ->equalTo('make_time', '')
                                ->unnest()
                            ->unnest()
                        ->unnest();

        if(!empty($item_id)){
            $where->equalTo('item_id', $item_id);
        }
        if(!empty($itemsig_id)){
            $where->equalTo('itemsig_id', $itemsig_id);
        }
        $datas = $this->fetchAll([
            'where'=>$where,
            'columns'=>['item_id','itemsig_id','patient_id','make_time','is_now_state'],
            'order'=>['id']
        ]);
        unset($where);
        if(!empty($datas)){
            foreach($datas as $key=>$data){
                $data_item = $data['item_id'];
                $data_itemsig = $data['itemsig_id'];
                $data_patient = $data['patient_id'];
                //当日预约患者
                if(!empty($data['make_time']) && $data['make_time'] == $now_date){
                    if($return_type == 0){
                        $arr['now_make'][$data_itemsig][$data_item] = isset($arr['now_make'][$data_itemsig][$data_item]) && !empty($arr['now_make'][$data_itemsig][$data_item]) ? $arr['now_make'][$data_itemsig][$data_item] : [];
                        $arr['send_mes_sig'] = isset($arr['send_mes_sig']) && !empty($arr['send_mes_sig']) ? $arr['send_mes_sig'] : [];//需要提醒预约信息的中心
                        $arr['send_mes_item'] = isset($arr['send_mes_item']) && !empty($arr['send_mes_item']) ? $arr['send_mes_item'] : [];//需要提醒信息的项目
                        if(!in_array($data_patient,$arr['now_make'][$data_itemsig][$data_item])){
                            $arr['now_make'][$data_itemsig][$data_item][] = $data_patient;
                            if(!in_array($data_itemsig,$arr['send_make_sig'])){
                                $arr['send_mes_sig'][] = $data_itemsig;
                            }
                            if(!in_array($data_item,$arr['send_mes_item'])){
                                $arr['send_mes_item'][] = $data_item;
                            }
                        }
                    }
                }
                //已进入窗口期未预约的患者
                if(empty($data['make_time']) && $data['is_now_state'] == 1){
                    if($return_type == 0){
                        $arr['no_make'][$data_itemsig][$data_item] = isset($arr['no_make'][$data_itemsig][$data_item]) && !empty($arr['no_make'][$data_itemsig][$data_item]) ? $arr['no_make'][$data_itemsig][$data_item] : [];
                        $arr['send_mes_sig'] = isset($arr['send_mes_sig']) && !empty($arr['send_mes_sig']) ? $arr['send_mes_sig'] : [];//需要提醒预约信息的中心
                        $arr['send_mes_item'] = isset($arr['send_mes_item']) && !empty($arr['send_mes_item']) ? $arr['send_mes_item'] : [];//需要提醒信息的项目
                        if(!in_array($data_patient,$arr['no_make'][$data_itemsig][$data_item])){
                            $arr['no_make'][$data_itemsig][$data_item][] = $data_patient;
                            if(!in_array($data_itemsig,$arr['send_mes_sig'])){
                                $arr['send_mes_sig'][] = $data_itemsig;
                            }
                            if(!in_array($data_item,$arr['send_mes_item'])){
                                $arr['send_mes_item'][] = $data_item;
                            }
                        }
                    }
                }

                //释放空间
                unset($data_item);
                unset($data_itemsig);
                unset($data_patient);
                unset($datas[$key]);
            }
        }

        return $arr;
    }

}
