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

namespace Application\Service\DB\Collect;

use Interop\Container\ContainerInterface;
use Laminas\Config\Factory;

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

    /**
     * Notes: 更新数据
     * User: lltyy
     * DateTime: 2023/5/24 9:48
     *
     * @param $content //更新内容
     * @param $setWordDatas //设置的白名单数据
     * @param $oldMateDatas //历史已匹配信息
     * @param $oldLockDatas //历史已锁定信息
     * @return int
     */
    public function saveMedicalData($content,&$setWordDatas,&$oldMateDatas){
        $ocrContentId = empty($content['id']) ? 0 : $content['id'];
        $save_data = [
            'id'=>$ocrContentId,
            'item_id'=>$content['item_id'],
            'itemsig_id'=>$content['itemsig_id'],
            'patient_id'=>$content['patient_id'],
            'checktime_id'=>$content['checktime_id'],
            'annex_id'=>$content['annex_id'],
            'medical_date'=>$content['annex_date'],
            'medical_name'=>empty($content['raw_name']) ? '' : trim($content['raw_name']),
            'mate_type'=>1
        ];
        $result = $this->save($save_data);
        if($result){
            $ocrContentId = empty($ocrContentId) ? $result : $ocrContentId;

            //更新匹配信息
            $mate_data = [];
            if(!empty($content['mate_data'])){
                if(is_array($content['mate_data'])){
                    $mate_data = $content['mate_data'];
                }else{
                    $mate_data = explode(',',$content['mate_data']);
                }

            }
            $mate_data = array_values($mate_data);
            $save_mate = [
                'id'=>isset($oldMateDatas[$ocrContentId]) && !empty($oldMateDatas[$ocrContentId]) ? $oldMateDatas[$ocrContentId] : 0,
                'annex_id'=>$content['annex_id'],
                'itemsig_id'=>$content['itemsig_id'],
                'patient_id'=>$content['patient_id'],
                'medical_id'=>$ocrContentId,
                'medical_name'=>$save_data['medical_name'],
                'white_word'=>json_encode($setWordDatas),
                'mate_white'=>json_encode($mate_data)
            ];
            $this->LocalService()->collectPatientmedicalwhite->save($save_mate);
            unset($save_mate);

        }
        unset($save_data);
        unset($content);

        return $ocrContentId;
    }

    /**
     * Notes:获取附件下未匹配、已匹配、黑名单信息数据
     * User: lltyy
     * DateTime: 2023/5/18 8:31
     *
     * @param $where
     */
    public function fetchAnnexData($where){
        $arr = [
            'mate_id'=>[],//已匹配附件ID
            'mate_count'=>[],//附件下的已匹配数量
            'act_count'=>[],//附件下的已匹配有效数量
            'no_mate_id'=>[],//未匹配附件ID
            'no_mate_count'=>[],//附件下的未匹配数量
            'black_id'=>[],//黑名单附件ID
            'black_count'=>[],//附件下的黑名单数量
            'annex_date'=>[]//附件的采集时间
        ];
        $cond = [
            'where'=>$where,
            'columns'=>['annex_id','mate_type','is_lock','medical_date','drug_id']
        ];
        $datas = $this->fetchAll($cond);
        if(!empty($datas)){
            foreach($datas as $data){
                $mate_type = $data['mate_type'];
                $annex_id = $data['annex_id'];

                //附件时间
                $arr['annex_date'][$annex_id] = isset($arr['annex_date'][$annex_id]) && $arr['annex_date'][$annex_id] != '' ? $arr['annex_date'][$annex_id] : [];
                if($arr['annex_date'][$annex_id] == '' && $data['medical_date'] != '' && !in_array($data['medical_date'],$arr['annex_date'][$annex_id])){
                    $arr['annex_date'][$annex_id][] = $data['medical_date'];
                }

                //未匹配
                if(empty($mate_type)){
                    $arr['no_mate_id'][$annex_id] = $annex_id;
                    $arr['no_mate_count'][$annex_id] = isset($arr['no_mate_count'][$annex_id]) && !empty($arr['no_mate_count'][$annex_id]) ? $arr['no_mate_count'][$annex_id] : 0;
                    $arr['no_mate_count'][$annex_id] += 1;
                }
                //已匹配
                if($mate_type == 1){
                    $arr['mate_id'][$annex_id] = $annex_id;
                    $arr['mate_count'][$annex_id] = isset($arr['mate_count'][$annex_id]) && !empty($arr['mate_count'][$annex_id]) ? $arr['mate_count'][$annex_id] : 0;
                    $arr['mate_count'][$annex_id] += 1;
                    if(!empty($data['drug_id'])){
                        $arr['act_count'][$annex_id] = isset($arr['act_count'][$annex_id]) && !empty($arr['act_count'][$annex_id]) ? $arr['act_count'][$annex_id] : 0;
                        $arr['act_count'][$annex_id] += 1;
                    }
                }
                //黑名单
                if($mate_type == 2){
                    $arr['black_id'][$annex_id] = $annex_id;
                    $arr['black_count'][$annex_id] = isset($arr['black_count'][$annex_id]) && !empty($arr['black_count'][$annex_id]) ? $arr['black_count'][$annex_id] : 0;
                    $arr['black_count'][$annex_id] += 1;
                }
            }
        }

        if(!empty($arr['black_id'])){
            foreach($arr['black_id'] as $black_annex){
                unset($arr['mate_id'][$black_annex]);//去除已匹配数据中黑名单附件
                unset($arr['no_mate_id'][$black_annex]);//去除未匹配数据中黑名单附件
            }
        }

        if(!empty($arr['no_mate_id'])){
            foreach($arr['no_mate_id'] as $no_mate_annex){
                unset($arr['mate_id'][$no_mate_annex]);//去除已匹配数据中未匹配附件
            }
        }
        $arr['no_mate_id'] = array_values($arr['no_mate_id']);
        $arr['mate_id'] = array_values($arr['mate_id']);
        $arr['black_id'] = array_values($arr['black_id']);

        return $arr;
    }

    /**
     * Notes: 删除指定识别名称数据
     * User: lltyy
     * DateTime: 2023/5/25 16:07
     *
     * @param $where//数据条件
     * @param array $delete_name_arr//要删除的识别内容数组
     * @param int $update_annex//是否更新附件信息【0 否 1 是】
     * @return int
     */
    public function deleteDataHaveName(array $where,array $delete_name_arr=[],$update_annex = 0){
        $count = 0;
        if(!empty($delete_name_arr)){
            $count = 1;
            //查询要删除的数据ID以及对应的附件ID
            $annex_arr = $delete_arr = [];
            $where_arr = [];
            foreach($delete_name_arr as $delete_name){
                $where_arr[] = 'medical_name like "%'.$delete_name.'%"';
            }
            $where .= ' and ('.implode(' or ',$where_arr).')';
            $cond = [
                'where'=>$where,
                'columns'=>['id','annex_id']
            ];
            $datas = $this->fetchAll($cond);
            if(!empty($datas)){
                foreach($datas as $data){
                    $data_annex = $data['annex_id'];
                    $annex_arr[$data_annex] = $data_annex;
                    $delete_arr[] = $data['id'];
                }
            }
            unset($where_arr);
            unset($where);
            unset($cond);
            unset($datas);

            //删除符合要求的识别内容
            if(!empty($delete_arr)){
                $this->upDelState('is_del = 0 and id in ('.implode(',',$delete_arr).')',1);
                $this->LocalService()->collectPatientmedicalwhite->upDelState('is_del = 0 and medical_id in ('.implode(',',$delete_arr).')',1);
                $this->LocalService()->collectPatientmedicalblack->upDelState('is_del = 0 and medical_id in ('.implode(',',$delete_arr).')',1);
                $this->LocalService()->collectPatientmedicallock->upDelState('is_del = 0 and medical_id in ('.implode(',',$delete_arr).')',1);
            }
            unset($delete_arr);

            //更新附件信息
            if($update_annex == 1 && !empty($annex_arr)){
                //$annex_arr = array_values($annex_arr);
                //$annex_count_arr = $this->fetchAnnexData('is_del = 0 and annex_id in ('.implode(',',$annex_arr).')');
                //$this->LocalService()->tmpOcrannex->updateAnnexCount('id in ('.implode(',',$annex_arr).')',0,0,$raw_annex_count_arr,$annex_count_arr,$ct_annex_count_arr);
            }
            unset($annex_arr);
        }

        return $count;
    }

    /**
     * Notes: 批量替换识别信息
     * User: lltyy
     * DateTime: 2023/5/25 16:07
     *
     * @param $where//数据条件
     * @param array $replace_datas//要替换的数组
     * @param int $update_ocr//是否重新匹配【0 否 1 是】
     * @return int
     */
    public function replaceDataHaveInfo($where,array $replace_datas=[],$update_ocr = 0)
    {
        $count = 0;
        if (!empty($replace_datas)) {
            $count = 1;

            //查询要替换的数据ID
            $where_arr = [];
            foreach ($replace_datas as $replace) {
                $where_arr[] = 'medical_name like "%' . $replace['replace_pre'] . '%"';
            }
            unset($replace_arr);

            $where .= ' and (' . implode(' or ', $where_arr) . ')';
            $cond = [
                'where' => $where,
                'columns' => ['id', 'annex_id', 'medical_name']
            ];
            $update_arr = $update_annex_arr = [];
            $datas = $this->fetchAll($cond);
            if (!empty($datas)) {
                foreach ($datas as $data) {
                    $medical_id = $data['id'];
                    $medical_name = $data['medical_name'];
                    foreach ($replace_datas as $replace_info) {
                        $medical_name = str_replace($replace_info['replace_pre'], $replace_info['replace_after'], $medical_name);
                    }

                    $update_data = [];
                    if ($medical_name != $data['medical_name']) {
                        $update_data['medical_name'] = $medical_name;
                    }
                    if (!empty($update_data)) {
                        if ($update_ocr == 0) {//更新明细信息
                            $this->LocalService()->collectPatientmedicallock->update($update_data, 'is_del = 0 and medical_id = ' . $medical_id);
                        }

                        if ($update_ocr == 1) {//重新匹配
                            $update_arr[] = $medical_id;
                            $update_annex_arr[] = $data['annex_id'];
                            $update_data['mate_type'] = 0;
                        }
                        $this->update($update_data, 'id = ' . $medical_id);
                    }

                    unset($update_data);
                }
            }
            unset($where_arr);
            unset($cond);
            unset($datas);
            unset($replace_datas);

            //重新匹配
            if($update_ocr == 1 && !empty($update_arr)){
                //删除已匹配数据
                $this->LocalService()->collectPatientmedicalwhite->upDelState('is_del = 0 and medical_id in ('.implode(',',$update_arr).')',1);
                $this->LocalService()->collectPatientmedicalblack->upDelState('is_del = 0 and medical_id in ('.implode(',',$update_arr).')',1);

                //获取黑/白名单数据
                $wordDatas = $this->LocalService()->collectMedicalword->wordNameData('is_del = 0');
                $white_word_arr = isset($wordDatas['white_word']) && !empty($wordDatas['white_word']) ? $wordDatas['white_word'] : [];
                $black_word_arr = isset($wordDatas['black_word']) && !empty($wordDatas['black_word']) ? $wordDatas['black_word'] : [];
                unset($wordDatas);

                //重新跑匹配
                $this->LocalService()->collectPatientmedicalwhite->mateWordData('id in ('.implode(',',$update_arr).')',0,0,$white_word_arr,$black_word_arr);

                //更新附件信息
                //$medical_annex_arr = $this->fetchAnnexData('is_del = 0 and annex_id in ('.implode(',',$update_annex_arr).')');
                //$annex_where = 'is_del = 0 and annex_type = 2 and id in ('.implode(',',$update_annex_arr).')';
                //$this->LocalService()->tmpOcrannex->updateAnnexCount($annex_where,0,0,$raw_annex_count_arr,$medical_annex_arr,$ct_annex_count_arr);

            }
            unset($update_arr);
            unset($update_annex_arr);
        }
        return $count;
    }

    /**
     * Notes:匹配上黑名单的数据与黑名单下白名单名称重新匹配
     * User: lltyy
     * DateTime: 2023/5/26 14:42
     *
     * @param $where
     * @param $word_name
     */
    public function mateWordData($where,$word_name){
        $count = 0;
        $where .= ' and mate_type = 2 and medical_name like "%'.$word_name. '%"';
        $cond = [
            'where' => $where,
            'columns' => ['id', 'annex_id']
        ];
        $update_arr = $update_annex_arr = [];
        $datas = $this->fetchAll($cond);
        if (!empty($datas)) {
            $count = 1;
            foreach ($datas as $data) {
                $update_arr[] = $data['id'];
                $update_annex_arr[] = $data['annex_id'];
            }
            $update_annex_arr = array_unique($update_annex_arr);
            $update_annex_arr = array_values($update_annex_arr);
        }
        unset($where_arr);
        unset($cond);
        unset($datas);

        //重新更新数据
        if(!empty($update_arr)){
            //删除已匹配数据
            $this->update(['mate_type'=>1],'id in ('.implode(',',$update_arr).')');
            $this->LocalService()->collectPatientmedicalblack->upDelState('is_del = 0 and medical_id in ('.implode(',',$update_arr).')',1);

            //更新附件信息
            //$medical_annex_arr = $this->fetchAnnexData('is_del = 0 and annex_id in ('.implode(',',$update_annex_arr).')');
            //$annex_where = 'is_del = 0 and annex_type = 2 and id in ('.implode(',',$update_annex_arr).')';
            //$this->LocalService()->tmpOcrannex->updateAnnexCount($annex_where,0,0,$raw_annex_count_arr,$medical_annex_arr,$ct_annex_count_arr);

        }
        unset($update_arr);
        unset($update_annex_arr);

        return $count;
    }


    /**
     * Notes:
     * User: lltyy
     * DateTime: 2023/6/6 8:52
     *
     */
    public function mateData($where,$limit=0,$offset=0){
        //获取指定条件下的医嘱数据
        $cond = [
            'where'=>$where,
            'columns'=>['id','sig_id','patient_id','annex_id','content'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->LocalService()->tmpTable->fetchAll($cond);
        unset($cond);
        $last_id = 0;
        if(!empty($datas)){
            //删除原匹配数据
            $delete_mate_arr = [];
            foreach($datas as $data_info){
                $last_id = $data_info['id'];
                $delete_mate_arr[] = $data_info['id'];
            }
            $this->update(['is_del'=>1],'is_del = 0 and table_id in ('.implode(',',$delete_mate_arr).')');
            unset($delete_mate_arr);

            foreach ($datas as $dataKey=>$data) {
                $save_data = [
                    'table_id'=>$data['id'],
                    'itemsig_id'=>$data['sig_id'],
                    'patient_id'=>$data['patient_id'],
                    'annex_id'=>$data['annex_id'],
                    'is_lock'=>0,
                    'mate_type'=>0,
                ];
                $content_arr = [];
                $ocr_content_datas = json_decode($data['content'],true);
                if(!empty($ocr_content_datas)){
                    foreach($ocr_content_datas as $ocr_content_data_key=>$ocr_content_arr){
                        foreach($ocr_content_arr as $ocr_content_key=>$ocr_content){
                            if(isset($ocr_content[0]) && strpos($ocr_content[0],'日期') === false  && strpos($ocr_content[0],'时间') === false && strpos($ocr_content[0],'开始') === false){
                                $content_arr[] = [
                                    'ocr_start_date'=>isset($ocr_content[0]) && $ocr_content[0] != '' ? $ocr_content[0] : '',
                                    'ocr_end_date'=>isset($ocr_content[5]) && $ocr_content[5] != '' ? $ocr_content[5] : '',
                                    'medical_name'=>isset($ocr_content[2]) && $ocr_content[2] != '' ? $ocr_content[2] : ''
                                ];
                            }
                            unset($ocr_content_arr[$ocr_content_key]);
                        }
                    }
                }
                unset($ocr_content_arr);

                if(!empty($content_arr)){
                    foreach($content_arr as $contentKey=>&$content){
                        $content = array_merge($save_data,$content);
                        $this->save($content);
                        unset($content_arr[$contentKey]);
                    }
                }
                unset($content_arr);
                unset($datas[$dataKey]);
            }
        }
        unset($datas);

        return $last_id;
    }

    /**
     * Notes:医嘱 - 信息【调用此方法时修改表名为：yikeen_tmp_medical】
     * User: lltyy
     * DateTime: 2023/6/6 8:52
     *
     */
    public function scanData($where='') {
        //信息匹配
        if(empty($where)){
            $where = 'is_del = 0 and annex_type in (89230)';
        }

        $sig_id_arr = [];
        if(!empty($sig_id_arr)){
            $where .= ' and sig_id in ('.implode(',',$sig_id_arr).')';
        }
        $bool = true;
        $page = 0;
        $limit = 100;
        $last_id = 0;
        while ($bool) {
            $page++;
            echo "medicalPAGE {$page}：" . PHP_EOL;
            $last_id = $this->mateData($where.' and id > '.$last_id,$limit,0);
            if(!$last_id) $bool = false;
        }
        unset($wordDatas);
    }


}