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

namespace Application\Service\DB\Tmp;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Expression;
use Laminas\Db\Sql\Predicate\Operator;

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

    /**
     * Notes: 获取中心患者的药物信息
     * User: lltyy  --  copy
     * DateTime: 2023/11/5 14:21
     *
     * @param array $info
     * @return array[]
     */
    public function fetchDrugDataByPatientSig(array $info=[]){

        $no_annex = isset($info['no_annex']) && !empty($info['no_annex']) ? $info['no_annex'] : 0;
        $drug_id = isset($info['drug_id']) && !empty($info['drug_id']) ? $info['drug_id'] : 0;
        $data_type = isset($info['data_type']) && !empty($info['data_type']) ? $info['data_type'] : 0;
        $sig_id = isset($info['sig_id']) && !empty($info['sig_id']) ? $info['sig_id'] : 0;
        $patient_id = isset($info['patient_id']) && !empty($info['patient_id']) ? $info['patient_id'] : 0;
        $drug_arr = isset($info['drug_arr']) && !empty($info['drug_arr']) ? $info['drug_arr'] : [];
        $noselect_take = isset($info['noselect_take']) && !empty($info['noselect_take']) ? $info['noselect_take'] : 0;
        $arr = [
            'sig'=>[],
            'patient'=>[],
            'all'=>[],
            'use_num'=>[],
            'patient_drug'=>[],
            'lock_drug'=>[],
            'lock_drug_data'=>[]
        ];
        $where = ['is_del'=>0];
        if(!empty($no_annex)) $where[] = new Operator('annex_id',Operator::OP_NE,$no_annex);
        //药物ID
        if(!empty($drug_id)){
            $where['drug_id'] = $drug_id;
        }else{
            if(!empty($sig_id)){
                $where['itemsig_id'] = $sig_id;
            }
        }
        if(!empty($drug_arr)){
            $where['drug_id'] = $drug_arr;
        }
        if($data_type == 1){
            if(!empty($sig_id)){
                $where['itemsig_id'] = $sig_id;
            }
            if(!empty($patient_id)){
                $where['patient_id'] = $patient_id;
            }
        }
//        var_dump($where);die;
        $cond = [
            'where'=>$where,
            'columns'=>['itemsig_id','patient_id','drug_id','annex_id','medical_date','end_date','dosage_num','dosage_unit','dosage_times','is_dispensary','objective'],
            'order'=>['medical_date asc','end_date asc']
        ];
        $lockDatas = $this->fetchAll($cond);

        unset($where);   unset($cond);

        if(!empty($lockDatas)){
            $patientDrugDatas = $takeNameArr = [];
            if($noselect_take != 1){
                $takeInfos = $this->LocalService()->dictionaryMedicaltake->fetchAll(['where'=>['is_del'=>0,'take_type'=>[2,3]],'columns'=>['id','english','name']]);
                if(!empty($takeInfos)){
                    foreach($takeInfos as $takeKey=>$takeInfo){
                        $takeId = $takeInfo['id'];
                        $takeNameArr[$takeId] = !empty($takeInfo['english']) ? $takeInfo['name'].'('.$takeInfo['english'].')' : $takeInfo['name'];
                        unset($takeInfos[$takeKey]);
                    }
                }
                unset($takeInfos);
            }


            foreach($lockDatas as $lockKey=>$lockData){
                $lock_sig = $lockData['itemsig_id'];
                $lock_patient = $lockData['patient_id'];//受试者ID
                $lock_drug = $lockData['drug_id']; //药物ID

                if(!isset($arr['sig'][$lock_sig][$lock_drug])){
                    $arr['sig'][$lock_sig][$lock_drug] = $lockData;
                }
                if(!isset($arr['patient'][$lock_patient][$lock_drug])){
                    $arr['patient'][$lock_patient][$lock_drug] = $lockData;
                }
                if(!isset($arr['all'][$lock_drug])){
                    $arr['all'][$lock_drug] = $lockData;
                }
                $arr['use_num'][$lock_drug] = isset($arr['use_num'][$lock_drug]) && !empty($arr['use_num'][$lock_drug]) ? $arr['use_num'][$lock_drug] : 0;
                $arr['use_num'][$lock_drug] += 1;

                //患者药物已存信息
                $medical_date = !is_null($lockData['medical_date']) && !empty($lockData['medical_date']) ? $lockData['medical_date'] : 0;
                if(!empty($medical_date)){
                    $patientDrugDatas[$lock_patient][$lock_drug]['start_date'][] = $medical_date;
                }
                $end_date = !is_null($lockData['end_date']) && !empty($lockData['end_date']) ? $lockData['end_date'] : 0;
                if(!empty($end_date)){
                    $patientDrugDatas[$lock_patient][$lock_drug]['end_date'][] = $end_date;
                }
                $dosage_num = !is_null($lockData['dosage_num']) && !empty($lockData['dosage_num']) ? $lockData['dosage_num'] : 0;
                $dosage_unit = !is_null($lockData['dosage_unit']) && !empty($lockData['dosage_unit']) ? $lockData['dosage_unit'] : 0;
                $num_unit = $dosage_num;
                if(!empty($dosage_num)){
                    if(!empty($dosage_unit) && isset($takeNameArr[$dosage_unit]) && !empty($takeNameArr[$dosage_unit])){
                        $num_unit .= '（'.$takeNameArr[$dosage_unit].'）';
                        $patientDrugDatas[$lock_patient][$lock_drug]['dosage_num'][] = $dosage_num.$takeNameArr[$dosage_unit];
                    }else{
                        $patientDrugDatas[$lock_patient][$lock_drug]['dosage_num'][] = $dosage_num;
                    }
                }

                $times_id = !is_null($lockData['dosage_times']) && !empty($lockData['dosage_times']) ? $lockData['dosage_times'] : 0;
                if(!empty($times_id)){
                    $patientDrugDatas[$lock_patient][$lock_drug]['dosage_times'][] = $times_id;
                }
                if($lockData['is_dispensary'] == 1){
                    $patientDrugDatas[$lock_patient][$lock_drug]['is_dispensary'] = 1;
                }
                $arr['lock_drug_data'][$lock_patient][$lock_drug][] = [
                    'id'=>$lockData['annex_id'],
                    'medical_date'=>empty($medical_date) ? '' : $medical_date,
                    'end_date'=>empty($end_date) ? '' : $end_date,
                    'dosage_num'=>$num_unit,
                    'dosage_times'=>isset($takeNameArr[$times_id]) && !empty($takeNameArr[$times_id]) ? $takeNameArr[$times_id] : '',
                    'is_dispensary'=>$lockData['is_dispensary'] == 1 ? '√' : '',
                    'objective'=>$lockData['objective'],
                ];
                unset($lockDatas[$lockKey]);
            }

            if(!empty($patientDrugDatas)){
                foreach($patientDrugDatas as $patientId=>$lockDrugDatas){
                    foreach($lockDrugDatas as $lockDrugId=>$lockDrugData){
                        $lock_mes_arr = [];//展示信息

                        //开始日期
                        $drug_startdate_arr = isset($lockDrugData['start_date']) && !empty($lockDrugData['start_date']) ? $lockDrugData['start_date'] : [];
                        $drug_startdate_arr = array_unique($drug_startdate_arr);
                        $drug_startdate_arr = array_values($drug_startdate_arr);
                        sort($drug_startdate_arr);
                        if(!empty($drug_startdate_arr)){
                            $lock_mes_arr[] = '（'.$drug_startdate_arr[0].'）';
                        }
                        $arr['lock_drug'][$patientId][$lockDrugId]['medical_date'] = !empty($drug_startdate_arr) ? $drug_startdate_arr[0] : '';
                        unset($drug_startdate_arr);

                        //剂量
                        $drug_dosagenum_arr = isset($lockDrugData['dosage_num']) && !empty($lockDrugData['dosage_num']) ? $lockDrugData['dosage_num'] : [];
                        $drug_dosagenum_arr = array_unique($drug_dosagenum_arr);
                        $drug_dosagenum_arr = array_values($drug_dosagenum_arr);
                        if(!empty($drug_dosagenum_arr)){
                            $lock_mes_arr[] = '（'.implode('/',$drug_dosagenum_arr).'）';
                        }
                        $arr['lock_drug'][$patientId][$lockDrugId]['dosage_num'] = $drug_dosagenum_arr;
                        unset($drug_dosagenum_arr);

                        //服用频率
                        $drug_timesid_arr = isset($lockDrugData['dosage_times']) && !empty($lockDrugData['dosage_times']) ? $lockDrugData['dosage_times'] : [];
                        $drug_timesid_arr = array_unique($drug_timesid_arr);
                        $drug_timesid_arr = array_values($drug_timesid_arr);
                        $drug_timesid_name = [];
                        if(!empty($drug_timesid_arr)){
                            foreach($drug_timesid_arr as $drug_timesid){
                                if(isset($takeNameArr[$drug_timesid]) && !empty($takeNameArr[$drug_timesid])){
                                    $drug_timesid_name[] = $takeNameArr[$drug_timesid];
                                }
                            }
                            $lock_mes_arr[] = '（'.implode('/',$drug_timesid_name).'）';
                        }
                        $arr['lock_drug'][$patientId][$lockDrugId]['dosage_times'] = $drug_timesid_name;
                        unset($drug_timesid_arr);
                        unset($drug_timesid_name);

                        //结束日期
                        $drug_enddate_arr = isset($lockDrugData['end_date']) && !empty($lockDrugData['end_date']) ? $lockDrugData['end_date'] : [];
                        $drug_enddate_arr = array_unique($drug_enddate_arr);
                        $drug_enddate_arr = array_values($drug_enddate_arr);
                        rsort ($drug_enddate_arr);
                        if(!empty($drug_enddate_arr)){
                            $lock_mes_arr[] = '（'.$drug_enddate_arr[0].'）';
                        }
                        $arr['lock_drug'][$patientId][$lockDrugId]['end_date'] = !empty($drug_enddate_arr) ? $drug_enddate_arr[0] : '';
                        unset($drug_enddate_arr);

                        //结束日期
                        $arr['lock_drug'][$patientId][$lockDrugId]['is_dispensary'] = 0;
                        if(isset($lockDrugData['is_dispensary']) && $lockDrugData['is_dispensary'] == 1){
                            $lock_mes_arr[] = '（取药）';
                            $arr['lock_drug'][$patientId][$lockDrugId]['is_dispensary'] = 1;
                        }
                        $arr['patient_drug'][$patientId][$lockDrugId] = implode('、',$lock_mes_arr);

                        unset($lock_mes_arr);
                        unset($lockDrugDatas[$lockDrugId]);
                    }
                    unset($patientDrugDatas[$patientId]);
                }
                unset($takeNameArr);
            }
            unset($patientDrugDatas);
        }
        unset($lockDatas);
        return $arr;
    }


    /**
     * Notes : 通过受试者、药物获取锁定数据
     * @param string $patient_id
     * @param string $drug_id
     * @return array[]
     * Author:唐伯虎不虎
     * Date:2024/1/31 11:16
     */
    public function getlockdrugData(string $patient_id,string $drug_id)
    {
        if(empty($patient_id) || empty($drug_id)) return false;


        $lockWhere['where'] = ['is_del'=>0,'patient_id'=>$patient_id,'drug_id'=>$drug_id];
        $lockWhere['columns'] = ['medical_date','end_date','dosage_unit','dosage_way','patient_id','drug_id','itemsig_id','dosage_medication','is_continue',
            'dosage_times','is_dispensary','adjust_num','dosage_num','objective'];
        $lockWhere['order'] = ['medical_date','end_date'];

        $datas = $this->fetchAll($lockWhere);

        $drug_name = $this->LocalService()->dictionaryDrug->getOneFieldVal('name',['is_del'=>0,'id'=>$drug_id]);

        $takeDatas = $this->LocalService()->dictionaryMedicaltake->fetchAll(['where' => ['is_del'=>0,'take_type'=>[2,3,4,6]], 'columns' => ['id','name','take_number']]);

        $quick_takeData = [];

        foreach($takeDatas as $k=>$v){
            $quick_takeData[$v['id']] = $v;
        }

        if(!empty($datas)){
            foreach($datas as $k=>&$v){
                //查询药物名称
                $v['drug_name'] = $drug_name;
                //频次
                if(!empty($v['dosage_times'])){
                    $v['dosage_times_number'] = $quick_takeData[$v['dosage_times']]['take_number'];
                }

                if(empty($v['dosage_times_number'])) $v['dosage_times_number'] = 1;
                if(empty($v['dosage_medication'])) $v['dosage_medication'] = 1;
            }
        }
        return $datas;
    }


    /**
     * Notes : 获取受试者已锁定数据所有药物
     * @param string $patient_id
     * @return array
     * Author:唐伯虎不虎
     * Date:2024/1/31 13:53
     */
    public function getpatientdrug(int $patient_id = 0):array
    {
        $lockdrugWhere['where'] = ['is_del'=>0];
        if(!empty($patient_id)){
            $lockdrugWhere['where']['patient_id'] = $patient_id;
        }

        $lockdrugWhere['columns'] = [new Expression('COUNT(`id`) as count'),'drug_id','patient_id'];

        $lockdrugWhere['group'] = ['drug_id'];

        $datas = $this->fetchAll($lockdrugWhere);

        $patient_drug = [];
        if(!empty($datas))
            foreach($datas as $k=>&$v){
                $v['name'] = $this->LocalService()->dictionaryDrug->getOneFieldVal('name',['id'=>$v['drug_id']]);
                $patient_drug[$v['patient_id']][] = $v;
            }
        unset($datas);
        return $patient_drug;
    }


    public function getlockData($patient_id,$drug_id=0)
    {
        $lockWhere['where'] = ['is_del'=>0,'patient_id'=>$patient_id];
        if(!empty($drug_id)){
            $lockWhere['where']['medical_date'] = $drug_id;
        }

        $lockWhere['columns'] = ['medical_date','end_date','dosage_unit','dosage_way','patient_id','drug_id','itemsig_id','dosage_medication','is_continue',
            'dosage_times','is_dispensary','adjust_num','dosage_num','drug_id'];
        $lockWhere['order'] = ['medical_date'];

        $datas = $this->fetchAll($lockWhere);

        if(empty($datas)) return [];

        $drugStr = array_values(array_unique(array_column($datas,'drug_id')));

        $drugnameDatas = $this->LocalService()->dictionaryDrug->fetchCol('name',['id'=>$drugStr]);

        $takeDatas = $this->LocalService()->dictionaryMedicaltake->fetchAll(['where' => ['is_del'=>0,'take_type'=>[2,3,4,6]], 'columns' => ['id','name','take_number']]);

        $quick_takeData = [];

        foreach($takeDatas as $k=>$v){
            $quick_takeData[$v['id']] = $v;
        }

        if(!empty($datas)){
            foreach($datas as $k=>&$v){
                if($v['doctoradvice_type'] == 0) {
                    $v['end_date'] = $v['medical_date'];
                    $v['special'] = 0;
                }elseif($v['doctoradvice_type'] == 1 && empty($v['medical_date'])){
                    $v['end_date'] = $v['medical_date'];
                    $v['special'] = 1;
                }
                //查询药物名称
                $v['name'] = $drugnameDatas[$v['drug_id']];
                //频次
                if(!empty($v['dosage_times'])){
                    $v['dosage_times'] = $quick_takeData[$v['dosage_times']]['name'];
                    $v['dosage_times_number'] = $quick_takeData[$v['dosage_times']]['take_number'];
                }
                //计量单位
                if(!empty($v['dosage_unit'])) $v['dosage_unit'] = $quick_takeData[$v['dosage_unit']]['name'];
                //服用方式
                if(!empty($v['dosage_way'])) $v['dosage_way'] = $quick_takeData[$v['dosage_way']]['name'];

                if(!empty($v['dosage_medication'])) $v['dosage_medication'] = $quick_takeData[$v['dosage_medication']]['name'];


                $v['is_continue'] = ($v['is_continue'] > 0) ? '是' : '否';
                $v['is_dispensary'] = ($v['is_dispensary'] > 0) ? '是' : '否';

            }
        }
        return $datas;
    }


    public function getlockData_gather($patient_id,$limit,$offset)
    {

        $lockWhere['where'] = ['is_del'=>0];
        if(!empty($patient_id)){
            $lockWhere['where']['patient_id'] = $patient_id;
        }


        $lockWhere['columns'] = ['medical_date','end_date','dosage_unit','dosage_way','patient_id','drug_id','itemsig_id','dosage_medication','is_continue',
            'dosage_times','is_dispensary','adjust_num','dosage_num','drug_id'];
        $lockWhere['order'] = ['medical_date'];
        if(!empty($limit)){
            $lockWhere['limit'] = $limit;
            $lockWhere['offset'] = $offset;
        }


        $datas = $this->fetchAll($lockWhere);

        if(empty($datas)) return [];

        $drugStr = array_values(array_unique(array_column($datas,'drug_id')));

        $drugnameDatas = $this->LocalService()->dictionaryDrug->fetchCol('name',['id'=>$drugStr]);
        $drugremarkDatas = $this->LocalService()->dictionaryDrug->fetchCol('drug_remark',['id'=>$drugStr]);

        $takeDatas = $this->LocalService()->dictionaryMedicaltake->fetchAll(['where' => ['is_del'=>0,'take_type'=>[2,3,4,6]], 'columns' => ['id','name','take_number']]);

        $quick_takeData = [];

        foreach($takeDatas as $k=>$v){
            $quick_takeData[$v['id']] = $v;
        }

        if(!empty($datas)){
            foreach($datas as $k=>&$v){
                if($v['doctoradvice_type'] == 0) {
                    $v['end_date'] = $v['medical_date'];
                    $v['special'] = 0;
                }elseif($v['doctoradvice_type'] == 1 && empty($v['medical_date'])){
                    $v['end_date'] = $v['medical_date'];
                    $v['special'] = 1;
                }
                //查询药物名称
                $v['name'] = $drugnameDatas[$v['drug_id']];
                $v['english'] = $drugremarkDatas[$v['drug_id']];
                //频次
                if(!empty($v['dosage_times'])){
                    $v['dosage_times'] = $quick_takeData[$v['dosage_times']]['name'];
                    $v['dosage_times_number'] = $quick_takeData[$v['dosage_times']]['take_number'];
                }
                //计量单位
                if(!empty($v['dosage_unit'])) $v['dosage_unit'] = $quick_takeData[$v['dosage_unit']]['name'];
                //服用方式
                if(!empty($v['dosage_way'])) $v['dosage_way'] = $quick_takeData[$v['dosage_way']]['name'];

                if(!empty($v['dosage_medication'])) $v['dosage_medication'] = $quick_takeData[$v['dosage_medication']]['name'];

                $v['is_continue'] = ($v['is_continue'] > 0) ? '是' : '否';
                $v['is_dispensary'] = ($v['is_dispensary'] > 0) ? '是' : '否';

            }
        }
        return $datas;
    }


    /**
     * Notes : 获取受试者用药时间
     * @param $patient_id
     * @return mixed
     * Author:唐伯虎不虎
     * Date:2024/2/4 10:01
     */
    public function getpatientlockdate($patient_id)
    {
        $lockdrugWhere['where'] = [
            'patient_id'=>$patient_id,
            new Operator('medical_date',Operator::OP_GT,0)
        ];

        $lockdrugWhere['columns'] = ['medical_date','patient_id'];

        $lockdrugWhere['group'] = ['medical_date'];

        $lockdrugWhere['order'] = ['medical_date'];

        $datas = $this->fetchAll($lockdrugWhere);

        return $datas;
    }

}