<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/5/6 10:57
 * @Description：
 *
 */

namespace Application\Service\DB\Item;

use Application\Service\DB\Dictionary\FormField;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\StringHelper;
use EasyWeChat\Kernel\Support\Str;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\NotIn;

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


    /**
     * Notes: 获取指定条件下的数据
     * User: lltyy
     * DateTime: 2023/4/25 10:16
     *
     * @param $where
     * @param $where
     * @return array
     */
    public function fetchDataByKey($where='is_del = 0',$columns=['id'],$order=['id'],$key='id',$is_more=0){
        $datas = [];
        $cond = [
            'where'=>$where,
            'columns'=>$columns,
            'order'=>$order
        ];
        $infoDatas = $this->fetchAll($cond);
        if(!empty($infoDatas)){
            foreach($infoDatas as $infoData){
                $data_key = $infoData[$key];
                if($is_more == 1){
                    $datas[$data_key][] = $infoData;
                }else{
                    $datas[$data_key] = $infoData;
                }
            }
        }
        unset($cond);
        unset($infoDatas);
        return $datas;
    }

    /**
     * Notes: 获取患者追加信息
     * User: lltyy
     * DateTime: 2024/8/1 17:24
     *
     * @param array $arr
     * @return array
     */
    public function fetchPatientData($arr=[]){
        $item_id = isset($arr['item_id']) && !empty($arr['item_id']) ? $arr['item_id'] : 0;
        $patient_id = isset($arr['patient_id']) && !empty($arr['patient_id']) ? $arr['patient_id'] : 0;
        $info = [];
        $key = 0;
        if(!empty($item_id)){
            $item_formfield_arr = $this->fetchAll(['where'=> [
                'is_del' => 0,
                'item_id' => $item_id,
            ],'columns'=>['form_id','field_id'],'order'=>['info_order']]);
            if(!empty($item_formfield_arr)){
                $form_arr = [
                    'key'=>[],
                    'form'=>[],
                    'field'=>[]
                ];
                $form_field_arr = array_values(array_column($item_formfield_arr,'field_id'));
                $fieldDatas = $this->LocalService()->itemFormField->fetchDataByKey([
                    'is_del' => 0,
                    new NotIn('type', [13, 14, 19]),
                    'item_id' => $item_id,
                    'id' => StringHelper::toArray($form_field_arr)
                ],['id','form_id','name','var_name','showfiled_name'],'id',0);
                unset($form_field_arr);
                $is_show_random_number_key = '';//随机号键值
                foreach($item_formfield_arr as $form_field_key=>$item_formfield){
                    $item_formfield_id = $item_formfield['field_id'];
                    if(isset($fieldDatas[$item_formfield_id]) && !empty($fieldDatas[$item_formfield_id])){
                        $key++;
                        $info[$key] = [
                            'id'=>$fieldDatas[$item_formfield_id]['form_id'].'_'.$item_formfield_id,
                            'field'=>'form_'.$fieldDatas[$item_formfield_id]['var_name'],
                            'value'=>'',
                            'attr_name'=>$fieldDatas[$item_formfield_id]['name'],
                            'attr_value'=>''
                        ];
                        $form_arr['key'][$item_formfield_id] = $key;
                        $form_arr['form'][] = $item_formfield['form_id'];
                        $form_arr['field'][] = $item_formfield_id;
                        if(in_array($fieldDatas[$item_formfield_id]['var_name'],['RANGC','RANDOM_GROUP_CUSTOM','RANGCA','RANDOM_GROUP_SYSTEM'])){
                            $key++;
                            $info[$key] = [
                                'id'=>$fieldDatas[$item_formfield_id]['form_id'].'_'.$item_formfield_id.'_number',
                                'field'=>'form_'.$item_formfield_id.'_number',
                                'value'=>'',
                                'attr_name'=>$fieldDatas[$item_formfield_id]['showfiled_name'],
                                'attr_value'=>''
                            ];
                            $form_arr['key'][$item_formfield_id.'_number'] = $key;
                            $is_show_random_number_key = $item_formfield_id.'_number';
                        }
                    }
                }
                unset($fieldDatas);
                //获取患者实际填写信息
                if(!empty($form_arr['field'])){
                    //获取患者随机号信息
                    $item_set_group_arr = [];//研究分层信息
                    if(!empty($is_show_random_number_key)){
                        $item_set_group_arr = $this->LocalService()->itemRandgroup->fetchCol('group_name',['is_del'=>0,'item_id' => $item_id]);
                        $patient_info = $this->LocalService()->patient->fetchOne([
                            'where'=>['is_del'=>0,'id' => $patient_id],
                            'columns'=>['id','random_number','random_number_id']
                        ]);
                        if(!empty($patient_info)){
                            $patient_random_number = !is_null($patient_info['random_number']) && $patient_info['random_number'] != '' ? $patient_info['random_number'] : '';
                            //获取项目是否设盲
                            $item_set_blind_method = $this->LocalService()->itemInfo->getOneFieldVal('blind_method',['id'=>$item_id]);
                            if($item_set_blind_method == 0 && !empty($patient_info['random_number_id'])){
                                $random_number_info = $this->LocalService()->itemRandomdetails->fetchOne([
                                    'where'=>['is_del'=>0,'id'=>$patient_info['random_number_id']],
                                    'columns'=>['programme_id','medication_id']
                                ]);
                                //方案分组
                                if(!empty($random_number_info) && !empty($random_number_info['programme_id'])){
                                    $random_name = $this->LocalService()->itemRandom->getOneFieldVal('random_name',['is_del'=>0,'item_id'=>$item_id,'id'=>$random_number_info['programme_id']]);
                                    if($random_name != ''){
                                        $patient_random_number .= '/'.$random_name;
                                    }
                                    unset($random_name);
                                }
                                //药物分组
                                if(!empty($random_number_info) && !empty($random_number_info['medication_id'])){
                                    $medication_name = $this->LocalService()->itemMedication->getOneFieldVal('medication_name',['is_del'=>0,'item_id'=>$item_id,'id'=>$random_number_info['medication_id']]);
                                    if($medication_name != ''){
                                        $patient_random_number .= '('.$medication_name.')';
                                    }
                                    unset($medication_name);
                                }
                                unset($random_number_info);
                            }
                            $info[$form_arr['key'][$is_show_random_number_key]]['value'] = $patient_random_number != '' ? $patient_random_number : '';
                            $info[$form_arr['key'][$is_show_random_number_key]]['attr_value'] = $patient_random_number != '' ? $patient_random_number : '';
                            unset($patient_random_number);
                            unset($item_set_blind_method);
                        }
                        unset($patient_info);
                    }
                    //获取表单内容选项信息
                    $field_select_datas = $select_field_arr = [];
                    $patientFormContents = $this->LocalService()->patientFormContent->fetchAll(['where'=> [
                        'is_del' => 0,
                        'patient_id' => $patient_id,
                        'form_id' => StringHelper::toArray($form_arr['form']),
                    ],'columns'=>['form_id','data']]);
                    $selectDatas = $this->LocalService()->itemFormField->fetchDataByKey([
                        'is_del' => 0,
                        'item_id' => $item_id,
                        'parent' => StringHelper::toArray($form_arr['field']),
                    ],['id','parent','name'],'parent',1);
                    if(!empty($selectDatas)){
                        $select_field_arr = array_values(array_keys($selectDatas));
                        $selectValueDatas = $this->LocalService()->itemFormFieldRadio->fetchDataByKey([
                            'form_id' => StringHelper::toArray($form_arr['form']),
                        ],['value','field_id'],'field_id',0);
                        foreach($selectDatas as $selectParent=>$selectData){
                            foreach($selectData as $select){
                                $select_id = $select['id'];
                                if(isset($selectValueDatas[$select_id]) && !empty($selectValueDatas[$select_id])){
                                    $select_value = $selectValueDatas[$select_id]['value'];
                                    $field_select_datas[$selectParent][$select_value] = $select['name'];
                                    unset($select_value);
                                    unset($selectValueDatas[$select_id]);
                                }
                            }
                            unset($selectDatas[$selectParent]);
                        }
                        unset($selectValueDatas);
                    }
                    unset($selectDatas);
                    if(!empty($patientFormContents)){
                        //研究分层表单内容ID
                        $randomgroup_key = !empty($is_show_random_number_key) ? explode('_',$is_show_random_number_key)[0] : '';
                        foreach($patientFormContents as $patientFormContentKey=>$patientFormContent){
                            $patientFormContent_data = json_decode($patientFormContent['data'],true);
                            foreach($patientFormContent_data as $patientFormContent_key=>$patientFormContent_value){
                                if(in_array($patientFormContent_key,$form_arr['field']) && isset($form_arr['key'][$patientFormContent_key])){
                                    $info_key = $form_arr['key'][$patientFormContent_key];
                                    if($randomgroup_key == $patientFormContent_key){
                                        $patient_formfield_value = $patientFormContent_value != '' && isset($item_set_group_arr[$patientFormContent_value]) && $item_set_group_arr[$patientFormContent_value] != '' ? $item_set_group_arr[$patientFormContent_value] : '';
                                        $info[$info_key]['value'] = $patient_formfield_value != '' ? $patient_formfield_value : '';
                                        $info[$info_key]['attr_value'] = $patient_formfield_value != '' ? $patient_formfield_value : '';
                                        unset($patient_formfield_value);
                                    }else {
                                        if (in_array($patientFormContent_key, $select_field_arr)) {
                                            $patientFormContent_value_arr = [];
                                            if (!empty($patientFormContent_value)) {
                                                $patientFormContent_value_arr = is_array($patientFormContent_value) ? $patientFormContent_value : [$patientFormContent_value];
                                            }
                                            $patientFormContent_value_info = [];
                                            if (!empty($patientFormContent_value_arr)) {
                                                foreach ($patientFormContent_value_arr as $patientFormContentValue) {
                                                    if (isset($field_select_datas[$patientFormContent_key]) && isset($field_select_datas[$patientFormContent_key][$patientFormContentValue]) && !empty($field_select_datas[$patientFormContent_key][$patientFormContentValue])) {
                                                        $patientFormContent_value_info[] = $field_select_datas[$patientFormContent_key][$patientFormContentValue];
                                                    }
                                                }
                                            }
                                            $info[$info_key]['value'] = !empty($patientFormContent_value_info) ? implode('、', $patientFormContent_value_info) : '';
                                            $info[$info_key]['attr_value'] = !empty($patientFormContent_value_info) ? implode('、', $patientFormContent_value_info) : '';
                                            unset($patientFormContent_value_arr);
                                            unset($patientFormContent_value_info);
                                        } else {
                                            $info[$info_key]['value'] = $patientFormContent_value != '' ? $patientFormContent_value : '';
                                            $info[$info_key]['attr_value'] = $patientFormContent_value != '' ? $patientFormContent_value : '';
                                        }
                                    }
                                    unset($info_key);
                                }
                            }
                            unset($patientFormContents[$patientFormContentKey]);
                            unset($patientFormContent_data);
                        }
                        unset($randomgroup_key);
                    }
                    unset($item_set_group_arr);
                    unset($patientFormContents);
                    unset($field_select_datas);
                    unset($select_field_arr);
                }
                unset($is_show_random_number_key);
                unset($form_arr);
            }
        }
        $info = array_values($info);
        return $info;
    }

    /**
     * Notes: 获取副项目设置的受试者表单属性及受试者明细信息
     * User: lltyy
     * DateTime: 2025/6/30 15:22
     *
     * @param array $arr
     * @return array
     */
    public function fetchAllPatientData($arr=[]){
        $item_id = isset($arr['item_id']) && !empty($arr['item_id']) ? $arr['item_id'] : 0;
        $patient_id = isset($arr['patient_id']) && !empty($arr['patient_id']) ? $arr['patient_id'] : [];
        $info = [];
        $formField = [];
        if(!empty($item_id)){
            $item_formfield_arr = $this->fetchAll(['where'=> [
                'is_del' => 0,
                'item_id' => $item_id,
            ],'columns'=>['form_id','field_id'],'order'=>['info_order']]);
            if(!empty($item_formfield_arr)){
                $form_arr = [
                    'form'=>[],
                    'field'=>[]
                ];
                $form_field_arr = array_values(array_column($item_formfield_arr,'field_id'));
                $fieldDatas = $this->LocalService()->itemFormField->fetchDataByKey([
                    'is_del' => 0,
                    new NotIn('type', [13, 14, 19]),
                    'item_id' => $item_id,
                    'id' => StringHelper::toArray($form_field_arr)
                ],['id','form_id','name','var_name','showfiled_name'],'id',0);
                unset($form_field_arr);
                $is_show_random_number_key = '';//随机号键值
                foreach($item_formfield_arr as $form_field_key=>$item_formfield){
                    $item_formfield_id = $item_formfield['field_id'];
                    if(isset($fieldDatas[$item_formfield_id]) && !empty($fieldDatas[$item_formfield_id])){
                        $formField[] = [
                            'prop'=>$fieldDatas[$item_formfield_id]['form_id'].'_'.$item_formfield_id,
                            'label'=>$fieldDatas[$item_formfield_id]['name'],
                        ];
                        $form_arr['form'][] = $item_formfield['form_id'];
                        $form_arr['field'][] = $item_formfield_id;
                        if(in_array($fieldDatas[$item_formfield_id]['var_name'],['RANGC','RANDOM_GROUP_CUSTOM','RANGCA','RANDOM_GROUP_SYSTEM'])){
                            $formField[] = [
                                'prop'=>$fieldDatas[$item_formfield_id]['form_id'].'_'.$item_formfield_id.'_number',
                                'label'=>$fieldDatas[$item_formfield_id]['showfiled_name'],
                            ];
                            $is_show_random_number_key = $fieldDatas[$item_formfield_id]['form_id'].'_'.$item_formfield_id.'_number';
                        }

                    }
                }
                unset($fieldDatas);
                //获取患者实际填写信息
                if(!empty($form_arr['field']) && !empty($patient_id)){
                    //获取患者随机号信息
                    $item_set_group_arr = [];//研究分层信息
                    if(!empty($is_show_random_number_key)){
                        $item_set_group_arr = $this->LocalService()->itemRandgroup->fetchCol('group_name',['is_del'=>0,'item_id' => $item_id]);
                        $patient_random_arr = $this->LocalService()->patient->fetchDataByKey(['is_del'=>0,'id' => $patient_id],['id','random_number','random_number_id'],['id'],['id'=>0]);
                        $patient_random_arr = isset($patient_random_arr['id']) && !empty($patient_random_arr['id']) ? $patient_random_arr['id'] : [];
                        if(!empty($patient_random_arr)){
                            //获取该项目下随机号设置的药物分组及方案分组信息
                            $item_set_number_arr = [];
                            //获取项目是否设盲
                            $item_set_blind_method = $this->LocalService()->itemInfo->getOneFieldVal('blind_method',['id'=>$item_id]);
                            if($item_set_blind_method == 0){
                                //项目设置的方案分组名称
                                $item_set_random = $this->LocalService()->itemRandom->fetchCol('random_name',['is_del'=>0,'item_id'=>$item_id]);
                                //项目设置的药物分组名称
                                $item_set_medication = $this->LocalService()->itemMedication->fetchCol('medication_name',['is_del'=>0,'item_id'=>$item_id]);
                                $item_set_number_arr = $this->LocalService()->itemRandomdetails->fetchAll([
                                    'where'=>['is_del'=>0,'item_id'=>$item_id,'is_use'=>1],
                                    'columns'=>['id','programme_id','medication_id']
                                ]);
                                if(!empty($item_set_number_arr)){
                                    foreach($item_set_number_arr as &$item_set_number){
                                        $item_set_number['random_name'] = isset($item_set_random[$item_set_number['programme_id']]) && $item_set_random[$item_set_number['programme_id']] != '' ? $item_set_random[$item_set_number['programme_id']] : '';
                                        $item_set_number['medication_name'] = isset($item_set_medication[$item_set_number['medication_id']]) && $item_set_medication[$item_set_number['medication_id']] != '' ? $item_set_medication[$item_set_number['medication_id']] : '';
                                        unset($item_set_number['programme_id']);
                                        unset($item_set_number['medication_id']);
                                    }
                                    $item_set_number_arr = ArrayHelper::index($item_set_number_arr,'id');
                                }
                                unset($item_set_random);
                                unset($item_set_medication);
                            }
                            foreach($patient_random_arr as $patient_random_key=>&$patient_random){
                                $patient_random['random_number'] = !is_null($patient_random['random_number']) && $patient_random['random_number'] != '' ? $patient_random['random_number'] : '';
                                if($item_set_blind_method == 0 && !empty($patient_random['random_number_id']) && isset($item_set_number_arr[$patient_random['random_number_id']]) && !empty($item_set_number_arr[$patient_random['random_number_id']])){
                                    //方案分组信息
                                    if($item_set_number_arr[$patient_random['random_number_id']]['random_name'] != ''){
                                        $patient_random['random_number'] .= '/'.$item_set_number_arr[$patient_random['random_number_id']]['random_name'];
                                    }
                                    //药物分组信息
                                    if($item_set_number_arr[$patient_random['random_number_id']]['medication_name'] != ''){
                                        $patient_random['random_number'] .= '('.$item_set_number_arr[$patient_random['random_number_id']]['medication_name'].')';
                                    }
                                }
                                $info[$patient_random_key][$is_show_random_number_key] = $patient_random['random_number'];
                                unset($patient_random_arr[$patient_random_key]);
                            }
                            unset($item_set_blind_method);
                            unset($item_set_number_arr);
                        }

                        unset($patient_random_arr);
                    }
                    //获取表单内容选项信息
                    $field_select_datas = $select_field_arr = [];
                    $patientFormContents = $this->LocalService()->patientFormContent->fetchAll(['where'=> [
                        'is_del' => 0,
                        'patient_id' => $patient_id,
                        'form_id' => StringHelper::toArray($form_arr['form']),
                    ],'columns'=>['form_id','data','patient_id']]);
                    $selectDatas = $this->LocalService()->itemFormField->fetchDataByKey([
                        'is_del' => 0,
                        'item_id' => $item_id,
                        'parent' => StringHelper::toArray($form_arr['field']),
                    ],['id','parent','name'],'parent',1);
                    if(!empty($selectDatas)){
                        $select_field_arr = array_values(array_keys($selectDatas));
                        $selectValueDatas = $this->LocalService()->itemFormFieldRadio->fetchDataByKey([
                            'form_id' => StringHelper::toArray($form_arr['form']),
                        ],['value','field_id'],'field_id',0);
                        foreach($selectDatas as $selectParent=>$selectData){
                            foreach($selectData as $select){
                                $select_id = $select['id'];
                                if(isset($selectValueDatas[$select_id]) && !empty($selectValueDatas[$select_id])){
                                    $select_value = $selectValueDatas[$select_id]['value'];
                                    $field_select_datas[$selectParent][$select_value] = $select['name'];
                                    unset($select_value);
                                    unset($selectValueDatas[$select_id]);
                                }
                            }
                            unset($selectDatas[$selectParent]);
                        }
                        unset($selectValueDatas);
                    }
                    unset($selectDatas);
                    if(!empty($patientFormContents)){
                        //研究分层表单内容ID
                        $randomgroup_key = !empty($is_show_random_number_key) ? explode('_',$is_show_random_number_key)[1] : '';
                        foreach($patientFormContents as $patientFormContentKey=>$patientFormContent){
                            $patientFormContent_data = json_decode($patientFormContent['data'],true);
                            if(!empty($patientFormContent_data)){
                                foreach($patientFormContent_data as $patientFormContent_key=>$patientFormContent_value){
                                    if(in_array($patientFormContent_key,$form_arr['field'])){
                                        $patient_formfield_value = $patientFormContent_value != '' ? $patientFormContent_value : '';
                                        if($randomgroup_key == $patientFormContent_key){
                                            $patient_formfield_value = $patient_formfield_value != '' && isset($item_set_group_arr[$patient_formfield_value]) && $item_set_group_arr[$patient_formfield_value] != '' ? $item_set_group_arr[$patient_formfield_value] : '';
                                        }else{
                                            if(in_array($patientFormContent_key,$select_field_arr)){
                                                $patientFormContent_value_info = [];
                                                $patientFormContent_value_arr = is_array($patientFormContent_value) ? $patientFormContent_value : [$patientFormContent_value];
                                                if(!empty($patientFormContent_value_arr)){
                                                    foreach($patientFormContent_value_arr as $patientFormContentValue){
                                                        if(isset($field_select_datas[$patientFormContent_key]) && isset($field_select_datas[$patientFormContent_key][$patientFormContentValue]) && !empty($field_select_datas[$patientFormContent_key][$patientFormContentValue])){
                                                            $patientFormContent_value_info[] = $field_select_datas[$patientFormContent_key][$patientFormContentValue];
                                                        }
                                                    }
                                                }
                                                unset($patientFormContent_value_arr);
                                                $patient_formfield_value = !empty($patientFormContent_value_info) ? implode('、',$patientFormContent_value_info) : '';
                                                unset($patientFormContent_value_info);
                                            }
                                        }
                                        $info[$patientFormContent['patient_id']][$patientFormContent['form_id'].'_'.$patientFormContent_key] = $patient_formfield_value;
                                        unset($patient_formfield_value);
                                    }
                                    unset($patientFormContent_data[$patientFormContent_key]);
                                }
                            }
                            unset($patientFormContent_data);
                            unset($patientFormContents[$patientFormContentKey]);
                        }
                        unset($randomgroup_key);
                    }
                    unset($patientFormContents);
                    unset($field_select_datas);
                    unset($select_field_arr);
                    unset($item_set_group_arr);
                }
                unset($is_show_random_number_key);
                unset($is_show_group_key);
                unset($form_arr);
            }
            unset($item_formfield_arr);
        }
        return ['setFormField'=>$formField,'patientFormField'=>$info];
    }
}