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

namespace Application\Service\DB\Item;

use Application\Service\Extension\Helper\StringHelper;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Json\Json;

class Patientattrs extends \Application\Service\DB\AbstractDb {
    public $tel = 'tel';
    public $randGroupId = 'randgroup_id';
    public $name = 'name';
    public $sex = 'sex';
    public $ns = 'ns';
    public $signatoryUserId = 'signatory_user_id';
    public Const PRIVACY_PATIENTATTR_CACHE_NAMESPACE = 'PrivacyPatientAttrs';
    public CONST CUSTOM_ATTR_MAP_PATIENT_FIELD = [
        'name' => 'patient_name',
        'ns' => 'patient_name_easy',
        'sex' => 'patient_sex',
        'tel' => 'patient_tel',
        'number' => 'patient_number',
        'randgroup_id' => 'randgroup_id',
    ];

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

    //默认添加拓展属性
    public function itemDefaultPatientattrInsert($item_id){
        $whereDPArr['where'] = [
            'is_del' => 0,
            'is_default' => 1,
        ];
        $patientattrData = $this->LocalService()->dictionaryPatientattr->fetchAll($whereDPArr);
        if (!empty($patientattrData)) {
            $maxOrder = 10;
            foreach ($patientattrData as $k => $v) {
                $arr['item_id'] = $item_id;
                $arr['dictionary_patientattr_id'] = $v['id'];
                $arr['attr_name'] = $v['attr_name'];
                $arr['attr_field'] = $v['attr_filed'];
                $arr['attr_type'] = $v['attr_type'];
                $arr['is_required'] = $v['is_required'];
                $arr['attr_type_id'] = $v['attr_type_id'];
                if (!empty($v['content'])) {
                    $arr['content'] = $v['content'];
                }
                $arr['attr_order'] = $maxOrder;
                $maxOrder += 10;
                $result = $this->LocalService()->patientattrs->save($arr);
            }
        }
        return true;
    }

	public function patientattrInsert($oldItemId,$newItemId){
        $whereOld['where'] = [
            'is_del' => 0,
            'item_id' => $oldItemId,
        ];
        $whereNew['where'] = [
            'is_del' => 0,
            'item_id' => $newItemId,
        ];

        $patientattrData = $this->LocalService()->patientattrs->fetchAll($whereOld);
        if (!empty($patientattrData)){
            foreach ($patientattrData as $k => $v) {
                unset($v['id']);
                $v['item_id'] = $newItemId;
                $result = $this->LocalService()->patientattrs->save($v);
            }
        }


    }
    public function patientattrItemTel($newItemId,$status = 0){
        $wherePatient['where'] = [
            'is_del' => 0,
            'item_id' => $newItemId,
            new Operator('patient_tel', Operator::OP_NE, 0),
        ];
        $patientTelData = $this->LocalService()->patient->fetchCol('patient_tel',$wherePatient['where']);
        if (!empty($patientTelData)){
            $whereUser['where'] = [
                'is_del' => 0,
                'mobile' => $patientTelData,
            ];
            $whereUser['columns'] = ['id','realname','patient_status'];//,'group_type'
            $userData = $this->LocalService()->adminUser->fetchAll($whereUser);

            if (!empty($userData)){
                if (empty($status)){
                    //项目登录禁用
                    $upData['patient_status'] = 1;
                }else{
                    //项目登录启用
                    $upData['patient_status'] = 0;
                }
                $this->LocalService()->adminUser->update($upData,[
                    'id' => array_column($userData,'id')
                ]);
            }
        }

        //is_applet
        $whereDPArr['where'] = [
            'is_del' => 0,
            'attr_filed' => $this->tel,
        ];
        $patientattrInfo = $this->LocalService()->dictionaryPatientattr->fetchOne($whereDPArr);
        if(empty($patientattrInfo)) return false;
        $whereNew['where'] = [
            'is_del' => 0,
            'item_id' => $newItemId,
            'attr_field' => $this->tel,
        ];
        $maxOrder = $this->LocalService()->patientattrs->getMaxOrder('attr_order', $whereNew['where']);
        $patientattrData = $this->LocalService()->patientattrs->fetchAll($whereNew);
        if(!empty($patientattrData)) return true;
        if (!empty($patientattrInfo)){
            $arr['item_id'] = $newItemId;
            $arr['attr_order'] = $maxOrder;
            $arr['attr_name'] = $patientattrInfo['attr_name'];
            $arr['attr_field'] = $patientattrInfo['attr_filed'];
            $arr['attr_type'] = $patientattrInfo['attr_type'];
            $arr['is_required'] = $patientattrInfo['is_required'];
            $arr['dictionary_patientattr_id'] = $patientattrInfo['id'];
            !empty($patientattrInfo['content']) &&$arr['content'] = $patientattrInfo['content'];
            $result = $this->LocalService()->patientattrs->save($arr);
            if(!empty($result)) return true;
        }

    }
    
    public function dictionaryPatientattrUpdateType(){
        $dictionaryFormtypeData = $this->LocalService()->dictionaryFormtype->fetchCol('type_code','is_del = 0');
        if (!empty($dictionaryFormtypeData)){
            $patientattrData = $this->LocalService()->dictionaryPatientattr->fetchAll(['where'=>'is_del=0']);

            if (!empty($patientattrData)){
                $attr_type_id_Arr = array_column($patientattrData,'attr_type_id');
                if (count($attr_type_id_Arr) == count(array_filter($attr_type_id_Arr))){
                    return true;
                }
                $newDictionaryFormtypeData = array_flip($dictionaryFormtypeData);
                foreach ($patientattrData as $patientattrDataKey => $patientattrDataValue) {
                    if ($patientattrDataValue['attr_filed'] == $this->randGroupId || $patientattrDataValue['attr_filed'] == $this->signatoryUserId) {
                        $patientattrDataValue['attr_type'] = 7;
                    }
                    if (!empty($patientattrDataValue['attr_type_id'])) {
                        continue;
                    }
                    $codeType = $this->fieldType($patientattrDataValue['attr_type']);
                    $attr_type_id = isset($newDictionaryFormtypeData[$codeType])?$newDictionaryFormtypeData[$codeType]:1;
                    $up['id'] = $patientattrDataValue['id'];
                    $up['attr_type_id'] = $attr_type_id;
                    $up['attr_type'] = $patientattrDataValue['attr_type'];
                    $id = $this->LocalService()->dictionaryPatientattr->save($up);
                }
            }
        }
        return true;
    }

    public function patientattrUpdateType(){
        $dictionaryFormtypeData = $this->LocalService()->dictionaryFormtype->fetchCol('type_code','is_del = 0');
        if (!empty($dictionaryFormtypeData)){
            $patientattrData = $this->LocalService()->patientattrs->fetchAll(['where'=>'is_del=0']);

            if (!empty($patientattrData)){
                $attr_type_id_Arr = array_column($patientattrData,'attr_type_id');
                if (count($attr_type_id_Arr) == count(array_filter($attr_type_id_Arr))){
                    return true;
                }
                $newDictionaryFormtypeData = array_flip($dictionaryFormtypeData);
                foreach ($patientattrData as $patientattrDataKey => $patientattrDataValue) {
                    if ($patientattrDataValue['attr_field'] == $this->randGroupId || $patientattrDataValue['attr_field'] == $this->signatoryUserId) {
                        $patientattrDataValue['attr_type'] = 7;
                    }
                    if (!empty($patientattrDataValue['attr_type_id'])) {
                        continue;
                    }
                    $codeType = $this->fieldType($patientattrDataValue['attr_type']);
                    $attr_type_id = isset($newDictionaryFormtypeData[$codeType])?$newDictionaryFormtypeData[$codeType]:1;
                    $up['id'] = $patientattrDataValue['id'];
                    $up['attr_type_id'] = $attr_type_id;
                    $up['attr_type'] = $patientattrDataValue['attr_type'];
                    $id = $this->LocalService()->patientattrs->save($up);
                }
            }
        }
        return true;
    }

    public function fieldType($type){
        $fieldTypeData = [
            1=>'text',
            2=>['integer','decimal_one','decimal_two','decimal_three'],
            3=>'radio',
            4=>'checkbox',
            5=>'date_ymd',
            6=>'date_uk',
            7=>'select',
            8=>'upload_img',
            9=>'upload_file',
            10=>'textarea',
            11=>'date_ymd_hi',
            12=>'date_ymd_his',

        ];
        return isset($fieldTypeData[$type])?$fieldTypeData[$type]:'text';
    }

    //更新受试者属性
    public function patientattrUpdatePatient($itemId,$patientattrData,$newContent){
        $whereNew['where'] = [
            'is_del' => 0,
            'attr_type' => [3, 4, 7],
            'item_id' => $itemId,
        ];
        $patientattrData = $this->LocalService()->patientattrs->fetchAll($whereNew);

        $newPatientattrData = [];
        if (!empty($patientattrData)){
            foreach ($patientattrData as $patientattrDataKey=>$patientattrDataValue){
                if (!empty($patientattrDataValue['content']) && in_array($patientattrDataValue['attr_type'],[3,4,7])){
                    $patientattrDataValue['content'] = ['source_ward12'=>'source_ward1','source_outpatients12'=>'source_outpatients1','source_ward3'=>'source_other'];
                    $patientattrDataValue['attr_field'] = 'number1';
                    $newPatientattrData[$patientattrDataValue['id']] = $patientattrDataValue;
                }

            }
        }

        $wherePatient['where'] = [
            'is_del' => 0,
            'item_id' => $itemId,
        ];
        $wherePatient['columns'] = ['id','patient_content'];

        $patientData = $this->LocalService()->patient->fetchAll($wherePatient);
        if (!empty($patientData)){
            foreach ($patientData as $patientDataKey=>&$patientDataValue) {
                if (!empty($patientDataValue['patient_content'])){
                    $patientContent = json_decode($patientDataValue['patient_content'],1);
                    if(is_array($patientContent) && !empty($patientContent)){
                        foreach ($patientContent as $patientContentKey=>&$patientContentValue) {
                            if (isset($newPatientattrData[$patientContentValue['id']])){
                                $patientContentValue['field'] = $newPatientattrData[$patientContentValue['id']]['attr_field'];
                                if ($newPatientattrData[$patientContentValue['id']]['attr_type'] == 3 || $newPatientattrData[$patientContentValue['id']]['attr_type'] == 7 ){
                                    if (($newPatientattrData[$patientContentValue['id']]['attr_field'] == $this->randGroupId) || ($newPatientattrData[$patientContentValue['id']]['attr_field'] == $this->signatory_user_id)){
                                        continue;
                                    }
                                    if (!empty($patientContentValue['value']) && isset($newPatientattrData[$patientContentValue['id']]['content'][$patientContentValue['value']])){
                                        $patientContentValue['value'] = $newPatientattrData[$patientContentValue['id']]['content'][$patientContentValue['value']];
                                    }
                                }else if($newPatientattrData[$patientContentValue['id']]['attr_type'] == 4){
                                    if (!empty($patientContentValue['value'])){
                                        foreach ($patientContentValue['value'] as $checkKey =>$checkValue) {
                                            if (!empty($checkValue)){
                                                $newCheckValue = trim($checkValue);
                                                if (isset($newPatientattrData[$patientContentValue['id']]['content'][$newCheckValue])){
                                                    $patientContentValue['value'][$checkKey] = $newPatientattrData[$patientContentValue['id']]['content'][$newCheckValue];
                                                }
                                            }
                                        }
                                    }
                                }

                            }
                        }

                        $patientDataValue['patient_content'] = json_encode($patientContent);
                        $patientData1 = $this->LocalService()->patient->save($patientDataValue);
                    }
                }
            }
        }
        return true;
    }

    /*
    *
    * */
    function oldItemPatientattrInsert($item_id = 83){
        //检查点
        $iteminfoId= $this->LocalService()->itemInfo->getOneFieldVal('id',[
            'is_del' => 0,
            'old_id' => $item_id,
        ]);
        if(empty($iteminfoId)) return false;
        $patientattrData = $this->LocalService()->patientattrs->dbData('oa_item_patientattr',[
            'is_del' => 0,
            'item_id' => explode(',', $item_id),
        ]);
        $patientSelectData = [];
        $patientValueData = [];
        if(!empty($patientattrData)){
            $patientattrIdArr = array_column($patientattrData,'id');
            $patientSelectData = $this->LocalService()->patientattrs->dbData('oa_item_patientattrselect',[
                'is_del' => 0,
                'attr_id' => $patientattrIdArr,
                'item_id' => $item_id,
            ]);
            $patientValueData = $this->LocalService()->patientattrs->dbData('oa_item_patientattrvalue',[
                'is_del' => 0,
                'attr_id' => $patientattrIdArr,
                'item_id' => $item_id,
            ]);


            foreach ($patientattrData as $k=>&$v){
                $selectArr = [];
                $v['item_id'] = $iteminfoId;
                $v['item_id_old'] = $item_id;
                if (!empty($patientSelectData)){
                    foreach ($patientSelectData as $patientSelectDataKey=>$patientSelectDataValue) {
                        if ($patientSelectDataValue['attr_id'] == $v['id']){
                            $selectArr[] = [
                                'id'=>$patientSelectDataValue['select_order'],
                                'select_name'=>$patientSelectDataValue['select_name'],
                                'select_order'=>$patientSelectDataValue['select_order'],
                                'select_variable'=>$patientSelectDataValue['var_name'],
                            ];
                        }
                    }
                }
                if(!empty($selectArr)){
                    $v['content'] = json_encode($selectArr);
                }

                $v['id_old'] = $v['id'];
                unset($v['id']);
                $patientattrResult = $this->LocalService()->patientattrs->save($v);

            }
            $att = ['研究分层'=>$this->randGroupId,'受试者姓名'=>$this->name,'性别'=>$this->sex ];
            foreach ( $att as $attKey=>$attValue) {
                $wherePatientattrs['where'] = [
                    'is_del' => 0,
                    'item_id_old' => $item_id,
                    'attr_field' => $attValue,
                ];
                $wherePatientattrs['columns'] = ['id','attr_field','attr_name'];
                $patientattrInfo = $this->LocalService()->patientattrs->fetchOne($wherePatientattrs);
                if (empty($patientattrInfo)) {
                    //排序
                    $wherePatientattrsMax = [
                        'is_del' => 0,
                        'item_id_old' => $item_id,
                    ];
                    $maxOrder = $this->LocalService()->patientattrs->getMaxOrder('attr_order', $wherePatientattrsMax);
                    $newAttr = [
                        'item_id'=>$iteminfoId,
                        'attr_name'=>$attKey,
                        'attr_field'=>$attValue,
                        'item_id_old'=>$item_id,
                        'attr_order'=>$maxOrder,
                    ];
                    if ($attKey == '研究分层'){
                        $newAttr['attr_type'] = 4;

                    }
                    if ($attKey == '受试者姓名'){
                        $newAttr['attr_type'] = 1;
                    }
                    if ($attKey == '性别'){
                        $newAttr['attr_type'] = 3;
                        $newAttr['content']  = json_encode(
                            [
                                [
                                    'id'=>10,
                                    'select_name'=>'男',
                                    'select_order'=>10,
                                    'select_variable'=>0,
                                ],
                                [
                                    'id'=>10,
                                    'select_name'=>'女',
                                    'select_order'=>10,
                                    'select_variable'=>1,
                                ]
                            ]
                        );
                    }
                    $newPatientattrId = $this->LocalService()->patientattrs->save($newAttr);

                }
            }

        }

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

    }

    public function oldPatientInsert($item_id=83){
        $iteminfoId= $this->LocalService()->itemInfo->getOneFieldVal('id',[
            'is_del' => 0,
            'old_id' => $item_id,
        ]);
        $iteminfoBigId= $this->LocalService()->itemInfo->getOneFieldVal('fid',[
            'is_del' => 0,
            'id' => $iteminfoId,
        ]);
        if(empty($iteminfoId)) return false;
        $patientData = $this->LocalService()->patientattrs->dbData('oa_item_patient',[
            'is_del' => 0,
            'item_id' => explode(',', $item_id),
        ]);
        $whereItemSignatory['where'] = [
            'is_del' => 0,
            'item_id' => $iteminfoBigId,
        ];

        $whereItemSignatory['columns'] = ['id','old_id'];
        $itemSignatoryIdData = $this->LocalService()->itemSignatory->fetchAll($whereItemSignatory);

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

        if (!empty($patientData)){

            $patientIdArr = array_column($patientData,'id');
            $patientValueData = $this->LocalService()->patientattrs->dbData('oa_item_patientattrvalue',[
                'is_del' => 0,
                'patient_id' => $patientIdArr,
                'item_id' => $item_id,
            ]);
            $patientattrselectData = $this->LocalService()->patientattrs->dbData('oa_item_patientattrselect',[
                'is_del' => 0,
                'item_id' => $item_id,
            ]);
            $patientattrData = $this->LocalService()->patientattrs->dbData('oa_item_patientattr',[
                'is_del' => 0,
                'item_id' => $item_id,
            ]);

            //老的属性总表
            $newPatientattrssDatas = [];
            foreach($patientattrData as $k=>$v)
            {
                $newPatientattrssDatas[$v['id']] = $v;
            }

            //老的下拉
            $patientattrselectHandle = [];
            if (!empty($patientattrselectData)){
                foreach ($patientattrselectData as $patientattrselectDataKey=>$patientattrselectDataValue) {
                    $patientattrselectHandle[$patientattrselectDataValue['attr_id']][$patientattrselectDataValue['id']] = $patientattrselectDataValue;
                }
            }

            //新的属性
            $whereNewPatientattrs['where'] = [
                'is_del' => 0,
                'item_id_old' => $item_id,
            ];
            $whereNewPatientattrs['columns'] = ['id','attr_field','id_old','attr_type'];
            $newPatientattrsData = $this->LocalService()->patientattrs->fetchAll($whereNewPatientattrs);
            $newPatientattrsDatas = [];
            if (!empty($newPatientattrsData)){
                foreach($newPatientattrsData as $k=>$v)
                {
                    $newPatientattrsDatas[$v['id_old'].'-'.$v['attr_field']] = $v;//.'-'.$v['attr_field']
                }

            }
            foreach ($patientData as $patientDataKey=>&$patientDataValue) {
                $patientContent = [];
                if (!empty($patientValueData)){
                    foreach ($patientValueData as $patientValueDataKey=>$patientValueDataValue){
                        $patientValueDataValue['attr_type'] =  $newPatientattrssDatas[$patientValueDataValue['attr_id']]['attr_type'];


                        if ($patientValueDataValue['patient_id'] == $patientDataValue['id']){

                            if (!empty($newPatientattrsDatas)){

                                $patientContent[$patientValueDataKey]['id'] = $newPatientattrsDatas[$patientValueDataValue['attr_id'].'-'.$patientValueDataValue['attr_field']]['id'] ;//.'-'.$patientValueDataValue['attr_field']
                                $patientContent[$patientValueDataKey]['field'] = $patientValueDataValue['attr_field'];
                                $newVaule = '';
                                if (isset($patientattrselectHandle[$patientValueDataValue['attr_id']][$patientValueDataValue['attr_value']]['var_name'])){
                                    $newVaule = $patientattrselectHandle[$patientValueDataValue['attr_id']][$patientValueDataValue['attr_value']]['var_name'];
                                }
                                if (($patientValueDataValue['attr_type'] == 3) || ($patientValueDataValue['attr_type'] == 4)){
                                    $patientContent[$patientValueDataKey]['value'] = $newVaule;
                                }else{
                                    $patientContent[$patientValueDataKey]['value'] = $patientValueDataValue['attr_value'];
                                }

                            }

                            //手机号
                            if ($patientValueDataValue['attr_field'] == $this->tel){
                                $patientDataValue['patient_tel'] = $patientValueDataValue['attr_value'];
                            }
                            //名称缩写
                            if ($patientValueDataValue['attr_field'] == $this->ns){
                                $patientDataValue['patient_name_easy'] = $patientValueDataValue['attr_value'];
                            }
                        }
                    }
                }

                if(!empty($patientContent)){
                    if (!empty($patientDataValue['random_pre_group'])){
                        $group['id'] = $newPatientattrsDatas['0-'.$this->randGroupId]['id'] ;
                        $group['field'] = $this->randGroupId;
                        $group['value'] =$patientDataValue['random_pre_group'];
                        array_push($patientContent,$group);

                    }
                    if (!empty($patientDataValue['patient_name'])){
                        $name['id'] = $newPatientattrsDatas['0-'.$this->name]['id'] ;
                        $name['field'] = $this->name;
                        $name['value'] =$patientDataValue['patient_name'];
                        array_push($patientContent,$name);
                    }
                    if (!empty($patientDataValue['patient_sex'])){
                        $sex['id'] = $newPatientattrsDatas['0-'.$this->sex]['id'] ;
                        $sex['field'] = $this->sex;
                        $sex['value'] =$patientDataValue['patient_sex'];
                        array_push($patientContent,$sex);
                    }
                    $patientContent = array_merge($patientContent);
                    $patientDataValue['patient_content'] = json_encode($patientContent);
                }
                $patientDataValue['item_id'] = $iteminfoId;
                $patientDataValue['item_id_old'] = $item_id;
                $patientDataValue['itemsig_id_old'] = $patientDataValue['itemsig_id'];
                $patientDataValue['itemsig_id'] = isset($signtoryDatas[ $patientDataValue['itemsig_id']]['id'])?$signtoryDatas[ $patientDataValue['itemsig_id']]['id']:0;

                $patientDataValue['random_number_id_old'] = $patientDataValue['random_number_id'];
                $patientDataValue['random_id_old'] = $patientDataValue['random_id'];

                if(!empty($patientDataValue['random_pre_group'])){
                    $patientDataValue['randgroup_id_old'] = $patientDataValue['randgroup_id'] = $patientDataValue['random_pre_group'];
                }
                if(empty($patientDataValue['subscription_status'])) unset($patientDataValue['subscription_status']);
                unset($patientDataValue['patient_name_new']);
                unset($patientDataValue['batch']);
                unset($patientDataValue['random_pre_group']);

                $patientResult = $this->LocalService()->patient->insert($patientDataValue);

            }
            $this->oldItemPatientStatusUpdate($item_id);
        }
        echo '<pre>';print_r($patientResult);die;

    }

    public function oldItemPatientStatusUpdate($item_id=83){
        $whereNewPatient['where'] = [
            'is_del' => 0,
            'item_id_old' => $item_id,
        ];
        $whereNewPatient['columns'] = ['id','itemsig_id','item_id','patient_status','itemsig_id_old'];
        $newPatientData = $this->LocalService()->patient->fetchAll($whereNewPatient);

        if (!empty($newPatientData)){
            foreach ($newPatientData as $newPatientDataKey=>$newPatientDataValue) {
                $where = [
                    'is_del' => 0,
                    'item_id' => $item_id,
                    'itemsig_id' => $newPatientDataValue['itemsig_id_old'],
                    'patient_id' => $newPatientDataValue['id']
                ];
                $patientCheckTimeData = $this->LocalService()->patientattrs->dbData('oa_item_patientchecktime',$where);
                $status = 9;
                if (!empty($patientCheckTimeData)){
                    foreach ($patientCheckTimeData as $patientCheckTimeDataKey=>$patientCheckTimeDataValue) {
                        if (!is_null($patientCheckTimeDataValue['leave_type'])){
                            $status = $patientCheckTimeDataValue['leave_type'];
                            break;
                        }
                    }
                }
                $up['patient_status'] = $status;
                $up['id'] = $newPatientDataValue['id'];
                $newPatientId = $this->LocalService()->patient->save($up);
            }
        }

        echo '<pre>';print_r($newPatientId);die;

    }

    public function dbData($db,$where){
        $yikeen = new \mysqli('localhost','root','root3306',"e-yda");//mc5 //e-yda

        $yikeen->select_db('e-yda') or die('选择数据库失败：'.$yikeen->error);

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

        $patientattrSql='select * from '.$db.' where '.$where;

        $patientattrResult = $yikeen->query($patientattrSql);
        $patientattrData=[];
        if (empty($patientattrResult)) return $patientattrData;
        while($row = $patientattrResult->fetch_assoc())
        {
            $patientattrData[]=$row;
        }
        return $patientattrData;

    }


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

    public function save(array $saveData)
    {
        $result = parent::save($saveData); // TODO: Change the autogenerated stub

        $this->syncPrivacyPatientAttrs();
        return $result;
    }

    public function insert(array $insertData)
    {
       $result = parent::insert($insertData); // TODO: Change the autogenerated stub
        $this->syncPrivacyPatientAttrs();
        return $result;
    }

    public function updateField($id, $field, $value)
    {
        $result = parent::updateField($id, $field, $value); // TODO: Change the autogenerated stub
        $this->syncPrivacyPatientAttrs();
        return $result;
    }

    public function update(array $updateData, $where)
    {
        $result = parent::update($updateData, $where); // TODO: Change the autogenerated stub
        $this->syncPrivacyPatientAttrs();
        return $result;
    }

    public function upDelState($where, $upDelStatus = 1)
    {
        $result = parent::upDelState($where, $upDelStatus); // TODO: Change the autogenerated stub
        $this->syncPrivacyPatientAttrs();
        return $result;
    }

    /**
     * @note 获取项目的隐私字段
     * @param $item_id
     * @return mixed
     * @throws \Laminas\Cache\Exception\ExceptionInterface
     */
    public function getPrivacyPatientAtts($item_id) {
        $redisExtend = $this->LocalService()->redisExtend->setNamespace(self::PRIVACY_PATIENTATTR_CACHE_NAMESPACE);
        return Json::decode($redisExtend->getItem($item_id) ?: '[]', Json::TYPE_ARRAY);
    }

    public function isValidPrivacyPatientattr(string $paientattrProp, int $item_id) {
        return in_array($paientattrProp, $this->getPrivacyPatientAtts($item_id));
    }

    /**
     * @note 同步记录隐私字段
     * @return void
     */
    public function syncPrivacyPatientAttrs(){
        $redisExtend = $this->LocalService()->redisExtend->setNamespace(self::PRIVACY_PATIENTATTR_CACHE_NAMESPACE);

        // 先清空缓存
        $cursor = '0';
        $match = sprintf("%s:%s", self::PRIVACY_PATIENTATTR_CACHE_NAMESPACE, '*');
        // 使用 SCAN 命令迭代所有匹配的键
        do {
            $result = $redisExtend->getRedisInstance()->scan($cursor, $match, 100);
            // 如果有匹配的键，使用 DEL 命令删除
            if (!empty($result)) {
                $redisExtend->getRedisInstance()->del($result);
            }
        } while ($cursor != '0');

        $patientAttrList = $this->LocalService()->patientattrs->fetchAll([
            'where' => [
                'is_del' => 0,
                'is_hide' => 1
            ],
            'column' => [
                'id', 'item_id', 'attr_field'
            ]
        ]);

        $itemPrivacyPatientAttrList = [];

        if (! empty($patientAttrList)) {
            foreach ($patientAttrList as &$patientAttr) {
                $itemPrivacyPatientAttrList[$patientAttr['item_id']][$patientAttr['id']] = $patientAttr['attr_field'];
            }

            foreach ($itemPrivacyPatientAttrList as $item_id => &$itemPrivacyPatientAttr) {
                $redisExtend->setItem($item_id, Json::encode($itemPrivacyPatientAttr));
            }
        }
    }

}