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

namespace Application\Service\DB\Tmp;
use Interop\Container\ContainerInterface;

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

    public function getannexinfo($patient_id,$annex_id,$type=1,$sig_id,$is_lock)
    {
        $tableName = ($is_lock>0) ? 'tmpDoctoradvicelock' : 'TmpDoctoradviceoriginal';

        //获取受试者附件产生的用药信息
        $doctoradviceWhere['where'] = ['is_del'=>0,'patient_id'=>$patient_id,'annex_id'=>$annex_id];
        if($is_lock == 0) $doctoradviceWhere['where']['mate_type'] = 1;
        $doctoradviceWhere['columns'] = ['id','objective','medical_date','dosage_medication','is_continue','medical_name','end_date','drug_id','dosage_num','dosage_unit','dosage_id','dosage_way','dosage_times','is_dispensary','medical_name','adjust_num'];

        $doctoradviceWhere['order'] = ['id'];

        $datas = $this->LocalService()->$tableName->fetchAll($doctoradviceWhere);
//var_dump($datas);die;
        $save_drug_arr = [];
        foreach($datas as $ocrContentInfo){
            if(!empty($ocrContentInfo['drug_id']) && !in_array($ocrContentInfo['drug_id'],$save_drug_arr)){
                $save_drug_arr[] = $ocrContentInfo['drug_id'];
            }
        }

        if($is_lock == 1){
            $sigLockContentDatas = $this->LocalService()->tmpDoctoradvicelock->fetchDrugDataByPatientSig(['no_annex'=>$annex_id,'data_type'=>1,'sig_id'=>$sig_id,'patient_id'=>$patient_id,'drug_arr'=>$save_drug_arr]);
        }else{
            $sigLockContentDatas = $this->LocalService()->tmpDoctoradvicelock->fetchDrugDataByPatientSig(['no_annex'=>$annex_id,'data_type'=>1,'sig_id'=>$sig_id,'drug_arr'=>$save_drug_arr]);
        }
        unset($save_drug_arr);
        $lockDrugDetails = [];
        if(isset($sigLockContentDatas['patient_drug'])){
            $lockDrugDetails = isset($sigLockContentDatas['patient_drug'][$patient_id]) && !empty($sigLockContentDatas['patient_drug'][$patient_id]) ? $sigLockContentDatas['patient_drug'][$patient_id] : [];
            unset($sigLockContentDatas['patient_drug']);
        }
        $takeInfos = $this->LocalService()->dictionaryMedicaltake->fetchAll(['where'=>['is_del'=>0],'columns'=>['id','english','name']]);
        if(!empty($takeInfos)){
            foreach($takeInfos as $takeKey=>$takeInfo){
                $takeNameArr[$takeInfo['id']] = $takeInfo;
                unset($takeInfos[$takeKey]);
            }
        }
        unset($takeInfos);


        if(!empty($datas)){
            foreach($datas as $k=>&$info){
                //获取用药名称
                $info['name'] = $this->LocalService()->dictionaryDrug->getOneFieldVal('name',['id'=>$info['drug_id']]);
                $info['english'] = $this->LocalService()->dictionaryDrug->getOneFieldVal('drug_remark',['id'=>$info['drug_id']]);
                $info['medical_date'] = !is_null($info['medical_date']) && !empty($info['medical_date']) ? $info['medical_date'] : '';//开始日期
                $info['end_date'] = !is_null($info['end_date']) && !empty($info['end_date']) ? $info['end_date'] : '';//结束日期
                $info['drug_id'] = !is_null($info['drug_id']) && !empty($info['drug_id']) ? $info['drug_id'] : '';//药物
                $info['dosage_num'] = !is_null($info['dosage_num']) && $info['dosage_num'] != '' ? $info['dosage_num'] : '';//剂量
                $info['dosage_unit'] = !is_null($info['dosage_unit']) && !empty($info['dosage_unit']) ? $info['dosage_unit'] : '';//剂量单位
                $info['dosage_way'] = !is_null($info['dosage_way']) && !empty($info['dosage_way']) ? $info['dosage_way'] : '';//服用方式
                $info['dosage_times'] = !is_null($info['dosage_times']) && !empty($info['dosage_times']) ? $info['dosage_times'] : '';//服用频次
                $info['adjust_num'] = !is_null($info['adjust_num']) && !empty($info['adjust_num']) ? $info['adjust_num'] : '';//调整量
                $info['medical_name'] = !is_null($info['medical_name']) && !empty($info['medical_name']) ? $info['medical_name'] : '';

                $content_drug = !empty($info['drug_id']) ? $info['drug_id'] : 0;
                $info['other_save'] = isset($lockDrugDetails) && !empty($lockDrugDetails[$content_drug]) ? $lockDrugDetails[$content_drug] : '';

                //未锁定
                if($is_lock != 1){
                    if(!is_null($info['ocr_start_date']) && !empty($info['ocr_start_date'])){
                        $info['medical_name'] = $info['ocr_start_date'].$info['medical_name'];
                    }
                    unset($info['ocr_start_date']);


                    //获取默认锁定信息
                    $lockDrug = [];
                    if(isset($sigLockContentDatas['patient'][$patient_id]) && isset($sigLockContentDatas['patient'][$patient_id][$content_drug]) && !empty($sigLockContentDatas['patient'][$patient_id][$content_drug])){
                        $lockDrug = $sigLockContentDatas['patient'][$patient_id][$content_drug];
                    }else{
                        if(isset($sigLockContentDatas['sig'][$sig_id]) && isset($sigLockContentDatas['sig'][$sig_id][$content_drug]) && !empty($sigLockContentDatas['sig'][$sig_id][$content_drug])){
                            $lockDrug = $sigLockContentDatas['sig'][$sig_id][$content_drug];
                        }else{
                            $allLockDrug = $this->LocalService()->tmpDoctoradvicelock->fetchDrugDataByPatientSig(['no_annex'=>$annex_id,'drug_id'=>$content_drug,'noselect_take'=>1]);
                            if(isset($allLockDrug['all'][$content_drug]) && !empty($allLockDrug['all'][$content_drug])){
                                $lockDrug = $allLockDrug['all'][$content_drug];
                            }
                            unset($allLockDrug);
                        }
                    }

                    if(!empty($lockDrug)){
                        //无剂量默认获取当前患者或当前中心该药物已锁定的剂量
                        if(empty($info['dosage_num'])){
                            if(isset($lockDrug['dosage_num']) && !empty($lockDrug['dosage_num'])){
                                $info['dosage_num'] = $lockDrug['dosage_num'];
                            }
                            //无剂量单位默认获取当前患者或当前中心该药物已锁定的剂量单位
                            if(isset($lockDrug['dosage_unit']) && !empty($lockDrug['dosage_unit'])){
                                $ocrContent['dosage_unit'] = $lockDrug['dosage_unit'];
                            }
                        }

                        //无服用频率默认获取当前患者或当前中心该药物已锁定的服用频率
                        if(empty($info['dosage_times'])){
                            if(isset($lockDrug['dosage_times']) && !empty($lockDrug['dosage_times'])){
                                $info['dosage_times'] = $lockDrug['dosage_times'];
                            }
                        }
                    }

                    $info['is_dispensary'] = !empty($info['is_dispensary']) ? $info['is_dispensary'] : '';
                    $info['date_bool'] = $info['end_date_bool'] = 0;
                    // 开始时间
                    if (!is_null($info['medical_date']) && $info['medical_date'] != '') {
                        $info['medical_date'] = $this->LocalService()->ocrRawdata->replaceRawdata($info['medical_date'], 2);
                        $info['medical_date'] = substr($info['medical_date'], 0, 8);
                    }

                    $validDate = $this->LocalService()->tmpDoctoradviceannex->validAnnexDate($info['medical_date']);

                    if($validDate['code'] != 200){
                        $ocrContent['date_bool'] = 1;
                    }
                    $info['medical_date'] = $validDate['date'];

                    $info['end_date_bool'] = 1;
                    $info['end_date'] = $info['medical_date'];

                }
                if($type == 0){
                    if(!empty($info['dosage_unit'])){
                        $dosage_unit = $info['dosage_unit'];
                        $info['dosage_unit'] = $takeNameArr[$info['dosage_unit']]['name'];
                        if(!empty($takeNameArr[$dosage_unit]['english'])) $info['dosage_unit'].= '('.$takeNameArr[$dosage_unit]['english'].')';
                    }

                    if(!empty($info['dosage_times'])){
                        $dosage_times = $info['dosage_times'];
                        $info['dosage_times'] = $takeNameArr[$info['dosage_times']]['name'];
                        if(!empty($takeNameArr[$dosage_times]['english'])) $info['dosage_times'].= '('.$takeNameArr[$dosage_times]['english'].')';
                    }

                    if(!empty($info['dosage_medication'])){
                        $dosage_times = $info['dosage_medication'];
                        $info['dosage_medication'] = $takeNameArr[$info['dosage_medication']]['name'];
                        if(!empty($takeNameArr[$dosage_times]['english'])) $info['dosage_medication'].= '('.$takeNameArr[$dosage_times]['english'].')';
                    }

                    $info['is_dispensary'] = !empty($info['is_dispensary']) ? '是' : '否';
                    $info['is_continue'] = !empty($info['is_continue']) ? '是' : '否';

                }
            }
        }
        return $datas;
    }

    /**
     * Notes : 删除无效医嘱原始数据
     * Author:唐伯虎不虎
     * Date:2024/1/29 17:05
     */
    public function delinvaliddata() : void
    {
        //获取指定条件下的医嘱数据
        $medicalCond = [
            'where'=>['is_del'=>0],
            'columns'=>['id','annex_id','sig_id','patient_id','medical_name','ocr_start_date','ocr_end_date'],
            'order'=>['id']
        ];

        $medicalDatas = $this->LocalService()->TmpDoctoradviceoriginal->fetchAll($medicalCond);

        if(!empty($medicalDatas)){
            $delete_arr = $delete_mate_arr = [];
            foreach($medicalDatas as $medicalKey=>$medical_info){
                $medical_info_name = trim($medical_info['medical_name']);
                if(empty($medical_info_name)){
                    $delete_arr[] = $medical_info['id'];
                    unset($medicalDatas[$medicalKey]);
                }
                $delete_mate_arr[] = $medical_info['id'];
            }

        }

        //删除不符合要求的数据
        if(!empty($delete_arr)){
            $this->LocalService()->TmpDoctoradviceoriginal->upDelState(['is_del'=>0,'id'=>$delete_arr],1);
        }
        unset($delete_arr);
    }


    public function validatetime($annex_date,$doctoradvice_type,$time_type)
    {

        if(empty($annex_date)) {
            if($doctoradvice_type == 0 && $time_type == 1) {
                return ['code'=>200,'date'=>$annex_date];
            }
            $code = 60010;
            $msg = '时间不能为空！';
            return ['code'=>$code,'msg'=>$msg,'date'=>$annex_date];
        }else{
            $annex_date_year = substr($annex_date,0,4);
            $annex_date_month = substr($annex_date,4,2);
            $annex_date_day = substr($annex_date,6,2);
            $annex_date_str = $annex_date_year.'-'.$annex_date_month.'-'.$annex_date_day;
            $date_reg = "/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/";
            //匹配日期格式
            if (preg_match ($date_reg, $annex_date_str, $parts)) {
                //检测是否为日期,checkdate为月日年
                if (checkdate($parts[2], $parts[3], $parts[1])) {
                    $code = 200;
                }else{
                    $code = 60011;
                    $msg = '时间格式不正确，【正确格式如：20210607】！';
                }
            }else{
                $code = 60011;
                $msg = '时间格式不正确，【正确格式如：20210607】！';
            }
            if($code == 200){
                $nowYear = date('Y');
                if(intval($annex_date_year) > $nowYear){
                    $code = 60011;
                    $msg = '采集时间所属年份【'.$annex_date_year.'】不能超过当前年份【'.$nowYear.'】！';
                }
            }
        }


        return ['code'=>$code,'msg'=>$msg,'date'=>$annex_date];
    }

}