<?php

namespace Application\Service\DB\Project;

use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\WsHelper;
use Application\Service\Extension\MiniAppWs\App;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Expression;
use Laminas\Db\Sql\Predicate\Operator;

class Csae extends \Application\Service\DB\AbstractDb {

    /** @var int AE属于新增AE */
    public const AE_ESTIMATE_TYPE_NEW = 6;

    public const AE_ESTIMATE_TYPE_HAS = 5;


    public function __construct($dbAdapter, ContainerInterface $container) {
        $this->tableName = 'yikeen_item_csae';
        parent::__construct($dbAdapter, $container);
    }

    //合并数据
    public function mergeCsaeData($itemCsaeData,$columns = [],$item_checkname_id = ''){
        $patientChangeIdS = implode(',',array_column($itemCsaeData,'patient_change_id'));
        $whereItemChange['where'] = [
            'is_del' => 0,
            'id' => $patientChangeIdS
        ];
        if(!empty($columns)) $whereItemChange['columns'] = $columns;
        if(!empty($item_checkname_id)) $whereItemChange['where']['item_checkname_id'] = $item_checkname_id;
        $itemIdentificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($whereItemChange);
        if (!empty($itemIdentificationresultchangeData)){
            $itemIdentificationresultchangeDatas = [];
            foreach ($itemIdentificationresultchangeData as $itemIdentificationresultchangeDataKey=>$itemIdentificationresultchangeDataValue) {
                $patientChangeId = $itemIdentificationresultchangeDataValue['id'];
                unset($itemIdentificationresultchangeDataValue['id']);
                $itemIdentificationresultchangeDatas[$patientChangeId] = $itemIdentificationresultchangeDataValue;
            }
            foreach ($itemCsaeData as $itemCsaeDataK=>&$itemCsaeDataV){
                if (!empty($item_checkname_id)){
                    if (isset($itemIdentificationresultchangeDatas[$itemCsaeDataV['patient_change_id']])){
                        $itemCsaeDataV = array_merge($itemCsaeDataV,$itemIdentificationresultchangeDatas[$itemCsaeDataV['patient_change_id']]);
                    }else{
                        unset($itemCsaeData[$itemCsaeDataK]);
                    }
                }else{
                    if (isset($itemIdentificationresultchangeDatas[$itemCsaeDataV['patient_change_id']])){
                        $itemCsaeDataV = array_merge($itemCsaeDataV,$itemIdentificationresultchangeDatas[$itemCsaeDataV['patient_change_id']]);
                    }
                }

            }
            $newItemCsaeData = array_merge($itemCsaeData);
        }
        return $newItemCsaeData;
    }
    public function arrayChangeIndexs($data,$field='id'){
        $datas = [];
        if (!empty($data)){
            foreach ($data as $key=>$value){
                $datas[$value[$field]] = $value;
            }
        }

        return $datas;
    }

    public function miniAppWsUser($data= []){
        if(empty($data['item_id'])) return false;
        $itemChangeIsSureCount = $this->LocalService()->itemIdentificationresultchange->getCount([
            'is_del' => 0,
            'lock_state' => 1,
            'is_normal_type' => 2,
            'is_sure' => 0,
            'item_id' => $data['item_id'],
         ]);
        $miniAppWs = new App();
        $miniAppWs->itemId = $data['item_id'];
        $miniAppWs->menuId = App::MODULE_CS;
        if (!empty($itemChangeIsSureCount)){
            if(!empty($data['type'])){
                $userIdData = $this->itemSignatoryRoleUser($data);
                //添加
                if (!empty($userIdData['adminUserIdDatas'])){
                    $miniAppWs->push($userIdData['adminUserIdDatas']);
                }
            } else{
                //删除
                $removeUserIdData = $this->itemChangeIsSureCount($data);
                if (!empty($removeUserIdData)){
                    $miniAppWs->remove($removeUserIdData);
                }
            }

        }else{
            unset($data['itemsig_id']);
            $removeUserIdData = $this->itemSignatoryRoleUser($data)['adminUserIdDatas'];
            if (!empty($removeUserIdData)){
                $miniAppWs->remove($removeUserIdData);
            }
        }

        return true;
    }

    public function itemSignatoryRoleUser($data= []){
        $returnData['adminUserIdDatas'] = [];
        $returnData['rolesignatoryrelationDatas'] = [];
        if (empty($data['select_type'])){
            if(empty($data['item_id'])) return $returnData;
            //查询角色下的角色管理用户信息
            $itemFid = $this->LocalService()->itemInfo->getOneFieldVal('fid', [
                'is_del' => 0,
                'id' => $data['item_id'],
            ]);
            if(empty($itemFid)) return $returnData;
            $where = [
                'is_del' => 0,
                'status' => 0,
                'item_id' => $itemFid,
            ];
        }else{
            $where = [
                'is_del' => 0,
                'status' => 0,
            ];
        }
        !empty($data['itemsig_id']) && $where['item_sign_id'] = $data['itemsig_id'];
        $whereroleSignatoryRelation['where'] = $where;
        $whereroleSignatoryRelation['columns'] = ['id', 'item_id', 'role_id', 'item_sign_id', 'signatory_user'];
        $rolesignatoryrelationData = $this->LocalService()->roleSignatoryRelation->fetchAll($whereroleSignatoryRelation);
        $rolesignatoryrelationDatas = [];
        $signatoryUserData = [];
        if (!empty($rolesignatoryrelationData)){
            foreach ($rolesignatoryrelationData as $rolesignatoryrelationDataKey=>$rolesignatoryrelationDataValue) {
                if (isset($rolesignatoryrelationDatas[$rolesignatoryrelationDataValue['item_id'].'-'.$rolesignatoryrelationDataValue['item_sign_id']][$rolesignatoryrelationDataValue['signatory_user']])){
                    $rolesignatoryrelationDatas[$rolesignatoryrelationDataValue['item_id'].'-'.$rolesignatoryrelationDataValue['item_sign_id']][$rolesignatoryrelationDataValue['signatory_user']] = $rolesignatoryrelationDataValue['signatory_user'];
                    $signatoryUserData[$rolesignatoryrelationDataValue['signatory_user']] = $rolesignatoryrelationDataValue['signatory_user'];
                }else{
                    $rolesignatoryrelationDatas[$rolesignatoryrelationDataValue['item_id'].'-'.$rolesignatoryrelationDataValue['item_sign_id']][$rolesignatoryrelationDataValue['signatory_user']] = $rolesignatoryrelationDataValue['signatory_user'];
                    $signatoryUserData[$rolesignatoryrelationDataValue['signatory_user']] = $rolesignatoryrelationDataValue['signatory_user'];

                }
            }

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

        //中心用户
        if (empty($rolesignatoryrelationDatas))  return $returnData;
        $whereSignatoryUser = [
            'where'=>[
                'is_del'=>0,
                'id'=>$signatoryUserData,
            ],
            'columns'=>[
                'id','user_name','user_tel',
            ],
        ];
        $newSignatoryUserDatas = [];
        $newSignatoryUserData = $this->LocalService()->signatoryUser->fetchAll($whereSignatoryUser);
        if (empty($newSignatoryUserData))  return $returnData;
        $userTelData = [];
        foreach ($newSignatoryUserData as $newSignatoryUserDataKey=>$newSignatoryUserDataValue) {
            if(empty($newSignatoryUserDataValue['user_tel'])) continue;
            if (isset($userTelData[$newSignatoryUserDataValue['user_tel']])){
                $userTelData[$newSignatoryUserDataValue['user_tel']] = $newSignatoryUserDataValue;
            }else{
                $userTelData[$newSignatoryUserDataValue['user_tel']] = $newSignatoryUserDataValue;
            }
        }

        //admin用户
        if (empty($userTelData))  return $returnData;
        $newUserTelData = array_keys($userTelData);
        $whereAdminUser = [
            'where'=>[
                'is_del'=>0,
                'real_status'=>0,
                'mobile'=>$newUserTelData,
            ],
            'columns'=>[
                'id','realname','mobile',
            ],
        ];
        $adminUserDatas = [];
        $adminUserData = $this->LocalService()->adminUser->fetchAll($whereAdminUser);

        if (empty($adminUserData))  return $returnData;
        $adminUserDatas = array_column($adminUserData,null,'mobile');
        if (empty($adminUserDatas))  return $adminUserDatas;
        foreach ($userTelData as $userTelDataKeys=>&$userTelDataValues) {
            if (isset($adminUserDatas[$userTelDataKeys])){
                $userTelDataValues['admin_user_id'] = $adminUserDatas[$userTelDataKeys]['id'];
            }else{
                unset($userTelData[$userTelDataKeys]);
            }
        }


        //合并
        $newSignatoryUserIdData = array_column($userTelData,null,'id');
        $adminUserIdDatas = [];

        foreach ($rolesignatoryrelationDatas as $rolesignatoryrelationDatasKey=>&$rolesignatoryrelationDatasValue){
            foreach ($rolesignatoryrelationDatasValue as $rolesignatoryrelationUserIdKey=>$rolesignatoryrelationUserIdValue) {
                if(isset($newSignatoryUserIdData[$rolesignatoryrelationUserIdValue])){
                    $adminUserIdDatas[$rolesignatoryrelationUserIdValue] = $newSignatoryUserIdData[$rolesignatoryrelationUserIdValue]['admin_user_id'];
                    $rolesignatoryrelationDatasValue[$rolesignatoryrelationUserIdKey] = $newSignatoryUserIdData[$rolesignatoryrelationUserIdValue]['admin_user_id'];
                }else{
                    unset($rolesignatoryrelationDatasValue[$rolesignatoryrelationUserIdKey]);
                }
            }

        }
        $returnData['adminUserIdDatas'] = $adminUserIdDatas;
        $returnData['rolesignatoryrelationDatas'] = $rolesignatoryrelationDatas;

        return $returnData;
    }

    public function usertRolesignatoryrelation ($data = []){
        $mobile = $this->LocalService()->identity->getMobile()?:0;
        $userId = $this->LocalService()->signatoryUser->getOneFieldVal('id', [
            'is_del' => 0,
            'user_tel' => $mobile,
        ]);

        $returnData = [];
        if(empty($data['item_id'])) return $returnData;
        //查询角色下的角色管理用户信息
        $itemFid = $this->LocalService()->itemInfo->getOneFieldVal('fid', [
            'is_del' => 0,
            'id' => $data['item_id'],
        ]);
        if(empty($itemFid)) return $returnData;
        $where = [
            'is_del' => 0,
            'status' => 0,
            'item_id' => $itemFid,
            'signatory_user' => $userId,
        ];

        $whereroleSignatoryRelation['where'] = $where;
        $whereroleSignatoryRelation['columns'] = ['id', 'item_id', 'role_id', 'item_sign_id', 'signatory_user'];
        $rolesignatoryrelationData = $this->LocalService()->roleSignatoryRelation->fetchAll($whereroleSignatoryRelation);
        $rolesignatoryrelationDatas = [];
        $signatoryUserData = [];
        if (!empty($rolesignatoryrelationData)){
            foreach ($rolesignatoryrelationData as $rolesignatoryrelationDataKey=>$rolesignatoryrelationDataValue) {
                if (isset($rolesignatoryrelationDatas[$rolesignatoryrelationDataValue['item_id'].'-'.$rolesignatoryrelationDataValue['item_sign_id']][$rolesignatoryrelationDataValue['signatory_user']])){
                    $rolesignatoryrelationDatas[$rolesignatoryrelationDataValue['item_id'].'-'.$rolesignatoryrelationDataValue['item_sign_id']][$rolesignatoryrelationDataValue['signatory_user']] = $rolesignatoryrelationDataValue['signatory_user'];
                    $signatoryUserData[$rolesignatoryrelationDataValue['signatory_user']] = $rolesignatoryrelationDataValue['signatory_user'];
                }else{
                    $rolesignatoryrelationDatas[$rolesignatoryrelationDataValue['item_id'].'-'.$rolesignatoryrelationDataValue['item_sign_id']][$rolesignatoryrelationDataValue['signatory_user']] = $rolesignatoryrelationDataValue['signatory_user'];
                    $signatoryUserData[$rolesignatoryrelationDataValue['signatory_user']] = $rolesignatoryrelationDataValue['signatory_user'];

                }
            }

        }
    }

    //删除数据
    public function itemChangeIsSureCount($data) {
        //当前中心下还有没有没处理的，如果为空就删除
        $itemChangeIsSureCount = $this->LocalService()->itemIdentificationresultchange->getCount([
            'is_del' => 0,
            'lock_state' => 1,
            'is_normal_type' => 2,
            'is_sure' => 0,
            'item_id' => $data['item_id'],
            'itemsig_id' => $data['itemsig_id'],
        ]);
        if(!empty($itemChangeIsSureCount)){
            $currentDatas = $this->itemSignatoryRoleUser($data);
            if (!empty($currentDatas['adminUserIdDatas'])){
                //所有有未处理的中心
                $itemIdentificationresultchangeWhere['where'] = [
                    'item_id' => $data['item_id'],
                    'itemsig_id' => $data['itemsig_id'],
                    'is_del' => 0,
                    'lock_state' => 1,
                    'is_normal_type' => 2,
                    'is_sure' => 0
                ];
                $itemIdentificationresultchangeWhere['columns'] = [
                    'count'=>new Expression('count(*)'),
                    'id',
                    'item_id',
                    'itemsig_id',
                ];
                $itemIdentificationresultchangeWhere['group'] = ['itemsig_id'];
                $itemChangeIsSureData = $this->LocalService()->itemIdentificationresultchange->fetchAll($itemIdentificationresultchangeWhere);
                $notHandle  = [];
                $tempNotHandle  = [];
                if(!empty($itemChangeIsSureData)){
                    foreach($itemChangeIsSureData as $itemChangeIsSureDataKey=>$itemChangeIsSureDataValue){
                        $rolesignatoryrelationDatas = $this->itemSignatoryRoleUser($itemChangeIsSureDataValue);
                        if (!empty($rolesignatoryrelationDatas['adminUserIdDatas'])) $tempNotHandle[$itemChangeIsSureDataKey] = $rolesignatoryrelationDatas['adminUserIdDatas'];
                    }

                    if(!empty($tempNotHandle)){
                        $strId = '';
                        foreach ($tempNotHandle as $item) {
                            $strId .= implode(',', $item).',';
                        }
                        $notHandle = array_diff($currentDatas['adminUserIdDatas'],explode(',',trim($strId,',')));
                        return $notHandle;

                    }else{
                        //直接删除
                        return $currentDatas['adminUserIdDatas'];
                    }
                }else{
                    //直接删除
                    return $currentDatas['adminUserIdDatas'];
                }
            }
        }
        return [];
        echo '<pre>';print_r($datas);die;
    }

    /**
     * @$item_id 项目中心ID
     * @$itemsig_id 项目中心ID
     * @$patient_id 受试者ID
     * @$item_checkname_id 指标ID
     * @$chang_id change表的唯一ID
     *
     */
    public function isAnnulChecknameSaveAction($chang_id=0,$item_id =0 ,$itemsig_id=0,$patient_id=0,$item_checkname_id=0,$patient_form_id=0,$types=0){

        if (empty($chang_id)) return false;

        //获取解锁的识别结果指标ID
        $identificationresultchange_where['where'] = [
            'lock_state' => 1,
            'is_del' => 0,
            'is_annul' => 0,
            'id' => $chang_id
        ];

        $identificationresultchangeData = $this->LocalService()->itemIdentificationresultchange->fetchAll($identificationresultchange_where);
        if(empty($identificationresultchangeData)) return false;


        $postData = [
            'item_id'=>$item_id?:$identificationresultchangeData[0]['item_id'],
            'itemsig_id'=>$itemsig_id?:$identificationresultchangeData[0]['itemsig_id'],
            'patient_id'=>$patient_id?:$identificationresultchangeData[0]['patient_id'],
            'item_checkname_id'=>$item_checkname_id?:$identificationresultchangeData[0]['item_checkname_id'],
            'patient_form_id'=>$patient_form_id?:$identificationresultchangeData[0]['patient_form_id'],
        ];

        $postData['destroy_remark'] = $destroy_remark = '质疑系统自动作废指标';
        $postData['destroy_date'] = $destroy_date =  time();


        $csae_where = [
            'is_del' => 0,
            'patient_change_id' => $chang_id,
        ];
        $identificationresultchange_id_arr = array_column($identificationresultchangeData,'id');
        $identificationresultchange_id = empty($identificationresultchange_id_arr) ? '' : implode(',',$identificationresultchange_id_arr);
        $postData['identificationresultchange_id'] = $identificationresultchange_id;

        //保存销毁信息
        $csae_data = $this->LocalService()->itemCsae->fetchOne(['where'=>$csae_where]);//获取csae信息
        $csae_data = empty($csae_data) ? [] : $csae_data;
        $save_data = [
            'item_id' => $postData['item_id'],
            'itemsig_id' =>$postData['itemsig_id'] ,
            'patient_id' => $postData['patient_id'],
            'patient_form_id' => $postData['patient_form_id'],
            'item_checkname_id' =>$postData['item_checkname_id'] ,
            'destroy_remark' => $postData['destroy_remark'],
            'destroy_date' => $destroy_date,
            'identificationresultchange_id' => $identificationresultchange_id,
            'csae_data' => json_encode($csae_data)
        ];
        $result = $this->LocalService()->itemIdentificationresultdestroy->save($save_data);
        if ($result) {
            $this->LocalService()->itemIdentificationresultchange->update([
                'is_annul'=>1,
                'is_sure'=>0
            ],[
                'id' => StringHelper::toArray($identificationresultchange_id)
            ]);
            $this->LocalService()->itemCsae->update(['is_del'=>1],$csae_where);
            empty($types) && $this->LocalService()->log->saveFileLog($result,'itemIdentificationresultdestroy',$postData,1,'单个指标解锁', $item_id);

            foreach ($identificationresultchangeData as $identificationresultchangeDataKey=>$identificationresultchangeDataValue){
                $asyncErr = $identificationresultchangeDataValue['item_id'].'-'.$identificationresultchangeDataValue['itemsig_id'].'-'.$identificationresultchangeDataValue['patient_id'].'-'.$identificationresultchangeDataValue['patient_form_id'].'-'.$identificationresultchangeDataValue['category_id'].'-'.$identificationresultchangeDataValue['checktime_id'].'-'.$identificationresultchangeDataValue['form_id'];
                $asyncErr = $this->LocalService()->itemIdentificationresultchange->asyncErr($asyncErr);
                $this->LocalService()->swTaskClient->send([
                    'svName' => 'itemIdentificationresultchange',
                    'methodName' => 'newItemIdentificationResultChangeWriteFileUPdate',
                    'params' => $identificationresultchangeDataValue
                ]);
            }

        }

        return true;

    }

    /**
     * @$chang_id change表的唯一ID
     *
     */
    public function isAnnulDate($chang_id=0){
        if (empty($chang_id)) return false;
        //获取解锁的识别结果指标ID
        $identificationresultchange_where['where'] = [
            'lock_state' => 1,
            'is_del' => 0,
            'id' => $chang_id
        ];
        $identificationresultchangeInfo = $this->LocalService()->itemIdentificationresultchange->fetchOne($identificationresultchange_where);
        if(empty($identificationresultchangeInfo)) return false;

        $whereWork = [
            'item_id'=>$identificationresultchangeInfo['item_id'],
            'itemsig_id'=>$identificationresultchangeInfo['itemsig_id'],
            'checktime_id'=>$identificationresultchangeInfo['checktime_id'],
            'patient_form_id'=>$identificationresultchangeInfo['patient_form_id'],
            'is_del'=>0,
        ];
        $isQuestionDate = $this->LocalService()->itemPatientworkannex->update(['is_question_date'=>$chang_id],$whereWork);
        return true;
    }

    /**
     * Notes:获取指定条件下的数据
     * User: lltyy
     * DateTime: 2024/5/15 9:20
     *
     * @param $where 条件
     * @param $columns 字段
     * @param string $key 键值
     * @param int $is_more 是否有多笔数据【0 否 1 是】
     * @return array
     */
    public function fetchDataByKey($where,$columns,$key='id',$is_more = 0){
        $datas = [];
        $cond = [
            'where'=>$where,
            'columns'=>$columns,
            'order'=>['item_id','patient_id']
        ];
        $infoDatas = $this->fetchAll($cond);
        if(!empty($infoDatas)){
            foreach($infoDatas as $infoKey=>$infoData){
                $data_key = isset($infoData[$key]) && !empty($infoData[$key]) ? $infoData[$key] : '';
                if($is_more == 1){
                    $datas[$data_key][] = $infoData;
                }else{
                    $datas[$data_key] = $infoData;
                }
                unset($infoDatas[$data_key]);
            }
        }
        unset($cond);
        unset($infoDatas);

        return $datas;
    }


    /**
     * Notes: 异步处理
     * @param
     * @return
     * @author haojinhua
     * @date 2024-09-30
     */
    public function caseredis($info = []){
        $item_id = isset($info['item_id']) && !empty($info['item_id']) ? $info['item_id'] : 0;
        $item_sig_ids = isset($info['itemsig_ids']) && !empty($info['itemsig_ids']) ? $info['itemsig_ids'] : 0;
        if(!empty($item_id) && !empty($item_sig_ids)){
            foreach ($item_sig_ids as $itemsig_id){
                WsHelper::flushAeMessage($item_id, $itemsig_id);
            }
        }
    }

    /**
     * Notes: 获取AE结果数据
     * User: lltyy
     * DateTime: 2024/10/24 9:19
     *
     */
    public function fetchCheckFieldAeData(array $arr = []){
        $info = [];
        $item_id = isset($arr['item_id']) && !empty($arr['item_id']) ? $arr['item_id'] : 0;
        $itemsig_id = isset($arr['itemsig_id']) && !empty($arr['itemsig_id']) ? $arr['itemsig_id'] : [];
        $patient_id = isset($arr['patient_id']) && !empty($arr['patient_id']) ? $arr['patient_id'] : [];
        $form_id = isset($arr['form_id']) && !empty($arr['form_id']) ? $arr['form_id'] : [];
        $checktime_id = isset($arr['checktime_id']) && !empty($arr['checktime_id']) ? $arr['checktime_id'] : [];
        $type = isset($arr['type']) && !empty($arr['type']) ? $arr['type'] : 0;//数据类型【0 检查项AE 1 表单内容AE】
        if(!empty($item_id)){
            //检查项AE
            if($type == 0){
                //获取检查项对应的表单内容ID
                $itemChecknameWhere = [
                    'is_del' => 0,
                    'form_field_id' => 0,
                    'item_id' => $item_id
                ];
                $itemChecknameArr = $this->LocalService()->itemCheckname->fetchCol('id',$itemChecknameWhere);
                unset($itemChecknameWhere);

                //获取异常判断为CS对应的患者进度表单填写ID信息
                $resultChangeWhere = [
                    'is_del' => 0,
                    'is_normal_type' => 2,
                ];
                if(!empty($itemChecknameArr)){
                    $resultChangeWhere['item_checkname_id'] = StringHelper::toArray(array_values($itemChecknameArr));
                }else{
                    $resultChangeWhere = [
                        'id' => 0,
                    ];
                }
                if(!empty($itemsig_id)){
                    $resultChangeWhere['itemsig_id'] = StringHelper::toArray($itemsig_id);
                }
                if(!empty($patient_id)){
                    $resultChangeWhere['patient_id'] = StringHelper::toArray($patient_id);
                }
                if(!empty($form_id)){
                    $resultChangeWhere['form_id'] = StringHelper::toArray($form_id);
                }
                if(!empty($checktime_id)){
                    $resultChangeWhere['checktime_id'] = StringHelper::toArray($checktime_id);
                }
                $resultChangeArr = $this->LocalService()->itemIdentificationresultchange->fetchCol('id',$resultChangeWhere);
                unset($resultChangeWhere);

                //获取AE信息
                $aeWhere = [
                    'is_del' => 0,
                    'is_ae_sure' => 1,
                ];
                if(!empty($resultChangeArr)){
                    $aeWhere['patient_change_id'] = StringHelper::toArray(array_values($resultChangeArr));
                }else{
                    $aeWhere = [
                        'id' => 0,
                    ];
                }
                $aeDatas = $this->fetchAll([
                    'where'=>$aeWhere,
                    'columns'=>['id','patient_change_id','item_checkname_id','ae_type','ae_remarks','relation_ae_id']
                ]);
                unset($aeWhere);
                if(!empty($aeDatas)){
                    $ae_type_show = [0=>'',1=>'非AE与研究疾病有关',2=>'非AE与病史有关',3=>'非AE与合并用药有关',4=>'非AE其他原因',5=>'属于已有AE',6=>'属于新增AE'];
                    //获取新增AE关联内容ID
                    $patientAeContentIdArr = [];
                    $csaeRelations = $this->LocalService()->itemCsaeRelation->fetchDataByKey([
                        'is_del' => 0,
                        'csae_id' => StringHelper::toArray(array_values(array_column($aeDatas,'id'))),
                        new Operator('content_id', Operator::OP_GT, 0),
                    ],['csae_id','content_id'],'csae_id',1);
                    $csaeRelationArr = [];
                    if(!empty($csaeRelations)){
                        foreach($csaeRelations as $csaeId=>$csaeRelation){
                            foreach($csaeRelation as $csaeRelationInfo){
                                $csaeRelationArr[$csaeId][] = $csaeRelationInfo['content_id'];
                                $patientAeContentIdArr[] = $csaeRelationInfo['content_id'];
                            }
                        }
                    }
                    unset($csaeRelations);

                    //获取已有AE关联内容ID
                    $csaeCheckeds = $this->LocalService()->itemCsaeChecked->fetchDataByKey([
                        'is_del' => 0,
                        'csae_id' => StringHelper::toArray(array_values(array_column($aeDatas,'id'))),
                        new Operator('content_id', Operator::OP_GT, 0),
                    ],['csae_id','content_id'],'csae_id',1);
                    $csaeCheckedArr = [];
                    if(!empty($csaeCheckeds)){
                        foreach($csaeCheckeds as $csaeCheckId=>$csaeChecked){
                            foreach($csaeChecked as $csaeCheckedInfo){
                                $csaeCheckedArr[$csaeCheckId][] = $csaeCheckedInfo['content_id'];
                                $patientAeContentIdArr[] = $csaeCheckedInfo['content_id'];
                            }
                        }
                    }
                    unset($csaeCheckeds);

                    //获取AE信息
                    $patientAeContentArr = [];
                    if(!empty($patientAeContentIdArr)){
                        $patientAeContentDatas = $this->LocalService()->itemPatientAeContent->fetchAll([
                            'where'=> [
                                'is_del' => 0,
                                'id' => StringHelper::toArray($patientAeContentIdArr),
                            ],
                            'columns'=>['id','data']
                        ]);
                        if(!empty($patientAeContentDatas)){
                            //获取AE名称ID
                            $aeVersion = ArrayHelper::index(SDMHelper::app()->form->getVersionData(SDMHelper::app()->form->getAeForm($item_id)['id']), 'var_name');
                            $AENameFieldId = isset($aeVersion['AETERM']) && isset($aeVersion['AETERM']['id']) && !empty($aeVersion['AETERM']['id']) ? $aeVersion['AETERM']['id'] : '';
                            unset($aeVersion);
                            foreach($patientAeContentDatas as $patientAeContentKey=>$patientAeContentData){
                                $patientAeContentData_content = StringHelper::jsonDecode($patientAeContentData['data']);
                                if($AENameFieldId != ''){
                                    if(isset($patientAeContentData_content[$AENameFieldId]) && $patientAeContentData_content[$AENameFieldId] != ''){
                                        $patientAeContentArr[$patientAeContentData['id']] = $patientAeContentData_content[$AENameFieldId];
                                    }else{
                                        if(!empty($patientAeContentData_content)){
                                            foreach($patientAeContentData_content as $patientAeContentDataKey=>$patientAeContentData_contentInfo){
                                                if(strpos($patientAeContentDataKey,$AENameFieldId.'-') !== false){
                                                    $patientAeContentDataKey_arr = explode('-',$patientAeContentDataKey);
                                                    if($patientAeContentDataKey_arr[0] == $AENameFieldId && $patientAeContentData_contentInfo != ''){
                                                        $patientAeContentArr[$patientAeContentData['id']] = $patientAeContentData_contentInfo;
                                                    }
                                                    unset($patientAeContentDataKey_arr);
                                                }
                                            }
                                        }
                                    }
                                }
                                unset($patientAeContentData_content);
                                unset($patientAeContentDatas[$patientAeContentKey]);
                            }
                            unset($AENameFieldId);
                        }
                        unset($patientAeContentDatas);
                    }
                    unset($patientAeContentIdArr);

                    foreach($aeDatas as $aeKey=>$aeData){
                        $patientChangeId = isset($resultChangeArr[$aeData['patient_change_id']]) && !empty($resultChangeArr[$aeData['patient_change_id']]) ? $resultChangeArr[$aeData['patient_change_id']] : 0;
                        $itemCheck = isset($itemChecknameArr[$aeData['item_checkname_id']]) && !empty($itemChecknameArr[$aeData['item_checkname_id']]) ? $itemChecknameArr[$aeData['item_checkname_id']] : 0;
                        if(!empty($patientChangeId) && !empty($itemCheck)){
                            $show_ae = [];
                            $ae_status = isset($ae_type_show[$aeData['ae_type']]) && !empty($ae_type_show[$aeData['ae_type']]) ? '['.$ae_type_show[$aeData['ae_type']].']' : '';
                            if(in_array($aeData['ae_type'],[5,6])){//属于新增AE
                                $csae_contentids = [];
                                if($aeData['ae_type'] == 5){//属于已有AE
                                    $ae_status = '';
                                    $csae_contentids = isset($csaeCheckedArr[$aeData['id']]) && !empty($csaeCheckedArr[$aeData['id']]) ? $csaeCheckedArr[$aeData['id']] : [];
                                }
                                if($aeData['ae_type'] == 6){//属于新增AE
                                    $ae_status = '';
                                    $csae_contentids = isset($csaeRelationArr[$aeData['id']]) && !empty($csaeRelationArr[$aeData['id']]) ? $csaeRelationArr[$aeData['id']] : [];
                                }
                                if(!empty($csae_contentids)){
                                    foreach($csae_contentids as $csae_contentid){
                                        if(isset($patientAeContentArr[$csae_contentid]) && $patientAeContentArr[$csae_contentid] != ''){
                                            //$show_ae[] = $ae_status.'(不良事件名称：'.$patientAeContentArr[$csae_contentid].')';
                                            $show_ae[] = $ae_status.$patientAeContentArr[$csae_contentid];
                                        }
                                    }
                                }
                                if(empty($show_ae)){
                                    //$show_ae[] = $ae_status.'(不良事件名称：)';
                                    $show_ae[] = $ae_status;
                                }
                            }else{
                                if($aeData['ae_type'] == 4 && $aeData['ae_remarks'] != ''){//非AE其他原因
                                    $ae_status .= $aeData['ae_remarks'];
                                }
                                $show_ae[] = $ae_status;
                            }
                            $info[$patientChangeId][$itemCheck] = [
                                'ae_type'=>$aeData['ae_type'],
                                'ae_remarks'=>$aeData['ae_remarks'],
                                'relation_ae_id'=>$aeData['relation_ae_id'],
                                'show_ae'=>$show_ae
                            ];
                            unset($show_ae);
                        }
                        unset($patientChangeId);
                        unset($itemCheck);
                        unset($aeDatas[$aeKey]);
                    }
                    unset($ae_type_show);
                }
                unset($aeDatas);
                unset($resultChangeArr);
                unset($itemChecknameArr);
            }

            //表单内容AE
            if($type == 1) {
                //获取检查项对应的表单内容ID
                $itemChecknameFieldWhere = [
                    'is_del' => 0,
                    'item_id' => $item_id,
                    new Operator('form_field_id', Operator::OP_GT, 0),
                ];
                if (!empty($form_id)) {
                    $itemChecknameFieldWhere['form_id'] = StringHelper::toArray($form_id);
                }
                $itemChecknameFieldArr = $this->LocalService()->itemCheckname->fetchCol('form_field_id', $itemChecknameFieldWhere);
                unset($itemChecknameFieldWhere);

                //获取异常判断为CS对应的患者进度表单填写ID信息
                $resultChangeFormcontentWhere = [
                    'is_del' => 0,
                    'is_normal_type' => 2,
                    new Operator('patientformcontent_id', Operator::OP_GT, 0),
                ];
                if (!empty($itemChecknameFieldArr)) {
                    $resultChangeFormcontentWhere['item_checkname_id'] = StringHelper::toArray(array_values(array_keys($itemChecknameFieldArr)));
                } else {
                    $resultChangeFormcontentWhere = [
                        'id' => 0,
                    ];
                }
                if (!empty($itemsig_id)) {
                    $resultChangeFormcontentWhere['itemsig_id'] = StringHelper::toArray($itemsig_id);
                }
                if (!empty($patient_id)) {
                    $resultChangeFormcontentWhere['patient_id'] = StringHelper::toArray($patient_id);
                }
                if (!empty($form_id)) {
                    $resultChangeFormcontentWhere['form_id'] = StringHelper::toArray($form_id);
                }
                $resultChangeFormcontentArr = $this->LocalService()->itemIdentificationresultchange->fetchCol('patientformcontent_id', $resultChangeFormcontentWhere);
                unset($resultChangeFormcontentWhere);

                //获取AE信息
                $aeWhere = [
                    'is_del' => 0,
                    'is_ae_sure' => 1,
                ];
                if (!empty($resultChangeFormcontentArr)) {
                    $aeWhere['patient_change_id'] = StringHelper::toArray(array_values(array_keys($resultChangeFormcontentArr)));
                } else {
                    $aeWhere = [
                        'id' => 0,
                    ];
                }
                $aeDatas = $this->fetchAll([
                    'where' => $aeWhere,
                    'columns' => ['id', 'patient_change_id', 'item_checkname_id', 'ae_type', 'ae_remarks', 'relation_ae_id']
                ]);
                unset($aeWhere);
                if (!empty($aeDatas)) {
                    $ae_type_show = [0 => '', 1 => '非AE与研究疾病有关', 2 => '非AE与病史有关', 3 => '非AE与合并用药有关', 4 => '非AE其他原因', 5 => '属于已有AE', 6 => '属于新增AE'];
                    //获取新增AE关联内容ID
                    $patientAeContentIdArr = [];
                    $csaeRelations = $this->LocalService()->itemCsaeRelation->fetchDataByKey([
                        'is_del' => 0,
                        'csae_id' => StringHelper::toArray(array_values(array_column($aeDatas, 'id'))),
                        new Operator('content_id', Operator::OP_GT, 0),
                    ], ['csae_id', 'content_id'], 'csae_id', 1);
                    $csaeRelationArr = [];
                    if (!empty($csaeRelations)) {
                        foreach ($csaeRelations as $csaeId => $csaeRelation) {
                            foreach ($csaeRelation as $csaeRelationInfo) {
                                $csaeRelationArr[$csaeId][] = $csaeRelationInfo['content_id'];
                                $patientAeContentIdArr[] = $csaeRelationInfo['content_id'];
                            }
                        }
                    }
                    unset($csaeRelations);

                    //获取已有AE关联内容ID
                    $csaeCheckeds = $this->LocalService()->itemCsaeChecked->fetchDataByKey([
                        'is_del' => 0,
                        'csae_id' => StringHelper::toArray(array_values(array_column($aeDatas, 'id'))),
                        new Operator('content_id', Operator::OP_GT, 0),
                    ], ['csae_id', 'content_id'], 'csae_id', 1);
                    $csaeCheckedArr = [];
                    if (!empty($csaeCheckeds)) {
                        foreach ($csaeCheckeds as $csaeCheckId => $csaeChecked) {
                            foreach ($csaeChecked as $csaeCheckedInfo) {
                                $csaeCheckedArr[$csaeCheckId][] = $csaeCheckedInfo['content_id'];
                                $patientAeContentIdArr[] = $csaeCheckedInfo['content_id'];
                            }
                        }
                    }
                    unset($csaeCheckeds);

                    //获取AE信息
                    $patientAeContentArr = [];
                    if (!empty($patientAeContentIdArr)) {
                        $patientAeContentDatas = $this->LocalService()->itemPatientAeContent->fetchAll([
                            'where' => [
                                'is_del' => 0,
                                'id' => StringHelper::toArray($patientAeContentIdArr),
                            ],
                            'columns' => ['id', 'data']
                        ]);
                        if (!empty($patientAeContentDatas)) {
                            //获取AE名称ID
                            $aeVersion = ArrayHelper::index(SDMHelper::app()->form->getVersionData(SDMHelper::app()->form->getAeForm($item_id)['id']), 'var_name');
                            $AENameFieldId = isset($aeVersion['AETERM']) && isset($aeVersion['AETERM']['id']) && !empty($aeVersion['AETERM']['id']) ? $aeVersion['AETERM']['id'] : '';
                            unset($aeVersion);
                            foreach ($patientAeContentDatas as $patientAeContentKey => $patientAeContentData) {
                                $patientAeContentData_content = StringHelper::jsonDecode($patientAeContentData['data']);
                                if ($AENameFieldId != '') {
                                    if (isset($patientAeContentData_content[$AENameFieldId]) && $patientAeContentData_content[$AENameFieldId] != '') {
                                        $patientAeContentArr[$patientAeContentData['id']] = $patientAeContentData_content[$AENameFieldId];
                                    } else {
                                        if (!empty($patientAeContentData_content)) {
                                            foreach ($patientAeContentData_content as $patientAeContentDataKey => $patientAeContentData_contentInfo) {
                                                if (strpos($patientAeContentDataKey, $AENameFieldId . '-') !== false) {
                                                    $patientAeContentDataKey_arr = explode('-', $patientAeContentDataKey);
                                                    if ($patientAeContentDataKey_arr[0] == $AENameFieldId && $patientAeContentData_contentInfo != '') {
                                                        $patientAeContentArr[$patientAeContentData['id']] = $patientAeContentData_contentInfo;
                                                    }
                                                    unset($patientAeContentDataKey_arr);
                                                }
                                            }
                                        }
                                    }
                                }
                                unset($patientAeContentData_content);
                                unset($patientAeContentDatas[$patientAeContentKey]);
                            }
                            unset($AENameFieldId);
                        }
                        unset($patientAeContentDatas);
                    }
                    unset($patientAeContentIdArr);

                    foreach ($aeDatas as $aeKey => $aeData) {
                        $patientFormContent = isset($resultChangeFormcontentArr[$aeData['patient_change_id']]) && !empty($resultChangeFormcontentArr[$aeData['patient_change_id']]) ? $resultChangeFormcontentArr[$aeData['patient_change_id']] : 0;
                        $itemCheckField = isset($itemChecknameFieldArr[$aeData['item_checkname_id']]) && !empty($itemChecknameFieldArr[$aeData['item_checkname_id']]) ? $itemChecknameFieldArr[$aeData['item_checkname_id']] : 0;
                        if (!empty($patientFormContent) && !empty($itemCheckField)) {
                            $show_ae = [];
                            $ae_status = isset($ae_type_show[$aeData['ae_type']]) && !empty($ae_type_show[$aeData['ae_type']]) ? '[' . $ae_type_show[$aeData['ae_type']] . ']' : '';
                            if (in_array($aeData['ae_type'], [5, 6])) {//属于新增AE
                                $csae_contentids = [];
                                if ($aeData['ae_type'] == 5) {//属于已有AE
                                    $csae_contentids = isset($csaeCheckedArr[$aeData['id']]) && !empty($csaeCheckedArr[$aeData['id']]) ? $csaeCheckedArr[$aeData['id']] : [];
                                }
                                if ($aeData['ae_type'] == 6) {//属于新增AE
                                    $csae_contentids = isset($csaeRelationArr[$aeData['id']]) && !empty($csaeRelationArr[$aeData['id']]) ? $csaeRelationArr[$aeData['id']] : [];
                                }
                                if (!empty($csae_contentids)) {
                                    foreach ($csae_contentids as $csae_contentid) {
                                        if (isset($patientAeContentArr[$csae_contentid]) && $patientAeContentArr[$csae_contentid] != '') {
                                            $show_ae[] = $ae_status . '(不良事件名称：' . $patientAeContentArr[$csae_contentid] . ')';
                                        }
                                    }
                                }
                                if (empty($show_ae)) {
                                    $show_ae[] = $ae_status . '(不良事件名称：)';
                                }
                            } else {
                                if ($aeData['ae_type'] == 4 && $aeData['ae_remarks'] != '') {//非AE其他原因
                                    $ae_status .= '(' . $aeData['ae_remarks'] . ')';
                                }
                                $show_ae[] = $ae_status;
                            }
                            $info[$patientFormContent][$itemCheckField] = [
                                'ae_type' => $aeData['ae_type'],
                                'ae_remarks' => $aeData['ae_remarks'],
                                'relation_ae_id' => $aeData['relation_ae_id'],
                                'show_ae' => $show_ae
                            ];
                            unset($show_ae);
                        }
                        unset($patientFormContent);
                        unset($itemCheckField);
                        unset($aeDatas[$aeKey]);
                    }
                    unset($ae_type_show);
                }
                unset($aeDatas);
                unset($resultChangeFormcontentArr);
                unset($itemChecknameFieldArr);
            }

        }

        return $info;
    }
}