<?php

namespace Application\Service\DB\Project;

use Interop\Container\ContainerInterface;
use Application\Service\Extension\MiniAppWs\App;
use Application\Service\Extension\Laminas;
use Laminas\Db\Sql\Expression;

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

    public function getChangeReference($where = []) {
        $changeReferenceDatas = [];
        $changeReferenceData = $this->fetchAll([
            'where' => [
                'is_del' => 0,
                'item_id' => $where['item_id'],
                'itemsig_id' => $where['itemsig_id'],
                'form_id' => $where['form_id'],
                'category_id' => $where['category_id'],
            ],//.' AND item_checkname_id = '.$where['item_checkname_id']
            'columns' => [
//                'id',
                'item_id',
                'itemsig_id',
                'form_id',
                'item_checkname_id',
                'category_id',
                'report_type',
                'reference_range_max',
                'reference_range_min',
                'patient_id',
                'max_symbol',
                'min_symbol'
            ],
        ]);
        !empty($changeReferenceData) && $changeReferenceDatas = array_column($changeReferenceData, null,'item_checkname_id');
        $itemFormInfo = $this->LocalService()->itemForm->fetchOne(['where'=> [
            'is_del' => 0,
            'id' => $where['form_id'],
        ]]);
        if (!empty($itemFormInfo) && !empty($itemFormInfo['checklist_id'])){
            $itemCheckNameData = $this->LocalService()->itemCheckname->fetchAll(['where'=> [
                'is_del' => 0,
                'category_id' => $itemFormInfo['checklist_id'],
                'item_id' => $where['item_id'],
            ]]);
            $report_type = $this->LocalService()->dictionaryCheckcategory->getOneFieldVal('report_type',[
                'is_del' => 0,
                'id' => $itemFormInfo['checklist_id'],
            ]);
            if (!empty($itemCheckNameData)){
                foreach ($itemCheckNameData as $itemCheckNameDatum){
                    $arr['form_id'] = $itemFormInfo['id'];
                    $arr['reference_range_max'] = $itemCheckNameDatum['max_val'];
                    $arr['reference_range_min'] = $itemCheckNameDatum['min_val'];
                    $arr['item_checkname_id'] = $itemCheckNameDatum['id'];
                    $arr['checkname_id'] = $itemCheckNameDatum['checkname_id'];
                    $arr['itemsig_id'] = $where['itemsig_id'];
                    $arr['report_type'] = $report_type;
                    $arr['max_symbol'] = '';
                    if(!empty($itemCheckNameDatum['max_symbol'])){
                        if($itemCheckNameDatum['max_symbol'] == 1){
                            $arr['max_symbol'] = '>';
                        }
                        if($itemCheckNameDatum['max_symbol'] == 2){
                            $arr['max_symbol'] = '>=';
                        }
                    }
                    $arr['min_symbol'] = '';
                    if(!empty($itemCheckNameDatum['min_symbol'])){
                        if($itemCheckNameDatum['min_symbol'] == 1){
                            $arr['min_symbol'] = '<';
                        }
                        if($itemCheckNameDatum['min_symbol'] == 2){
                            $arr['min_symbol'] = '<=';
                        }
                    }
                    if (!isset($changeReferenceDatas[$itemCheckNameDatum['id']])){
                        $changeReferenceDatas[$itemCheckNameDatum['id']] = $arr;
                    }
                }
            }

        }
        $changeReferenceDatas = array_merge($changeReferenceDatas);
        return $changeReferenceDatas;
    }

    public function setChangeReference($data = []) {
        $item_id = $data[0]['item_id'];
        $itemsig_id = $data[0]['itemsig_id'];
        $form_id = $data[0]['form_id'];
        $category_id = $data[0]['category_id'];
        $changeReferenceDatas = [];
        $changeReferenceData = $this->fetchAll([
            'where' => [
                'is_del' => 0,
                'item_id' => $item_id,
                'itemsig_id' => $itemsig_id,
                'form_id' => $form_id,
                'category_id' => $category_id,
            ],
        ]);
        if (!empty($changeReferenceData)){
            foreach ($changeReferenceData as $changeReferenceDatum) {
                $key  = $changeReferenceDatum['item_id'].'-'.$changeReferenceDatum['itemsig_id'].'-'.$changeReferenceDatum['form_id'].'-'.$changeReferenceDatum['category_id'].'-'.$changeReferenceDatum['item_checkname_id'];
                if (!isset($changeReferenceDatas[$key])){
                    $changeReferenceDatas[$key] = $changeReferenceDatum;
                }

            }
        }
        if (!empty($data)){
            foreach ($data as $dataK=>$dataV) {
                if (empty($dataV['lock_state'])) continue;
                $key  = $dataV['item_id'].'-'.$dataV['itemsig_id'].'-'.$dataV['form_id'].'-'.$dataV['category_id'].'-'.$dataV['item_checkname_id'];
                $arr = [
                    'item_id' => $dataV['item_id'],
                    'itemsig_id' => $dataV['itemsig_id'],
                    'form_id' => $dataV['form_id'],
                    'item_checkname_id' => $dataV['item_checkname_id'],
                    'category_id' => $dataV['category_id'],
                    'report_type' => $dataV['report_type'],
                    'patient_id' => $dataV['patient_id'],
                    'collect_date' => strtotime($dataV['collect_date']),
                    'reference_range_max' => $dataV['reference_range_max'],
                    'reference_range_min' => $dataV['reference_range_min'],
                    'max_symbol' => $dataV['max_symbol'],
                    'min_symbol' => $dataV['min_symbol'],
                ];
                if (isset($changeReferenceDatas[$key])){
                    if (($dataV['max_symbol'] == $changeReferenceDatas[$key]['max_symbol']) && ($dataV['min_symbol'] == $changeReferenceDatas[$key]['min_symbol']) && ($dataV['reference_range_max'] == $changeReferenceDatas[$key]['reference_range_max']) && ($dataV['reference_range_min'] == $changeReferenceDatas[$key]['reference_range_min'])){
                         continue;
                    }
                    $arr['id'] = $changeReferenceDatas[$key]['id'];
                }
                $this->save($arr);
            }
        }


    }

    public function dateTimes($timeString = '',$formatType='Y-m-d'){
        if (!empty($timeString)) {
            $pattern = "/(\d+)[\/-](\d+)[\/-](\d+)/";
            preg_match($pattern, $timeString, $matches);

            if (!empty($matches)) {
                $year = isset($matches[1])?$matches[1]:0;
                $month = isset($matches[2])?$matches[2]:0;
                $day = isset($matches[3])?$matches[3]:0;
                if (empty($year) || empty($month) || empty($day) ) {
                    return '';
                }

                if (!is_numeric($year) || strlen($year) > 4  || $year > date('Y')) return '';
                if (!is_numeric($month) || strlen($month) > 2  || $month > 12) return '';

                $t = date('t', strtotime($year.'-'.$month));
                if (strlen($day) > 2) {
                    $day = substr($day, 0, 2);
                }
                if ($day > $t) {
                    $day = substr($day, 0, 1);
                }

                $dayTime = "$year-$month-$day";
                $date = \DateTime::createFromFormat($formatType, $dayTime);
                $formattedTime = $date ? $date->format($formatType) : '';
                return $formattedTime;
            }else{
                return '';
            }
        }else{
            return '';
        }
    }
}