<?php

namespace Application\Service\DB\Project;

use Application\Service\Extension\Laminas;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Where;

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

    public function saveExceedswindow($data)
    {
        $date = $this->LocalService()->itemPatientchecktime->fetchOne([
            'where'=>['is_del'=>0,'checktime_id'=>$data['checktime_id'],'patient_id'=>$data['patient_id']],
            'columns'=>['plan_start_date','plan_end_date']
        ]);

        $start_time = $date['plan_start_date'];

        $end_time = $date['plan_end_date'];

        foreach($data['handleDatas'] as $k=>$v){

            if($v == '1970-01-01') continue;

            $collectDate = strtotime($v);

            if($collectDate >= $start_time && $collectDate <= $end_time){
                continue;
            }

            if($collectDate < $start_time){
                $arr['exceedswindow_days'] = ceil(($collectDate/86400) - ($start_time/86400));
            }
            //采集时间大于时间窗开始时间
            if($collectDate > $end_time) {
                $arr['exceedswindow_days'] = ceil(($collectDate/86400) - ($end_time/86400));
            }

            $arr['item_id'] = $data['item_id'];
            $arr['itemsig_id'] = $data['itemsig_id'];
            $arr['patient_id'] = $data['patient_id'];
            $arr['checktime_id'] = $data['checktime_id'];
            $arr['form_id'] = $data['form_id'];
            $arr['field_id'] = $k;
            $arr['data_type'] = $data['data_type'];
            $arr['is_del'] = 0;
            $arr['content_id'] = $data['content_id'];
            $arr['form_order'] = $data['form_order'];
            $arr['date_time'] = $collectDate;
            $arr['start_time'] = $start_time;
            $arr['end_time'] = $end_time;

            $this->LocalService()->projectExceedswindow->save($arr);
        }

        return true;
    }

    public function changeBookedTime($data)
    {
        $item_id = $data['item_id'];
        $patient_id = $data['patient_id'];
        $checktime_id = $data['checktime_id'];
        $anchor_id = $data['anchor_id'];
        $checktimeArr = $this->LocalService()->itemPatientchecktime->fetchCol('checktime_id',"item_id = $item_id and patient_id = $patient_id  and anchor_id = $anchor_id and is_del = 0");


    }

    public function saveExceedswindowFormAction($item_id,$patient_id = 0,$checktime_id = [])
    {
        //删除当前条件下所有未查数据
        $updateWhere = ['item_id'=>$item_id];
        if(!empty($patient_id)) $updateWhere['patient_id'] = $patient_id;
        if(!empty($checktime_id)) $updateWhere['checktime_id'] = $checktime_id;
        $this->update(['is_del'=>1],$updateWhere);

        $dataWhere = ['is_del'=>0,'item_id'=>$item_id];
        if(!empty($patient_id)) $dataWhere['patient_id'] = $patient_id;
        if(!empty($checktime_id)) $dataWhere['checktime_id'] = $checktime_id;
        $patientchecktimeDatas = $this->LocalService()->itemPatientchecktime->fetchAll([
            'where'=>$dataWhere,
            'columns'=>['id','patient_id','checktime_id','plan_start_date','plan_end_date','item_id']
        ]);
        $date = [];
        foreach ($patientchecktimeDatas as $anchor){
            $date[$anchor['patient_id'].'-'.$anchor['checktime_id']] = $anchor;
        }
        unset($patientchecktimeDatas);

        //表单超窗
        $fieldDatas = $this->LocalService()->itemFormField->fetchCol('form_id',"item_id = $item_id and is_hyperwindow = 1 and is_del = 0");

        if(!empty($fieldDatas)){
            $formId = implode(',',$fieldDatas);

            $formDatas = $this->LocalService()->itemForm->fetchAll([
                'where'=>"is_del = 0 and id in ($formId) and item_id = $item_id",
                'columns'=>['id','item_id','type']
            ]);

            foreach($formDatas as $formV){
                $form_id = $formV['id'];
                $hyperwindowField = Laminas::$serviceManager->itemFormField->fetchCol('id',['is_del'=>0,'is_hyperwindow'=>1,'form_id'=>$form_id]);

                $config = Laminas::$serviceManager->itemForm->getPreviewConfig($form_id,true);

                $contentWhere = ['is_del'=>0,'item_id'=>$item_id,'form_id'=>$form_id];
                if(!empty($patient_id)) $contentWhere['patient_id'] = $patient_id;
                if(!empty($checktime_id)) $contentWhere['checktime_id'] = $checktime_id;
                $formContentDatas = $this->LocalService()->patientFormContent->fetchAll([
                    'where'=>$contentWhere,
                    'columns'=>['id','item_id','data','patient_id','checktime_id','form_id','itemsig_id']
                ]);
                if(empty($formContentDatas)) continue;

                foreach ($formContentDatas as $content){
                    $info = json_decode($content['data'],true);
                    $handleDatas = [];
                    foreach ($config['config']['form'] as $rule){
                        if(isset($hyperwindowField[$rule['field_id']]) && isset($info[$rule['prop']]) && !empty($info[$rule['prop']])){
                            $handleDatas[$rule['field_id']] = $info[$rule['prop']];
                        }
                    }

                    $start_time = $date[$content['patient_id'].'-'.$content['checktime_id']]['plan_start_date'];

                    $end_time = $date[$content['patient_id'].'-'.$content['checktime_id']]['plan_end_date'];

                    if(!empty($handleDatas)){

                        foreach($handleDatas as $k=>$v){

                            if($v == '1970-01-01') continue;

                            $collectDate = strtotime($v);

                            if($collectDate >= $start_time && $collectDate <= $end_time){
                                continue;
                            }

                            if($collectDate < $start_time){
                                $arr['exceedswindow_days'] = ceil(($collectDate/86400) - ($start_time/86400));
                            }
                            //采集时间大于时间窗开始时间
                            if($collectDate > $end_time) {
                                $arr['exceedswindow_days'] = ceil(($collectDate/86400) - ($end_time/86400));
                            }

                            $arr['item_id'] = $content['item_id'];
                            $arr['itemsig_id'] = $content['itemsig_id'];
                            $arr['patient_id'] = $content['patient_id'];
                            $arr['checktime_id'] = $content['checktime_id'];
                            $arr['form_id'] = $content['form_id'];
                            $arr['field_id'] = $k;
                            $arr['data_type'] = 1;
                            $arr['content_id'] = $content['id'];
                            $arr['start_time'] = $start_time;
                            $arr['end_time'] = $end_time;
                            $arr['data_time'] = $collectDate;
                            $arr['form_order'] = 1;

                            $this->LocalService()->projectExceedswindow->insert($arr);
                        }

                        unset($handleDatas);
                    }

                }

                unset($formContentDatas,$config,$hyperwindowField);
            }
        }

        //化验单超窗
        $annexWhere = new Where();
        $annexWhere->equalTo('is_del',0)
            ->equalTo('item_id',$item_id)
            ->greaterThan('collect_date',0);
        if(!empty($patient_id)) $annexWhere->equalTo('patient_id',$patient_id);
        if(!empty($checktime_id)) $annexWhere->in('checktime_id',$checktime_id);
        $changeData = $this->LocalService()->itemPatientworkannex->fetchAll([
            'where'=>$annexWhere,
            'columns'=>['patient_id','checktime_id','form_id','itemsig_id','category_id','collect_date','item_id'],
            'group'=>['patient_id','checktime_id','form_id']
        ]);
        if(!empty($changeData)){
            //化验单表单备注字段
            $formField = $this->LocalService()->itemFormField->fetchCol('form_id',"item_id = $item_id and var_name = 'CHECKREMARK' and is_del = 0");
            $formField = array_flip($formField);

            foreach($changeData as $v){

                $collectDate = strtotime($v['collect_date']);

                //时间格式有误数据无需判断
                if($collectDate == '1970-01-01') continue;

                $start_time = $date[$v['patient_id'].'-'.$v['checktime_id']]['plan_start_date'];

                $end_time = $date[$v['patient_id'].'-'.$v['checktime_id']]['plan_end_date'];

                if($collectDate >= $start_time && $collectDate <= $end_time){
                    continue;
                }

                if($collectDate < $start_time){
                    $diff = ($collectDate / 86400) - ($start_time / 86400);
                    $arr['exceedswindow_days'] = $diff > 0 ? ceil($diff) : floor($diff);
                }
                //采集时间大于时间窗开始时间
                if($collectDate > $end_time) {
                    $diff = ($collectDate/86400) - ($end_time/86400);
                    $arr['exceedswindow_days'] = $diff > 0 ? ceil($diff) : floor($diff);
                }

                $arr['item_id'] = $v['item_id'];
                $arr['itemsig_id'] = $v['itemsig_id'];
                $arr['patient_id'] = $v['patient_id'];
                $arr['checktime_id'] = $v['checktime_id'];
                $arr['form_id'] = $v['form_id'];
                $arr['field_id'] = $v['category_id'];
                $arr['data_type'] = 2;
                $arr['content_id'] = $v['formcontent_id'];
                $arr['start_time'] = $start_time;
                $arr['end_time'] = $end_time;
                $arr['data_time'] = $collectDate;
                $arr['form_order'] = 1;
                $arr['notes'] = '';
                //化验单表单查询是否有备注
                $patientFormContent = $this->LocalService()->patientFormContent->fetchOne([
                    'where'=>['patient_id'=>$v['patient_id'],'checktime_id'=>$v['checktime_id'],'form_id'=>$v['form_id'],'is_del'=>0],
                    'columns'=>['id','data']
                ]);
                if(!empty($patientFormContent)){
                    $info = json_decode($patientFormContent['data'],true);
                    if(isset($info[$formField[$v['form_id']]]) && !empty($info[$formField[$v['form_id']]])){
                        $arr['notes'] = $info[$formField[$v['form_id']]];
                    }
                }

                $this->LocalService()->projectExceedswindow->insert($arr);
            }
        }

        return true;
    }
}