<?php
namespace Application\Service\DB\Item;

use Application\Service\Extension\Helper\ArrayHelper;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Expression;
use Laminas\Db\Sql\Predicate\Operator;


class PatientChecktimeList extends \Application\Service\DB\AbstractDb {
    public function __construct($dbAdapter, ContainerInterface $container) {
        $this->tableName = 'yikeen_patient_checktime_list';
        parent::__construct($dbAdapter, $container);
    }
    private  array $AeAndSaeFlag = [
        'sae_flag'=>[],
        'ae_flag'=>[],
        'ae'=>'ae',
        'sae'=>'sae',
        'ae_type_flag'=>5,
        'sae_type_flag'=>3,
        'ae_order'=>10101110,
        'sae_order'=>10101111,
        'is_ae'=>0,
        'is_sae'=>0,
        'ae_id'=>-1,
        'sae_id'=>-2
    ];

    /**
     * Notes: 删除真实数据
     * return int 受影响的行数
     */
    public function delete($where){
        return $this->tableGateway->delete($where);
    }

    //数据查询
    public function patientChecktimeInsert($item_id = 0,$patient_id = 0,$more=0,$checktime_post_ids=0, $type=0){
        if(empty($item_id)) return false;

        //检查点
        $itemChecktimeWhere['where'] = [
            new Operator('is_del', Operator::OP_NE, 1),
            'item_id' => $item_id,
        ];

        //新增一个检查点=====
        if (!empty($checktime_post_ids)){
            $itemChecktimeWhere['where'] = [
                new Operator('is_del', Operator::OP_NE, 1),
                'item_id' => $item_id,
                'id' => explode(',', $checktime_post_ids),
            ];
        }
        $itemChecktimeWhere['columns'] = ['id','check_name','check_order','is_del','is_skip','patient_id','patientchecktime_id','stage_id','random_id'];
        $itemChecktimeWhere['order'] = ['check_order'];
        $itemChecktimeData = $this->LocalService()->itemChecktime->fetchAll($itemChecktimeWhere);
        //受试者
        $patientWhere['where'] = [
            'is_del' => 0,
            'item_id' => $item_id,
        ];

        //批量导入受试者
        if (!empty($more) && is_array($patient_id)){
            $patientWhere['where'] = ['is_del'=>0,'item_id'=>$item_id,'id'=>$patient_id];
        }else{
            if (!empty($patient_id)){
                $patientWhere['where']['id'] = is_array($patient_id) ? $patient_id : explode(',', $patient_id);
            }
        }

        $patientWhere['columns'] = ['id','item_id','itemsig_id','patient_number','patient_status'];
        $patientData = $this->LocalService()->patient->fetchAll($patientWhere);

        if (empty($patientData)){
            return false;
            echo '没有找到受试者';die;
        }

        if (!empty($itemChecktimeData)){
            $check_order  = 10000000;
            foreach ($itemChecktimeData as &$itemChecktimeDatumValues) {
                if ($itemChecktimeDatumValues['is_del'] == 9){
                    $itemChecktimeDatumValues['check_order'] = $check_order;
                    $check_order ++;
                }
            }
            array_multisort(array_column($itemChecktimeData,'check_order'), SORT_ASC, $itemChecktimeData);
        }

        $patientIdArr = array_column($patientData,'id');
        $itemsigIdArr = array_column($patientData,'itemsig_id');
        $itemChecktimeIdArr = array_column($itemChecktimeData,'id');
        $randomIds = implode(',',array_filter(array_unique(array_column($itemChecktimeData,'random_id'))));
        if(!empty($randomIds)){
            $itemRandomNameData = $this->LocalService()->itemRandom->fetchCol('random_name',[
                'is_del' => 0,
                'id' => array_filter(array_unique(array_column($itemChecktimeData,'random_id'))),
            ]);
            foreach ($itemChecktimeData as &$itemChecktimeDatumName) {
                $itemChecktimeDatumName['old_check_name'] = $itemChecktimeDatumName['check_name'];
                if (isset($itemRandomNameData[$itemChecktimeDatumName['random_id']])){
                    $itemChecktimeDatumName['check_name'] = $itemRandomNameData[$itemChecktimeDatumName['random_id']].'-'.$itemChecktimeDatumName['check_name'];
                    $itemChecktimeDatumName['random_names'] = $itemRandomNameData[$itemChecktimeDatumName['random_id']];
                    $itemChecktimeDatumName['random_ids'] = $itemRandomNameData[$itemChecktimeDatumName['random_id']];
                }else{
                    $itemChecktimeDatumName['random_names'] = '';
                    $itemChecktimeDatumName['random_ids'] = 0;
                }
            }
        }
        $itemFormWhere = [
            'where'=>[
                'item_id'=>$item_id,
                'is_del'=>0,
            ],
            'columns'=>[
                'id',
                'name',
                'item_id',
                'group_id',
                'except_checktime',

            ],
        ];
        $itemFormIdData = $this->LocalService()->itemForm->fetchAll($itemFormWhere);

        //******
            $form = [];
        //***********


        $AeAndSaeData = [];
        $patientAeAndSaeFlag = ['sae_flag'=>[],'ae_flag'=>[],'ae'=>'ae','sae'=>'sae','ae_type_flag'=>5,'sae_type_flag'=>3,'is_ae'=>0,'is_sae'=>0];
        $dictionaryFormGroupData = $this->LocalService()->dictionaryFormGroup->fetchCol('code',[
            'is_del' => 0,
            'code' => ['AE', 'SAE']
        ]);
       //处理AE和SAE类的
        if (!empty($itemFormIdData)){
            $dictionaryFormGroupDatas = $dictionaryFormGroupData?array_flip($dictionaryFormGroupData):[];
            if(!empty($dictionaryFormGroupDatas)){
                if(isset($dictionaryFormGroupDatas['AE'])){
                    $patientAeAndSaeFlag['ae_type_flag'] = $dictionaryFormGroupDatas['AE'];
                    $patientAeAndSaeFlag['is_ae'] = 1;

                }
                if(isset($dictionaryFormGroupDatas['SAE'])){
                    $patientAeAndSaeFlag['sae_type_flag'] = $dictionaryFormGroupDatas['SAE'];
                    $patientAeAndSaeFlag['is_sae'] = 1;

                }
            }
            foreach ($itemFormIdData as $itemFormIdDataKey=>$itemFormIdDataValue) {
                $form[$itemFormIdDataValue['id']] = $itemFormIdDataValue;
                if (in_array($itemFormIdDataValue['group_id'],$dictionaryFormGroupDatas)){
                    if (isset($AeAndSaeData[$itemFormIdDataValue['group_id']])){
                        $AeAndSaeData[$itemFormIdDataValue['group_id']][] = $itemFormIdDataValue['id'];//$AeAndSaeData[$itemFormIdDataValue['group_id']].','.$itemFormIdDataValue['id'];
                    }else{
                        $AeAndSaeData[$itemFormIdDataValue['group_id']][] = $itemFormIdDataValue['id'];

                    }
                }

            }
        }


        //ae总数
        $itemPatientAeContentDatas = [];
        if (isset($AeAndSaeData[$patientAeAndSaeFlag['ae_type_flag']]) && !empty($AeAndSaeData[$patientAeAndSaeFlag['ae_type_flag']])){
            $itemPatientAeContentWhere = [
                'where'=>[
                    'item_id'=>$item_id,
                    'is_del'=>0,
                    'form_id'=>$AeAndSaeData[$patientAeAndSaeFlag['ae_type_flag']],
                ],
                'columns'=>[
                    'id',
                    'count'=>new Expression('count(*)'),
                    'form_ids'=>new Expression('GROUP_CONCAT(form_id)'),
                    'ids'=>new Expression('GROUP_CONCAT(id)'),
                    'item_id',
                    'patient_id',

                ],
                'group' => ['patient_id'],
            ];
            $itemPatientAeContentData = $this->LocalService()->itemPatientAeContent->fetchAll($itemPatientAeContentWhere);
            !empty($itemPatientAeContentData) && $itemPatientAeContentDatas = array_column($itemPatientAeContentData,null,'patient_id');
        }

        //sae总数
        $itemPatientsAeContentDatas = [];
        if (isset($AeAndSaeData[$patientAeAndSaeFlag['sae_type_flag']]) && !empty($AeAndSaeData[$patientAeAndSaeFlag['sae_type_flag']])){
            $itemPatientsAeContentWhere = [
                'where'=>[
                    'item_id'=>$item_id,
                    'is_del'=>0,
                    'form_id'=>$AeAndSaeData[$patientAeAndSaeFlag['sae_type_flag']],
                ],
                'columns'=>[
                    'id',
                    'count'=>new Expression('count(*)'),
                    'form_ids'=>new Expression('GROUP_CONCAT(form_id)'),
                    'ids'=>new Expression('GROUP_CONCAT(id)'),
                    'item_id',
                    'patient_id',

                ],
                'group' => ['patient_id'],
            ];
            $itemPatientsAeContentData = $this->LocalService()->patientFormContent->fetchAll($itemPatientsAeContentWhere);
            !empty($itemPatientsAeContentData) && $itemPatientsAeContentDatas = array_column($itemPatientsAeContentData,null,'patient_id');
        }

        $itemFormIdDatas = $itemFormIdData?array_column($itemFormIdData,'id'):[];

        $dictionaryDSFormGroupid = $this->LocalService()->dictionaryFormGroup->getOneFieldVal('id','is_del= 0 and code = "DS"');
        $dsform_id = $this->LocalService()->itemForm->getOneFieldVal('id','is_del= 0 and group_id = '.$dictionaryDSFormGroupid.' and item_id ='.$item_id);

//        echo '<pre>';print_r(implode(',',$itemFormIdDatas));die;

        $itemCheckcontentWhere = [
            'where'=>[
                'check_id'=>$itemChecktimeIdArr,
                'item_id'=>$item_id,
                'form_id'=>$itemFormIdDatas,//表单未删除的
                'is_del'=>0,
            ],
            'columns'=>[
                'count'=>new Expression('count(*)'),
                'form_ids'=>new Expression('GROUP_CONCAT(form_id)'),
                'id',
                'check_id',
                'item_id',
                'form_id',
            ],
            'group' => ['check_id'],

        ];
        $itemCheckcontentData = $this->LocalService()->itemCheckcontent->fetchAll($itemCheckcontentWhere);

        if(!empty($itemCheckcontentData)){

            foreach ($itemCheckcontentData as $contentK => $contentV)
            {
                $formArr = explode(',',$contentV['form_ids']);
                if (!empty($formArr)){
                    foreach ($formArr as $formK => $formV){
                        if (isset($form[$formV])){
                            if(!empty($form[$formV]['except_checktime'])  && $form[$formV]['group_id'] == 4){
                                if(in_array($contentV['check_id'],explode(',',$form[$formV]['except_checktime']))){
                                    $itemCheckcontentData[$contentK]['count'] -= 1;
                                    unset($formArr[$formK]);
                                    continue;
                                }
                            }
                        }

                    }
                    $itemCheckcontentData[$contentK]['form_ids'] = implode(',',$formArr);
                }

            }



            $itemCheckcontentDatas = array_column($itemCheckcontentData,null,'check_id');
            foreach ($itemChecktimeData as &$itemChecktimeDatum) {
                $itemChecktimeDatum['count'] = 0;
                $itemChecktimeDatum['form_ids'] = '';
                if (isset($itemCheckcontentDatas[$itemChecktimeDatum['id']])){
                    $itemChecktimeDatum['count'] = $itemCheckcontentDatas[$itemChecktimeDatum['id']]['count'];
                    $itemChecktimeDatum['form_ids'] = $itemCheckcontentDatas[$itemChecktimeDatum['id']]['form_ids'];
                }else{
                    //试验总结类的不会设置对应的表单
                    $itemChecktimeDatum['count'] = 1;
                    $itemChecktimeDatum['form_ids'] = $dsform_id ;
                }
            }
        }

        $itemPatientchecktimeWhere = [
            'where'=>[
                'checktime_id' =>$itemChecktimeIdArr,
                'patient_id'=>$patientIdArr,
                'is_skip'=>[0,2],//只有0和2 1为跳过
                'is_del'=>0,
                'item_id'=>$item_id,
//                'form_id'=>$itemFormIdDatas,//表单未删除的

            ],
            'columns'=>[
                'checktime_ids'=>new Expression('GROUP_CONCAT(checktime_id)'),
                'id',
                'item_id',
                'patient_id',
                'checktime_id',
                'itemsig_id',
                'is_skip',
            ],
        ];
        $itemPatientchecktimeWhere['group'] = ['patient_id'];
        $itemPatientchecktimeData = $this->LocalService()->itemPatientchecktime->fetchAll($itemPatientchecktimeWhere);
        $itemPatientchecktimeDatas = $itemPatientchecktimeData?array_column($itemPatientchecktimeData,null,'patient_id'):[];
//        echo '<pre>';print_r($itemPatientchecktimeDatas);die;
        //受试者检查点工作内容表
        $patientchecktimeIdArr = array_filter(array_column($itemChecktimeData,'patientchecktime_id','id'));
        $itemPatientcheckcontentWhere = [
            'where'=>[
                'patientchecktime_id' =>$patientchecktimeIdArr?:0,
                'patient_id'=>$patientIdArr,
                'item_id'=>$item_id,
                'is_del'=>0,
                'form_id'=>$itemFormIdDatas,//表单未删除的

            ],
            'columns'=>[
                'count'=>new Expression('count(*)'),
                'form_ids'=>new Expression('GROUP_CONCAT(form_id)'),
                'item_id',
                'patient_id',
                'itemsig_id',
                'patientchecktime_id',
                'form_id',

            ],
            'group' => ['patientchecktime_id'],

        ];
        $itemPatientcheckcontentData = $this->LocalService()->itemPatientcheckcontent->fetchAll($itemPatientcheckcontentWhere);
        if(!empty($itemPatientcheckcontentData)){
            $itemPatientcheckcontentDatas = array_column($itemPatientcheckcontentData,null,'patientchecktime_id');
            foreach ($itemChecktimeData as &$itemChecktimeDatum2) {
                if (isset($itemPatientcheckcontentDatas[$itemChecktimeDatum2['patientchecktime_id']])){
                    $itemChecktimeDatum2['count'] = $itemPatientcheckcontentDatas[$itemChecktimeDatum2['patientchecktime_id']]['count']+$itemChecktimeDatum2['count'];
                    if(!empty($itemChecktimeDatum2['form_ids'])){
                        $itemChecktimeDatum2['form_ids'] = $itemPatientcheckcontentDatas[$itemChecktimeDatum2['patientchecktime_id']]['form_ids'].','.$itemChecktimeDatum2['form_ids'];

                    }else{
                        $itemChecktimeDatum2['form_ids'] = $itemPatientcheckcontentDatas[$itemChecktimeDatum2['patientchecktime_id']]['form_ids'];

                    }
                }
            }
        }

        //已完成的工作===yikeen_item_patient_form
        $patientFormWhere = [
            'where'=>[
                'checktime_id' =>$itemChecktimeIdArr,
                'patient_id'=>$patientIdArr,
                'item_id'=>$item_id,
                'is_del'=>0,
                'form_id'=>$itemFormIdDatas,//表单未删除的
                'itemsig_id'=>$itemsigIdArr,//中心


            ],
            'columns'=>[
                'count'=>new Expression('count(*)'),
                'is_completes'=>new Expression('GROUP_CONCAT(is_complete)'),
                'checktime_ids'=>new Expression('GROUP_CONCAT(checktime_id)'),
                'form_ids'=>new Expression('GROUP_CONCAT(form_id)'),
                'patientchecktime_ids'=>new Expression('GROUP_CONCAT(patientchecktime_id)'),
                'item_id',
                'form_id',
                'checktime_id',
                'patient_id',
                'itemsig_id',
                'patientchecktime_id',

            ],
        ];
        $patientFormWhere['group'] = ['checktime_id','patient_id'];//,'patient_id'
        $itemPatientFormData = $this->LocalService()->patientForm->fetchAll($patientFormWhere);
        $itemPatientFormDatas = [];
        foreach ($itemPatientFormData as $itemPatientFormDataKey=>&$itemPatientFormDataValue) {

            $isCompleteArr = explode(',',$itemPatientFormDataValue['is_completes']);
            $isCompleteFormArrIdArr = array_unique(explode(',',$itemPatientFormDataValue['form_ids']));
            $is_complete = array_unique($isCompleteArr);
            $itemPatientFormDataValue['is_complete_flag'] = 0;
            if(in_array(1,$isCompleteArr)){
                $itemPatientFormDataValue['is_complete_flag'] = 1;
            }

            //已完成的个数
            $itemPatientFormDataValue['count'] = count($isCompleteFormArrIdArr);//count($isCompleteArr);

            if (isset($itemPatientFormDatas[$itemPatientFormDataValue['patient_id'].'-'.$itemPatientFormDataValue['checktime_id']])){
                $itemPatientFormDatas[$itemPatientFormDataValue['patient_id'].'-'.$itemPatientFormDataValue['checktime_id']] = $itemPatientFormDataValue;

            }else{
                $itemPatientFormDatas[$itemPatientFormDataValue['patient_id'].'-'.$itemPatientFormDataValue['checktime_id']] = $itemPatientFormDataValue;

            }
        }

        $patientWorkCount = [];
        //is_complete_flag:0为未完成,1为已完成 ,2空白
        foreach ($patientData as $patientDataKey=>&$patientDataValue) {
            $patientWorkCount[$patientDataKey]['patient_id'] = $patientDataValue['id'];
            $patientWorkCount[$patientDataKey]['item_id'] = $patientDataValue['item_id'];
            $patientWorkCount[$patientDataKey]['itemsig_id'] = $patientDataValue['itemsig_id'];
            $patientWorkCount[$patientDataKey]['patient_number'] = $patientDataValue['patient_number'];

            //ae  sae
            $newtemPatientsAeContentDatas = $newtemPatientaEContentDatas = [
                'count'=>0,
                'is_pass'=>1,
                'id'=>$this->AeAndSaeFlag['ae_id'],
//                'ae_type'=>0,
                'form_ids'=>'',
                'question_count_r'=>0,
                'clear_question_count_r'=>0,
                'colse_question_count_r'=>0,

                //s判断==
                'question_count_s'=>0,
                'clear_question_count_s'=>0,
                'colse_question_count_s'=>0,

                'question_count'=>0,
                'clear_question_count'=>0,
                'colse_question_count'=>0,
                'confirm_approve_count'=>0,
                'is_complete'=>0,
                'is_complete_flag'=>4,
                'lock_count'=>0,
                'lock_flag'=>0,
                'complete_ids'=>'',
            ];
            $newtemPatientaEContentDatas['check_name'] = $patientAeAndSaeFlag['ae'];
            $newtemPatientaEContentDatas['ae_type'] = 0;
            $newtemPatientaEContentDatas['check_order'] = $this->AeAndSaeFlag['ae_order'];

            $newtemPatientsAeContentDatas['sae_type'] = 0;
            $newtemPatientsAeContentDatas['check_name'] = $patientAeAndSaeFlag['sae'];
            $newtemPatientsAeContentDatas['check_order'] = $this->AeAndSaeFlag['sae_order'];
            $newtemPatientsAeContentDatas['id'] = $this->AeAndSaeFlag['sae_id'];

            if (!empty($itemPatientAeContentDatas)){
                if (isset($itemPatientAeContentDatas[$patientDataValue['id']])){
                    $patientAeAndSaeFlag['ae_flag'][] = $patientDataValue['itemsig_id'];
                    $newtemPatientaEContentDatas['count'] = 1;//$itemPatientAeContentDatas[$patientDataValue['id']]['count'];
                    $newtemPatientaEContentDatas['is_complete'] = 1;//$itemPatientAeContentDatas[$patientDataValue['id']]['count'];
                    $newtemPatientaEContentDatas['check_name'] = $patientAeAndSaeFlag['ae'];
                    $newtemPatientaEContentDatas['form_ids'] = $itemPatientAeContentDatas[$patientDataValue['id']]['form_ids'];
                    $newtemPatientaEContentDatas['complete_ids'] = $itemPatientAeContentDatas[$patientDataValue['id']]['ids'];
                    $newtemPatientaEContentDatas['is_pass'] = 0;
                    $newtemPatientaEContentDatas['is_complete_flag'] = 1;


                }
            }

            if (!empty($itemPatientsAeContentDatas)){
                if (isset($itemPatientsAeContentDatas[$patientDataValue['id']])){
                    $patientAeAndSaeFlag['sae_flag'][] = $patientDataValue['itemsig_id'];
                    $newtemPatientsAeContentDatas['count'] = 1;//$itemPatientsAeContentDatas[$patientDataValue['id']]['count'];
                    $newtemPatientsAeContentDatas['is_complete'] = 1;//$itemPatientsAeContentDatas[$patientDataValue['id']]['count'];
                    $newtemPatientsAeContentDatas['check_name'] = $patientAeAndSaeFlag['sae'];
                    $newtemPatientsAeContentDatas['form_ids'] = $itemPatientsAeContentDatas[$patientDataValue['id']]['form_ids'];
                    $newtemPatientsAeContentDatas['complete_ids'] = $itemPatientsAeContentDatas[$patientDataValue['id']]['ids'];
                    $newtemPatientsAeContentDatas['is_pass'] = 0;
                    $newtemPatientsAeContentDatas['is_complete_flag'] = 1;
                }
            }

            $patientDataValue['itemChecktimeData'] = array_column($itemChecktimeData,null,'id');
            if (!empty($patientDataValue['itemChecktimeData'])){
                $work_count = 0;
                $is_plan = 0;
                $work_complete_count = 0;
                $batch_count_s_s = 0;
                $incomplete = 0;
                foreach ($patientDataValue['itemChecktimeData'] as $itemChecktimeDataKey=>$itemChecktimeDataValue) {
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['count_original'] = $itemChecktimeDataValue['count'];
                    $whereData = [
                        'count'=>$itemChecktimeDataValue['count'],
                        'checktime_id'=>$itemChecktimeDataValue['id'],
                        'item_id'=>$item_id,
                        'patient_id'=>$patientDataValue['id'],
                        'form_ids'=>$itemChecktimeDataValue['form_ids'],
                    ];
                    $itemChecktimeCountData = $this->itemChecktimeCount($whereData);
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['count'] = $itemChecktimeCountData['count'];
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['count_Relation'] = $itemChecktimeCountData['count_Relation'];
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['form_ids'] = $itemChecktimeCountData['form_ids'];
                    $work_count = $itemChecktimeCountData['count']+ $work_count;
                    if ($itemChecktimeDataValue['is_del'] == 2)  $is_plan = 1;
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['is_complete_flag'] = 2;

                    if (!empty($itemPatientchecktimeDatas)){
                        $checktimeIdArr  = isset($itemPatientchecktimeDatas[$patientDataValue['id']]['checktime_ids'])?explode(',',$itemPatientchecktimeDatas[$patientDataValue['id']]['checktime_ids']):[];
                        if (!empty($itemChecktimeDataValue['patient_id']) && $itemChecktimeDataValue['patient_id'] !=$patientDataValue['id']){
                            $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['is_complete_flag'] = 4;
                        }else{
                            if (!isset($itemChecktimeDataValue['id']) || !in_array($itemChecktimeDataValue['id'],$checktimeIdArr)){
                                $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['is_complete_flag'] = 4;
                            }
                        }
                    }

                    //新加==9-22
                    $batch_count_s = 0;
                    if (!empty($itemChecktimeDataValue['form_ids'])){
                        $formIdArr = explode(',',$itemChecktimeDataValue['form_ids']);
                        foreach ($formIdArr as $formIdArrKeys=>$formIdArrValues){
                            $formgroup = $this->LocalService()->itemForm->getOneFieldVal('group_id',[
                                'id' => $formIdArrValues,
                            ]);
                            $typetype = $this->LocalService()->itemForm->getOneFieldVal('type',[
                                'id' => $formIdArrValues,
                            ]);
                            if ($typetype == 1){
                                $batch_count_s += count($this->_getmanyformcount($item_id,$formIdArrValues,$itemChecktimeDataValue['id'],$patientDataValue['id'],$formgroup,$typetype));
                            }
                        }
                    }
                    $batch_count_s_s = $batch_count_s_s+$batch_count_s;

                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['complete_color_flag_e'] = 0;//0为半颜色，1为全颜色
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['complete_color_flag_s'] = 0;//0为半颜色，1为全颜色
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['complete_color_flag_r'] = 0;//0为半颜色，1为全颜色
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['incomplete_flag'] = 0;//填写一半,没有写全的表单
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['color_flag_e'] = 3;//0为绿色，1为黄色 2为红色
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['color_flag_s'] = 0;//0为绿色， 2为红色
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['color_flag_r'] = 0;//0为绿色， 2为红色
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['question_count'] = 0;//质疑总数
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['clear_question_count'] = 0;//已回复质疑数
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['colse_question_count'] = 0;//关闭质疑数
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['question_count_r'] = 0;//质疑总数
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['clear_question_count_r'] = 0;//已回复质疑数
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['colse_question_count_r'] = 0;//关闭质疑数

                    //新加==9-22
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['batch_count_s'] = $batch_count_s;//合并用药总数
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['batch_count_r'] = $batch_count_s;//合并用药总数
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['batch_lock_count'] = $batch_count_s;//合并用药总数

                    //s判断==
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['question_count_s'] = 0;//质疑总数==s
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['clear_question_count_s'] = 0;//已回复质疑数==s
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['colse_question_count_s'] = 0;//关闭质疑数==s


                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['is_plan'] = ($itemChecktimeDataValue['is_del'] == 2)?1:0;
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['is_experiment'] = ($itemChecktimeDataValue['is_del'] == 9)?1:0;
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['approve_count'] = 0;
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['clear_approve_count'] = 0;
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['clear_approve_count'] = 0;
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['clear_confirm_approve_count'] = 0;
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['confirm_approve_count'] = 0;
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['lock_count'] = 0;
                    $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['lock_flag'] = 0;

                    if (isset($itemPatientFormDatas[$patientDataValue['id'].'-'.$itemChecktimeDataValue['id']])){
                        $new_is_complete_flag = $itemPatientFormDatas[$patientDataValue['id'].'-'.$itemChecktimeDataValue['id']]['is_complete_flag'];
                        $new_is_complete = $itemPatientFormDatas[$patientDataValue['id'].'-'.$itemChecktimeDataValue['id']]['count'];
                        $new_form_ids = $itemPatientFormDatas[$patientDataValue['id'].'-'.$itemChecktimeDataValue['id']]['form_ids'];
                        if($new_is_complete_flag == 1){
                            $work_complete_count = $work_complete_count+$new_is_complete;
                            if($itemChecktimeCountData['count'] != $new_is_complete){
                                $incomplete = 1;
                                $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['incomplete_flag'] = 1;//填写一半,没有写全的表单
                                $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['color_flag_e'] = 0;//0为绿色，1为黄色 2为红色
                            }else{
                                $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['complete_color_flag_e'] = 1;//0为半颜色，1为全颜色

                            }

                        }
                        $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['is_complete'] = $new_is_complete;
                        $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['is_complete_flag'] =$new_is_complete_flag;
                    }
                    if ($itemChecktimeDataValue['is_del'] ==9 && $patientDataValue['patient_status'] !=9){
                        $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['count'] = 1;
                        $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['is_complete'] = 1;
                        $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['color_flag_e'] = 0;
                        $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['complete_color_flag_e'] = 1;
                        $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['is_complete_flag'] = 1;
                        $patientDataValue['itemChecktimeData'][$itemChecktimeDataKey]['is_pass'] = 0;
                        $work_complete_count = $work_complete_count+1;
                    }
                }
                array_push($patientDataValue['itemChecktimeData'],$newtemPatientaEContentDatas,$newtemPatientsAeContentDatas);

                if ($work_complete_count > $work_count){
                    $work_complete_count = $work_count;
                }
                $patientWorkCount[$patientDataKey]['work_count'] = $work_count;
                $patientWorkCount[$patientDataKey]['batch_count_s'] = $batch_count_s_s;
                $patientWorkCount[$patientDataKey]['batch_count_r'] = $batch_count_s_s;
                $patientWorkCount[$patientDataKey]['batch_lock_count'] = $batch_count_s_s;
                $patientWorkCount[$patientDataKey]['work_complete_count'] = $work_complete_count;
                $patientWorkCount[$patientDataKey]['is_plan'] = $is_plan;
            }
        }

        if (!empty($type)){
            $newPatientData = $this->LocalService()->patientChecktimeListEdc->patientChecktimeListData($item_id,$patientData);
            if (!empty($newPatientData)){
                foreach ($newPatientData as $patientDatum) {
                    foreach ($patientDatum['itemChecktimeData'] as $temChecktimeDataKey=>$itemChecktimeDatums) {

                        if  (!in_array($patientDatum['itemsig_id'],$patientAeAndSaeFlag['sae_flag'])){

                            if ($itemChecktimeDatums['check_name'] == $patientAeAndSaeFlag['sae']){

                                unset($patientDatum['itemChecktimeData'][$temChecktimeDataKey]);
                            }
                        }
                        if  (!in_array($patientDatum['itemsig_id'],$patientAeAndSaeFlag['ae_flag'])){
                            if ($itemChecktimeDatums['check_name'] == $patientAeAndSaeFlag['ae']){
                                unset($patientDatum['itemChecktimeData'][$temChecktimeDataKey]);
                            }
                        }
                    }

                    unset($patientDatum['patient_number']);
                    unset($patientDatum['patient_status']);
                    $patientDatum['item_checktime_list'] = json_encode($patientDatum['itemChecktimeData']);
                    unset($patientDatum['itemChecktimeData']);
                    $result = $this->LocalService()->patientChecktimeListEdc->save($patientDatum);
                }
            }

            $newPatientWorkCount = $this->LocalService()->patientChecktimeListEdc->patientWorkCountData($item_id,$patientWorkCount);
            if (!empty($newPatientWorkCount)){
                foreach ($newPatientWorkCount as $patientWorkDatum) {
                    unset($patientWorkDatum['patient_number']);
                    unset($patientDatum['patient_status']);

                    $result = $this->LocalService()->patientWorkCountEdc->save($patientWorkDatum);

                }
            }
            return true;

        }else{
            $datas['patientData'] = $patientData;
            $datas['patientAeAndSaeFlag']  = $patientAeAndSaeFlag;
            if(!empty($more) && in_array($more,[3,4])){
                $methods = '';
                if ($more == 3){
                    //更新添加检查点
                    $methods = 'updateChangeChecktimeJson';
                }else if($more == 4){
                    //更新数据
                    $methods = 'updateOldChangeChecktimeJson';
                }
                if (!empty($methods)){
                    $this->LocalService()->swTaskClient->send([
                        'svName' => 'patientChecktimeList',
                        'methodName' => $methods,
                        'params' => $datas
                    ]);
                }

               return true;
            }

            foreach ($patientData as $patientDatum) {
                $patientDatum['patient_id'] = $patientDatum['id'];

                unset($patientDatum['id']);
                unset($patientDatum['patient_number']);
                unset($patientDatum['patient_status']);
                $patientDatum['item_checktime_list'] = json_encode($patientDatum['itemChecktimeData']);
                unset($patientDatum['itemChecktimeData']);
                $result = $this->LocalService()->patientChecktimeListEdc->save($patientDatum);
            }
            foreach ($patientWorkCount as $patientWorkDatum) {
                unset($patientWorkDatum['patient_number']);
                unset($patientDatum['patient_status']);
                $result = $this->LocalService()->patientWorkCountEdc->save($patientWorkDatum);
            }
            if(empty($more) && !empty($patient_id)){
                $this->LocalService()->swTaskClient->send([
                    'svName' => 'patientChecktimeList',
                    'methodName' => 'updateChangeChecktimeJson',
                    'params' => $datas
                ]);
                return true;
            }
        }
        return true;
    }

    //处理工作总数
    public function itemChecktimeCount($whereData = []){
        $whereData['count_Relation'] = 0;
        if (!empty($whereData['form_ids'])){
            $FormRelationwhere['where'] = [
                'is_del' => 0,
                'relation_form_id' => explode(',', $whereData['form_ids'])
            ];
            $FormRelationwhere['columns'] = ['form_id','relation_form_id'];
            $FormRelationData=$this->LocalService()->itemFormRelation->fetchAll($FormRelationwhere);
            $formIdArr = explode(',',$whereData['form_ids']);
            $unsetArr = [];
            if (!empty($FormRelationData)){
                foreach ($FormRelationData as $FormRelationDataKey=>$FormRelationDataValue) {
                    $Pformwhere= [
                        'is_del' => 0,
                        'item_id' => $whereData['item_id'],
                        'patient_id' => $whereData['patient_id'],
                        'form_id' => $FormRelationDataValue['relation_form_id'],
                        'checktime_id' => $whereData['checktime_id'],
                    ];
                    $PatientformInfo=$this->LocalService()->itemPatientChecktimeForm->getCount($Pformwhere);
                    if (empty($PatientformInfo)){
                        $unsetArr[] = $FormRelationDataValue['relation_form_id'];
                    }

                }
            }

            $whereData['count'] = $whereData['count'] - count($unsetArr);
            $whereData['count_Relation'] = count($unsetArr);
            $newFormIdArr = array_diff($formIdArr,$unsetArr);
            !empty($newFormIdArr) && $whereData['form_ids']  = implode(',',$newFormIdArr);
        }
        return $whereData;
    }

    //处理完成质疑
    public function questionClearUpdate($whereData = []){
        //$this->LocalService()->patientChecktimeListEdc->questionClearUpdate($whereData);
        return true;
    }

    public function _getmanyformcount($item_id,$form_id,$checktime_id,$patient_id,$formgroup,$formtype)
    {
        $patientformwhereArr = [
            'is_del' => 0,
            'item_id' => $item_id,
            'patient_id' => $patient_id,
            'form_id' => $form_id,
        ];
        if($formgroup != 4 && !empty($checktime_id))$patientformwhereArr['checktime_id'] = $checktime_id;
        if($formtype == 5){
            $patientformcontent = $this->LocalService()->itemCsaeRelation->fetchCol('id', [
                'is_del' => 0,
                'patient_id' => $patient_id,
            ]);
        }else{
            $patientformcontent = $this->LocalService()->patientFormContent->fetchCol('id', $patientformwhereArr);
        }
        return $patientformcontent;
    }


    /**
     * 更新表单是否完成
     * @$item_id 小项目id
     * @$itemsig_id 中心id
     * @$patient_id 受试者id
     * @$form_id 表单id
     * @$checktime_id 检查点id
     * @$type 是否完成 0未完成 1为已完成（绿色） 2为表单填写不全，但已填写（半绿色） 3为表单填写全了，改为填写不全（半绿色）  4为表单填写全了，改为未填写（白色）  5为表单填写不全，改为未填写（白色）
     *
     */
    public function isCompleteForm($where = []){
        $item_id = $where['item_id'];
        $form_id = $where['form_id'];
        $patient_id = $where['patient_id'];
        $checktime_id = $where['checktime_id'];
        $itemsig_id = $where['itemsig_id'];
        $type = $where['type'];
        if (empty($item_id) || empty($itemsig_id) || empty($patient_id) || empty($form_id) || empty($checktime_id)){
            return false;
            echo '参数不正确';die;
        }
        //是否为edc项目
        if (!$this->isEdcItem($item_id,0)){//如果是大项目id的话，type为 1
            return false;
        }

        $patientChecktimeListWhere = [
            'is_del' => 0,
            'patient_id' => $patient_id,
            'item_id' => $item_id,
            'itemsig_id' => $itemsig_id,
        ];
        $patientChecktimeListInfoData = $this->LocalService()->patientChecktimeListEdc->fetchOne(['where'=>$patientChecktimeListWhere]);
        $itemChecktimeList = json_decode($patientChecktimeListInfoData['item_checktime_list'],true);

        $countZ = 0;
        $work_complete_count = 0;
        $is_plan = 0;
        $incomplete_flag = 0;
        if (empty($itemChecktimeList)){
            return false;
            echo '没有找到';die;
        }else{
            $old_incomplete_flag = 0;
            foreach ($itemChecktimeList as $itemChecktimeListKey=>&$itemChecktimeListValue){

                if (isset($itemChecktimeListValue['incomplete_flag']) && !empty($itemChecktimeListValue['incomplete_flag'])){
                    $old_incomplete_flag = 1;
                }
                if (!isset($itemChecktimeListValue['incomplete_form_arr'])){
                    $itemChecktimeListValue['incomplete_form_arr'] = [];
                }
                $form_id_arr = [];
                if (isset($itemChecktimeListValue['form_ids']) && !empty($itemChecktimeListValue['form_ids'])) $form_id_arr = explode(',',$itemChecktimeListValue['form_ids']);
                $issetFormFlag = 0;
                if (in_array($form_id,$form_id_arr)){
                    $issetFormFlag = 1;
                }

                if (!isset($itemChecktimeListValue['incomplete_flag'])){
                    $itemChecktimeListValue['incomplete_flag'] = 0;
                }
                if ($itemChecktimeListKey == $checktime_id){
                    if (!empty($issetFormFlag)){
                        if ($type == 0){
                            //表单未完成
                            $itemChecktimeListValue['is_complete_flag'] = 0;
                        }else if($type == 1){
                            //表单已完成
                            //添加完成数加 ===
                            $itemChecktimeListValue['is_complete'] = isset($itemChecktimeListValue['is_complete'])?($itemChecktimeListValue['is_complete']+1):1;
                            $itemChecktimeListValue['is_complete_flag'] = 0;
                            if (isset($itemChecktimeListValue['is_complete']) && ($itemChecktimeListValue['is_complete'] >= $itemChecktimeListValue['count'])){
                                $itemChecktimeListValue['is_complete_flag'] = 1;
                                $itemChecktimeListValue['incomplete_flag'] = 0;
                            }else{
                                if (!empty($itemChecktimeListValue['incomplete_flag']) && in_array($form_id,$itemChecktimeListValue['incomplete_form_arr'])){
                                    $itemChecktimeListValue['incomplete_flag'] -= 1;
                                    $itemChecktimeListValue['incomplete_form_arr'] = array_diff($itemChecktimeListValue['incomplete_form_arr'],[$form_id]);
                                }
                            }

                        }else if(in_array($type ,[2,3])){
                            if (!in_array($form_id,$itemChecktimeListValue['incomplete_form_arr'])){
                                array_push($itemChecktimeListValue['incomplete_form_arr'],$form_id);
                                $itemChecktimeListValue['incomplete_flag'] += 1;
                            }
                            //表单已填写，但未填写全
                            $itemChecktimeListValue['is_complete_flag'] = 2;
                            if (isset($itemChecktimeListValue['is_complete'])){
                                //表单已填写，改为写全不全
                                if ($type == 3){
                                    if (!empty($itemChecktimeListValue['is_complete'])){
                                        $itemChecktimeListValue['is_complete'] = $itemChecktimeListValue['is_complete'] - 1;
                                    }
                                }
                                if (($itemChecktimeListValue['is_complete'] >= $itemChecktimeListValue['count'])){
                                    $itemChecktimeListValue['is_complete_flag'] = 1;
                                }
                            }
                        }else if(in_array($type ,[4,5])){

                            //表单已填写，改为未填写（白色）
                            $itemChecktimeListValue['is_complete_flag'] = 2;
                            if (!empty($itemChecktimeListValue['incomplete_flag']) && in_array($form_id,$itemChecktimeListValue['incomplete_form_arr'])){
                                $itemChecktimeListValue['incomplete_flag'] -= 1;
                                $itemChecktimeListValue['incomplete_form_arr'] = array_diff($itemChecktimeListValue['incomplete_form_arr'],[$form_id]);
                            }
                            if (isset($itemChecktimeListValue['is_complete'])){
                                //表单填写不全，改为未填写（白色）
                                if ($type != 5){
                                    if (!empty($itemChecktimeListValue['is_complete'])){
                                        $itemChecktimeListValue['is_complete'] = $itemChecktimeListValue['is_complete'] - 1;
                                    }
                                }
                                if (($itemChecktimeListValue['is_complete'] >= $itemChecktimeListValue['count'])){
                                    $itemChecktimeListValue['is_complete_flag'] = 1;
                                }
                            }
                        }
                    }
                    if (empty($itemChecktimeListValue['is_complete']) && count($itemChecktimeListValue['incomplete_form_arr'])){
                        unset($itemChecktimeListValue['is_complete']);
                    }
                }

                //判断是否是计划外  1为有
                if (isset($itemChecktimeListValue['is_plan']) && !empty($itemChecktimeListValue['is_plan'])) $is_plan = 1;
                $countZ = $countZ+$itemChecktimeListValue['count'];
                $work_complete_count = $work_complete_count+($itemChecktimeListValue['is_complete'] ?? 0);

            }
            if (!empty($countZ) && !empty($work_complete_count) && ($countZ == $work_complete_count)){
                $incomplete_flag = 0;
            }else{
                if (!empty($countZ) && in_array($type,[2,3])){
                    $incomplete_flag = 1;
                }
            }

        }
        $updateCount['work_count'] = $countZ;
        $updateCount['work_complete_count'] = $work_complete_count;

        if (!empty($is_plan)){
            $updateCount['is_plan'] = $is_plan;
        }
        $resultCount = $this->LocalService()->patientWorkCountEdc->update($updateCount, [
            'is_del' => 0,
            'patient_id' => $patient_id,
        ]);
        $updateList['item_checktime_list'] = json_encode($itemChecktimeList);
        $resultList = $this->LocalService()->patientChecktimeListEdc->update($updateList,$patientChecktimeListWhere);
        return true;

    }


    /**
     * 更新表单（添加和删除表单）
     * @$item_id 小项目id
     * @$form_id 表单id
     * @$checktime_id 检查点id
     * @$is_plan 是否为计划外 0不是 1为是
     * @$type 是否为删除表单 0添加 1为删除
     *
     */

    public function updateForm($where = []){
        $item_id = $where['item_id'];
        $form_id = $where['form_id'];
        $checktime_id = $where['checktime_id'];
        $type = $where['type'];
        if (empty($item_id) || empty($form_id) || empty($checktime_id)){
            echo '参数不正确';die;
        }

        //是否为edc项目
        if (!$this->isEdcItem($item_id,0)){//如果是大项目id的话，type为 1
            return false;
        }

        $whereEdcList = [
            'where'=> [
                'is_del' => 0,
                'item_id' => $item_id,
            ],
            'columns'=>['id','item_id','patient_id','create_user_id','item_checktime_list'],
        ];
        $patientChecktimeListEdcData = $this->LocalService()->patientChecktimeListEdc->fetchAll($whereEdcList);
        $fieldDatas = $this->fieldData($where);
        $i = 0;
        if (!empty($patientChecktimeListEdcData)){
            foreach ($patientChecktimeListEdcData as $patientChecktimeListEdcDataKey=>$patientChecktimeListEdcDatum) {
                $countZ = 0;
                $work_complete_count = 0;
                $flag = 0;
                $newIsPlanArr = [];
                if  (!empty($patientChecktimeListEdcDatum['item_checktime_list'])){
                    $itemChecktimeList = json_decode($patientChecktimeListEdcDatum['item_checktime_list'],true);
                    $issetFlag = 0;
                    $aeAndSae = [];
                    foreach ($itemChecktimeList as $itemChecktimeListKey=>&$itemChecktimeListValue){
                        if (in_array($itemChecktimeListValue['id'],[$this->AeAndSaeFlag['ae_id'],$this->AeAndSaeFlag['sae_id']])){
                            if ($itemChecktimeListValue['check_name'] == $this->AeAndSaeFlag['ae']){
                                $itemChecktimeListValue['check_order'] = $this->AeAndSaeFlag['ae_order'];
                                $itemChecktimeListValue['id'] = $this->AeAndSaeFlag['ae_id'];
                            }
                            if ($itemChecktimeListValue['check_name'] == $this->AeAndSaeFlag['sae']){
                                $itemChecktimeListValue['check_order'] = $this->AeAndSaeFlag['sae_order'];
                                $itemChecktimeListValue['id'] = $this->AeAndSaeFlag['sae_id'];
                            }
                        }
                        $form_id_arr = [];
                        if (isset($itemChecktimeListValue['form_ids']) && !empty($itemChecktimeListValue['form_ids'])) $form_id_arr = explode(',',$itemChecktimeListValue['form_ids']);
//                        echo '<pre>';print_r($itemChecktimeListValue);die;

                        if ($itemChecktimeListValue['id'] == $checktime_id){
                            $postFormId = explode(',',$form_id);

                            if ($type == 0){
                                $flag = 1;
                                $itemChecktimeListValue['count'] = $itemChecktimeListValue['count']+count($postFormId);
                                if (!isset($itemChecktimeListValue['form_ids']) || empty($itemChecktimeListValue['form_ids'])){
                                    $itemChecktimeListValue['form_ids'] = $form_id;
                                }else{
                                    $itemChecktimeListValue['form_ids'] = $itemChecktimeListValue['form_ids'].','.$form_id;
                                }

                            }else if($type == 1){
                                //删除表单
                                $flag = 1;
                                $newsCount = $itemChecktimeListValue['count']-count($postFormId);
                                if ($newsCount <= 0){
                                    $itemChecktimeListValue['count'] = 0;
                                }else{
                                    $itemChecktimeListValue['count'] = $newsCount;
                                }
                                $newFormArr = array_diff($form_id_arr,$postFormId);
                                if (!empty($newFormArr)){
                                    $itemChecktimeListValue['form_ids'] = implode(',',$newFormArr);
                                }else{
                                    $itemChecktimeListValue['form_ids'] = '';
                                }
                                if (empty($itemChecktimeListValue['form_ids'])){
                                    $itemChecktimeListValue['is_pass'] = 1;
                                }

                            }

                        }else{
                            if (!in_array($itemChecktimeListValue['check_name'],[$this->AeAndSaeFlag['ae'],$this->AeAndSaeFlag['sae']])){
                                $issetFlag = 1;
                            }
                        }

                        if (isset($itemChecktimeListValue['is_complete'])){
                            if ($itemChecktimeListValue['is_complete'] >= $itemChecktimeListValue['count']){
                                $itemChecktimeListValue['is_complete']  = $itemChecktimeListValue['count'];
                            }
                        }else{
                            $itemChecktimeListValue['is_complete']  = 0;
                        }
                        $countZ = $countZ+$itemChecktimeListValue['count'];
                        $work_complete_count = $work_complete_count+$itemChecktimeListValue['is_complete'];

                    }
                    if (!empty($issetFlag) && ($type == 0)){
                        $flag = 1;
                        array_push($itemChecktimeList,$fieldDatas);
                        if (isset($fieldDatas['count']) && !empty($fieldDatas['count'])){
                            $countZ = $countZ+$fieldDatas['count'];
                        }
                        if (isset($fieldDatas['is_complete']) && !empty($fieldDatas['is_complete'])){
                            $work_complete_count = $work_complete_count+$fieldDatas['is_complete'];
                        }
                        $check_order = array_column($itemChecktimeList,'check_order');
                        array_multisort($check_order,SORT_ASC ,$itemChecktimeList);
                        $itemChecktimeList = array_column($itemChecktimeList,null,'id');
                    }
//                    echo '<pre>';print_r($itemChecktimeList);die;
                    if (!empty($itemChecktimeList) && !empty($flag)){
                        $updateList['item_checktime_list'] = json_encode($itemChecktimeList);
                        $resultList = $this->LocalService()->patientChecktimeListEdc->update($updateList,[
                            'is_del' => 0,
                            'patient_id' => $patientChecktimeListEdcDatum['patient_id'],
                        ]);
                    }
                    if (!empty($flag)){
                        $updateCount['work_count'] = $countZ;
                        $updateCount['work_complete_count'] = $work_complete_count;
                        $resultCount = $this->LocalService()->patientWorkCountEdc->update($updateCount, [
                            'is_del' => 0,
                            'patient_id' => $patientChecktimeListEdcDatum['patient_id']
                        ]);
                    }
                }

            }

        }
        return true;

    }

    public function fieldData($where = []){
        $checktimeRandom = [
            'random_id'=>0,
            'check_name'=>'',
            'check_order'=>0,
            'id'=>0,
            'is_del'=>0,
            'stage_id'=>0,
        ];
        if (!empty($where['checktime_id'])){
            $checktimeInfo = $this->LocalService()->itemChecktime->fetchOne(['where'=> [
                new Operator('is_del', Operator::OP_NE, 1),
                'id' => $where['checktime_id']
            ]]);
            if (!empty($checktimeInfo)){
                $checktimeRandom['check_name'] = $checktimeInfo['check_name'];
                $checktimeRandom['check_order'] = $checktimeInfo['check_order'];
                $checktimeRandom['id'] = $checktimeInfo['id'];
                $checktimeRandom['is_del'] = $checktimeInfo['is_del'];
                $checktimeRandom['stage_id'] = $checktimeInfo['stage_id'];
                if (!empty($checktimeInfo['random_id'])){
                    $checktimeRandom['random_id'] = $checktimeInfo['random_id'];
                }
            }
        }
        $fieldDatas = [
            'count'=>isset($where['form_id']) ?count(explode(',',$where['form_id'])):0,
            'is_pass'=>0,
            'id'=>$checktimeRandom['id'],
            'form_ids'=>isset($where['form_id'])?$where['form_id']:'',
            'question_count_r'=>0,
            'clear_question_count_r'=>0,
            'colse_question_count_r'=>0,

            //s判断==
            'question_count_s'=>0,
            'clear_question_count_s'=>0,
            'colse_question_count_s'=>0,

            'question_count'=>0,
            'clear_question_count'=>0,
            'colse_question_count'=>0,
            'confirm_approve_count'=>0,
            'is_complete'=>0,
            'is_complete_flag'=>2,
            'lock_count'=>0,
            'lock_flag'=>0,
            'is_del'=>$checktimeRandom['is_del'],
            'stage_id'=>$checktimeRandom['stage_id'],
            'random_id' =>$checktimeRandom['random_id'],
            'check_name' =>$checktimeRandom['check_name'],
            'check_order' =>$checktimeRandom['check_order'],
        ];
        return $fieldDatas;
    }

    /**
     * 更新表单（添加和删除表单）
     * @$item_id 小项目id
     * @$form_id 表单id
     * @$checktime_id 检查点id
     * @$is_plan 是否为计划外 0不是 1为是
     * @$type 是否为删除表单 0添加 1为删除
     *
     */

    public function updateFormBack($where = []){
        $item_id = $where['item_id'];
        $form_id = $where['form_id'];
        $checktime_id = $where['checktime_id'];
        $is_plan = $where['is_plan'];
        $type = $where['type'];
        if (empty($item_id) || empty($form_id) || empty($checktime_id)){
            echo '参数不正确';die;
        }

        //是否为edc项目
        if (!$this->isEdcItem($item_id,0)){//如果是大项目id的话，type为 1
            return false;
        }

        $whereEdcList = [
            'where'=> [
                'is_del' => 0,
                'item_id' => $item_id,
            ],
            'columns'=>['id','item_id','patient_id','create_user_id','item_checktime_list'],
        ];
        $patientChecktimeListEdcData = $this->LocalService()->patientChecktimeList->fetchAll($whereEdcList);
        if (!empty($patientChecktimeListEdcData)){
            foreach ($patientChecktimeListEdcData as $patientChecktimeListEdcDataKey=>$patientChecktimeListEdcDatum) {
                $countZ = 0;
                $work_complete_count = 0;
                $flag = 0;
                $newIsPlanArr = [];
                if  (!empty($patientChecktimeListEdcDatum['item_checktime_list'])){
                    $itemChecktimeList = json_decode($patientChecktimeListEdcDatum['item_checktime_list'],true);

                    foreach ($itemChecktimeList as $itemChecktimeListKey=>&$itemChecktimeListValue){
                        $form_id_arr = [];
                        if (isset($itemChecktimeListValue['form_ids']) && !empty($itemChecktimeListValue['form_ids'])) $form_id_arr = explode(',',$itemChecktimeListValue['form_ids']);

                        if ($itemChecktimeListKey == $checktime_id){
                            $issetFormFlag = 0;
                            if (in_array($form_id,$form_id_arr)){
                                $issetFormFlag = 1;
                            }
                            if ($type == 0){
                                //添加表单
                                if (empty($issetFormFlag)){
                                    $flag = 1;
                                    $itemChecktimeListValue['count'] = $itemChecktimeListValue['count']+1;
                                    if (empty($itemChecktimeListValue['form_ids'])){
                                        $itemChecktimeListValue['form_ids'] = $form_id;
                                    }else{
                                        $itemChecktimeListValue['form_ids'] = $itemChecktimeListValue['form_ids'].','.$form_id;
                                    }
                                    //添加一个计划外的
                                    if (!empty($is_plan)){
                                        $itemChecktimeListValue['is_plan'] = $is_plan;
                                    }
                                }
                            }else if($type == 1){
                                //删除表单
                                if (!empty($issetFormFlag)){
                                    $flag = 1;
                                    $newsCount = $itemChecktimeListValue['count']-1;
                                    if ($newsCount <= 0){
                                        $itemChecktimeListValue['count'] = 0;
                                    }else{
                                        $itemChecktimeListValue['count'] = $newsCount;
                                    }
                                    $newFormArr = array_diff($form_id_arr,[$form_id]);
                                    if (!empty($newFormArr)){
                                        $itemChecktimeListValue['form_ids'] = implode(',',$newFormArr);
                                    }else{
                                        $itemChecktimeListValue['form_ids'] = '';
                                    }
                                    //删除一个计划外的
                                    if (!empty($is_plan)){
                                        $itemChecktimeListValue['is_plan'] = 0;
                                    }

                                }

                            }

                        }
                        if (isset($itemChecktimeListValue['is_plan'])){
                            $newIsPlanArr[] =  $itemChecktimeListValue['is_plan'];
                        }else{
                            $newIsPlanArr[] = 0;

                        }
                        if (isset($itemChecktimeListValue['is_complete'])){
                            if ($itemChecktimeListValue['is_complete'] >=$itemChecktimeListValue['count']){
                                $itemChecktimeListValue['is_complete']  = $itemChecktimeListValue['count'];
                            }
                        }else{
                            $itemChecktimeListValue['is_complete']  = 0;
                        }
                        $countZ = $countZ+$itemChecktimeListValue['count'];
                        $work_complete_count = $work_complete_count+$itemChecktimeListValue['is_complete'];

                    }
                    if (!empty($itemChecktimeList) && !empty($flag)){
                        $updateList['item_checktime_list'] = json_encode($itemChecktimeList);
                        $resultList = $this->LocalService()->patientChecktimeList->update($updateList,[
                            'is_del' => 0,
                            'patient_id' => $patientChecktimeListEdcDatum['patient_id'],
                        ]);
                    }
                    if (!empty($flag)){
                        $updateCount['is_plan'] = 0;
                        $updateCount['work_count'] = $countZ;
                        $updateCount['work_complete_count'] = $work_complete_count;

                        $resultCount = $this->LocalService()->patientWorkCount->update($updateCount, [
                            'is_del' => 0,
                            'patient_id' => $patientChecktimeListEdcDatum['patient_id']
                        ]);
                    }
                }
            }

        }
        return true;
    }

    /**
     * 是否为edc项目
     * @$item_id 项目id
     * @$type 是否为删除表单 0为小项目 1为大项目
     */
    public function isEdcItem($item_id,$type=0){
        if (empty($type)){
            $itemInfoData = $this->LocalService()->itemInfo->fetchOne(['where'=> [
                'is_del' => 0,
                'id' => $item_id,
            ]]);
            if (empty($itemInfoData)){
                return false;
            }
            $item_id = $itemInfoData['fid']?:0;
        }
        $itemInfoIsEdc = $this->LocalService()->itemInfo->getOneFieldVal('is_edc',[
            'is_del' => 0,
            'id' => $item_id,
        ]);
        if (empty($itemInfoIsEdc)){
            return false;
        }
        return true;

    }


    /**
     * 大项目edc设置变动（删除或添加进度条数据）
     * @$item_id 项目id
     * @$is_edc 是否为edc 0为不是 1为是
     * @$type 是哪个模块操作 0为大项目设置模块操作  1为受试者模块操作
     *
     *
     *
     *
     * 受试者删除或添加
     * @$where['patient_id'] 受试者id（字符串）
     * @$where['item_id'] 项目id（字符串）
     */
    public function delectePatientFormItem($where = []){

        if (isset($where['type']) && empty($where['type'])){
            $itemData = $this->LocalService()->itemInfo->fetchAll(['where'=> [
                'is_del' => 0,
                'fid' => $where['item_id'],
            ]]);
            if (empty($itemData)){
                return false;
            }
            $itemInfoIds = implode(',',array_column($itemData,'id'));
        }


        if (empty($where['type'])){
            //大项目edc设置变动（先判断是否为edc，再判断是否为改动edc的设置）
            if (empty($where['is_edc'])){
                $resultRelation = $this->LocalService()->realRolemodulerelationEdc->update(['status'=>1], [
                    'status' => 0,
                    'item_id' => $where['item_id']
                ]);
                //大项目edc设置变动（删除或添加进度条数据）
                $where = [
                    'is_del' => 0,
                    'item_id' => array_column($itemData,'id'),
                ];
                //删除受试者表单数据
                $del = [
                    'is_del'=>1,
                ];

                $resultCount = $this->LocalService()->patientWorkCountEdc->update($del,$where);
                $resultList = $this->LocalService()->patientChecktimeListEdc->update($del,$where);
                $whereDelQuestion = [
                    'is_del'=>0,
                    'item_id'=>$itemInfoIds?explode(',',$itemInfoIds):0,
                ];
                $this->delQuestion($whereDelQuestion);

            }else{
                //大项目edc设置变动（删除或添加进度条数据）
                $resultRelation = $this->LocalService()->realRole->itemRealRelation($where['item_id']);
                //添加受试者表单数据
                foreach ($itemData as $itemDataKey=>$itemDataValue){
                    $this->patientChecktimeInsert($itemDataValue['id']);
                }

            }

        }else if($where['type'] == 1){

            //受试者模块操作（先判断是否为edc）
            if (empty($where['is_edc'])){
                //受试者删除
                $where = [
                    'is_del' => 0,
                    'patient_id' => explode(',', $where['patient_id'])
                ];
                //删除受试者表单数据
                $del = [
                    'is_del'=>1,
                ];

                $resultCount = $this->LocalService()->patientWorkCountEdc->update($del,$where);
                $resultList = $this->LocalService()->patientChecktimeListEdc->update($del,$where);
            }else{
                //添加受试者表单数据
                $patientIdArr = explode(',',$where['patient_id']);
                foreach ($patientIdArr as $patientIdArrKey=>$patientIdArrValue){
                    $this->patientChecktimeInsert($where['item_id'],$patientIdArrValue);
                }
            }

        }else if($where['type'] == 2){
            //受试者导入模块操作（先判断是否为edc）
            $this->patientChecktimeInsert($where['item_id'],$where['patient_id'],1);
        }

        return true;

    }

    //删除项目下所有质疑
    public function delQuestion($where = ''){
        if (empty($where)) return false;
        $del = [
            'is_del'=>1,
        ];

        $this->LocalService()->itemConfirm->update(['is_del'=>2],['item_id'=>$where['item_id']]);
        $this->LocalService()->itemLock->update($del,$where);
        $this->LocalService()->itemPatientFormLogicErrorLog->update($del,$where);
        $this->LocalService()->itemPatientFormLogicErrorPointer->update(['is_del'=>2],$where);
        $this->LocalService()->patientFormContentUpdated->update($del,$where);
        unset($where['is_del']);
        $this->LocalService()->itemPatientFormLogicError->update(['is_del'=>2,'patient_id'=>0],$where);
        $this->LocalService()->itemPatientFormLogicErrorQuery->update(['is_del'=>1,'error_id'=>0],$where);

    }



    public function updateChangeChecktimeJson($newsPatientParameter = []){
        $newsPatientDatas =$newsPatientParameter['patientData'];
        $patientAeAndSaeFlag =$newsPatientParameter['patientAeAndSaeFlag'];
        if(empty($newsPatientDatas)) return false;
        $patientDataPop = array_pop($newsPatientDatas);
        if (!empty($patientDataPop)){
            $patientEdcWhere = [
                'where'=>[
                    'is_del'=>0,
                    'item_id'=>isset($patientDataPop['item_id'])?$patientDataPop['item_id']:0,
                    'itemsig_id'=>isset($patientDataPop['itemsig_id'])?$patientDataPop['itemsig_id']:0,
                ],
            ];
            $workData = $this->LocalService()->patientWorkCountEdc->fetchAll($patientEdcWhere);
            $patientChecktimeData = $this->LocalService()->patientChecktimeListEdc->fetchAll($patientEdcWhere);
            if (!empty($patientChecktimeData) && !empty($patientDataPop['itemChecktimeData'])){
                $newPatientWorkCount = [];
                foreach ($patientChecktimeData as $checktimeK=>&$patientChecktimeV) {
                    if ($patientChecktimeV['patient_id'] == $patientDataPop['id']) continue;
                    $item_checktime_list = [];
                    !empty($patientChecktimeV['item_checktime_list']) && $item_checktime_list = json_decode($patientChecktimeV['item_checktime_list'],true);

                    if (!empty($item_checktime_list)){
                        if (count($item_checktime_list) == count($patientDataPop['itemChecktimeData'])) continue;
                        foreach ($patientDataPop['itemChecktimeData'] as $newChecktimeK=>$newPatientChecktimeV) {
                            $checkNameArr = array_column($item_checktime_list,'check_name');
                            $checkIdArr = array_column($item_checktime_list,'id');
                            $new_check_name = trim($newPatientChecktimeV['check_name']);

                            if (in_array($new_check_name,[$patientAeAndSaeFlag['ae'],$patientAeAndSaeFlag['sae']])){
                                if ($newPatientChecktimeV['check_name'] == $patientAeAndSaeFlag['ae'] && !in_array($patientAeAndSaeFlag['ae'],$checkNameArr)){
                                    array_push($item_checktime_list,$newPatientChecktimeV);
                                }
                                if ($new_check_name == $patientAeAndSaeFlag['sae'] && !in_array($patientAeAndSaeFlag['sae'],$checkNameArr)){
                                    array_push($item_checktime_list,$newPatientChecktimeV);
                                }

                            }else{
                                if (!in_array($newPatientChecktimeV['id'],$checkIdArr)){
                                    array_push($item_checktime_list,$newPatientChecktimeV);
                                }
                            }

                        }
                    }
                    $ae = [];
                    $sae = [];
                    $work_count = 0;
                    $work_complete_count = 0;
                    if(!empty($item_checktime_list)){
                        foreach($item_checktime_list as $checkId=>&$checkData){
                            $newPatientWorkCount[$patientChecktimeV['patient_id']]['work_count_every'][$checkData['check_name']] = $checkData['count'];

                            $work_count = $work_count+$checkData['count'];
                            if  (isset($checkData['is_complete']) && ($checkData['is_complete'] > 0)){
                                $newPatientWorkCount[$patientChecktimeV['patient_id']]['is_complete_every'][$checkData['check_name']] = $checkData['is_complete'];
                                if ($checkData['is_complete'] > $checkData['count']){
                                    $checkData['is_complete'] = $checkData['count'];
                                }
                                $work_complete_count = $work_complete_count + $checkData['is_complete'];

                            }
                            if  (!in_array($checkData['check_name'],[$patientAeAndSaeFlag['ae'],$patientAeAndSaeFlag['sae']])){
                               continue;
                            }
                            if ($checkData['check_name'] == $patientAeAndSaeFlag['ae']){
                                $checkData['check_order'] = $this->AeAndSaeFlag['ae_order'];
                                $checkData['id'] = $this->AeAndSaeFlag['ae_id'];
                                $ae = $checkData;
                            }
                            if ($checkData['check_name'] == $patientAeAndSaeFlag['sae']){
                                $checkData['check_order'] = $this->AeAndSaeFlag['sae_order'];
                                $checkData['id'] = $this->AeAndSaeFlag['sae_id'];
                                $sae = $checkData;
                            }
                            unset($item_checktime_list[$checkId]);
                        }
                        $check_order = array_column($item_checktime_list,'check_order');
                        array_multisort($check_order,SORT_ASC ,$item_checktime_list);
                        $item_checktime_list = array_column($item_checktime_list,null,'id');
                        if (!empty($ae)){
                            array_push($item_checktime_list,$ae);

                        }
                        if (!empty($sae)){
                            array_push($item_checktime_list,$sae);

                        }
                        $newPatientWorkCount[$patientChecktimeV['patient_id']]['work_count'] = $work_count;
                        $newPatientWorkCount[$patientChecktimeV['patient_id']]['work_complete_count'] = $work_complete_count;

                        $patientChecktimeV['item_checktime_list'] = json_encode($item_checktime_list);
                        $ChecktimeListEdc = [
                            'item_checktime_list'=>$patientChecktimeV['item_checktime_list'],
                            'update_time'=>$patientChecktimeV['update_time'],
                            'update_user_id'=>$patientChecktimeV['update_user_id'],
                        ];

                        $resultChecktime = $this->LocalService()->patientChecktimeListEdc->update($ChecktimeListEdc, [
                            'is_del' => 0,
                            'id' => $patientChecktimeV['id']
                        ]);
                    }
                }
            }
        }
        return true;
    }

    public function updateOldChangeChecktimeJson($newsPatientParameter = []){
        $newsPatientDatas =$newsPatientParameter['patientData'];
        if(empty($newsPatientDatas)) return false;
            $patientEdcWhere = [
                'where'=>[
                    'is_del'=>0,
                    'item_id'=>isset($newsPatientDatas[0]['item_id'])?$newsPatientDatas[0]['item_id']:0,
                    'itemsig_id'=>isset($newsPatientDatas[0]['itemsig_id'])?$newsPatientDatas[0]['itemsig_id']:0,
                ],
            ];
            $patientIdArr = array_column($newsPatientDatas,'id');
            !empty($patientIdArr) && $patientEdcWhere['where']['patient_id'] = $patientIdArr;
            $newPatientIdDatas = array_column($newsPatientDatas,null,'id');

            $workData = $this->LocalService()->patientWorkCountEdc->fetchAll($patientEdcWhere);
            $patientChecktimeData = $this->LocalService()->patientChecktimeListEdc->fetchAll($patientEdcWhere);

        $newPatientWorkCount = [];
        if (!empty($patientChecktimeData)){
                foreach ($patientChecktimeData as $checktimeK=>&$patientChecktimeV) {
                    if (isset($newPatientIdDatas[$patientChecktimeV['patient_id']])){
                        $patientDataPop = $newPatientIdDatas[$patientChecktimeV['patient_id']];

                        $work_count = 0;
                        $work_complete_count = 0;
                        $item_checktime_list = $patientDataPop['itemChecktimeData'];
                        if(!empty($item_checktime_list)){
                            foreach($item_checktime_list as $checkId=>&$checkData){
                                $newPatientWorkCount[$patientChecktimeV['patient_id']]['work_count_every'][$checkData['check_name']] = $checkData['count'];
                                $work_count = $work_count+$checkData['count'];
                                if  (isset($checkData['is_complete']) && ($checkData['is_complete'] > 0)){
                                    $newPatientWorkCount[$patientChecktimeV['patient_id']]['is_complete_every'][$checkData['check_name']] = $checkData['is_complete'];
                                    if ($checkData['is_complete'] > $checkData['count']){
                                        $checkData['is_complete'] = $checkData['count'];
                                    }
                                    $work_complete_count = $work_complete_count + $checkData['is_complete'];

                                }

                            }
                            $newPatientWorkCount[$patientChecktimeV['patient_id']]['work_count'] = $work_count;
                            $newPatientWorkCount[$patientChecktimeV['patient_id']]['work_complete_count'] = $work_complete_count;
                        }
                        $patientChecktimeV['item_checktime_list'] = json_encode($patientDataPop['itemChecktimeData']);
                        $ChecktimeListEdc = [
                            'item_checktime_list'=>$patientChecktimeV['item_checktime_list'],
                            'update_time'=>$patientChecktimeV['update_time'],
                            'update_user_id'=>$patientChecktimeV['update_user_id'],
                        ];

                        $resultChecktime = $this->LocalService()->patientChecktimeListEdc->update($ChecktimeListEdc, [
                            'is_del' => 0,
                            'id' => $patientChecktimeV['id']
                        ]);
                    }
                }

                if (!empty($newPatientWorkCount)){
                    foreach ($workData as $patientWorks){
                        if (isset($newPatientWorkCount[$patientWorks['patient_id']])){
                            $newDatas = $newPatientWorkCount[$patientWorks['patient_id']];
                            $workCountUP = [];
                            if($patientWorks['count'] != $newDatas['count'] || $patientWorks['work_complete_count'] != $newDatas['work_complete_count']){
                                $workCountUP = [
                                    'work_count'=>$newDatas['work_count'],
                                    'work_complete_count'=>$newDatas['work_complete_count'],
                                    'update_time'=>$patientWorks['update_time'],
                                    'update_user_id'=>$patientWorks['update_user_id'],
                                ];
                                $resultWork = $this->LocalService()->patientWorkCountEdc->update($workCountUP, [
                                    'is_del' => 0,
                                    'id' => $patientWorks['id'],
                                ]);
                            }
                        }
                    }
                }
            }
        return true;
    }

    public function syncDatas($where = []){
        if  (empty($where['item_id'])){
            echo '参数不正确';die;
        }
        if  (!isset($where['sync']) || !in_array($where['sync'],[1,3,4])){
            echo $where['sync'].'参数没有设置或不等于[3,4]';die;
        }
        if (($where['sync'] == 3) && empty($where['patient_id'])){
            echo '参数不正确';die;
        }
        if ($where['sync'] == 1){
            if (isset($where['item_id']) && isset($where['itemsig_id'])){
                $patientWhere = [
                    'is_del' => 0,
                    'item_id' => $where['item_id'],
                    'itemsig_id' => $where['itemsig_id']
                ];
                if (isset($where['id']) && !empty($where['id'])){
                    $patientWhere['id'] = explode(',', $where['id']);
                }
                $patientId = $this->LocalService()->patient->fetchCol('id',$patientWhere);
                if (!empty($patientId)){
                    $where['patient_id'] = $patientId;
                }
            }

        }
        $this->LocalService()->swTaskClient->send([
            'svName' => 'patientChecktimeList',
            'methodName' => 'updateOldCheckData',
            'params' => $where
        ]);

    }
    public function updateOldCheckData($where = []){
        if  (empty($where['item_id'])){
            echo '参数不正确';die;
        }
        if  (!isset($where['sync']) || !in_array($where['sync'],[1,3,4])){
            echo $where['sync'].'参数没有设置或不等于[3,4]';die;
        }
        if (($where['sync'] == 3) && empty($where['patient_id'])){
            echo '参数不正确';die;

        }
        $this->patientChecktimeInsert($where['item_id'],$where['patient_id'],$where['sync']);
    }

}