<?php
namespace Application\Service\DB\Admin;

use Application\Command\Swoole\Server\WebSocketCommand;
use Interop\Container\Containerinterface;
use Swoole\Coroutine\Http\Client;
use function Co\run;

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

    public function fillUkData($item_id)
    {
        $fieldType = [
            '2'=>'UK-UK-UK',
            '20'=>"UK-UK-UK UK:UK",
            '21'=>"UK-UK-UK UK:UK:UK",
            '22'=>"UK:UK",
            '23'=>"UK:UK:UK"
        ];
        $fieldData = $this->LocalService()->itemFormField->fetchAll(['where'=>"item_id = $item_id and type in (2,20,21,22,23) and is_del = 0",'columns'=>['id','form_id','type']]);

        if(empty($fieldData)) return false;
        $field = [];
        foreach($fieldData as $v){
            $field[$v['form_id']][] = $v;
        }
        $form = implode(',',array_unique(array_column($fieldData,'form_id')));
        $formContent = $this->LocalService()->patientFormContent->fetchCol('data',"is_del = 0 and form_id in ($form)");

        foreach($formContent as $key=>$value){
            $info = json_decode($value,true);
            $flag = false;
            foreach($field[$info['form_id']] as $v){
                if(isset($info[$v['id']]) && $info[$v['id']] == ''){
                    $flag = true;
                    $info[$v['id']] = $fieldType[$v['type']];
                }
            }
            if($flag == true) $this->LocalService()->patientFormContent->update(['data'=>json_encode($info,true)],['id'=>$key]);
        }


        $aeFormId = $this->LocalService()->itemForm->getOneFieldVal('id',"is_del = 0 and group_id = 5 and item_id = $item_id and id in ($form)");
        if(!empty($aeFormId)){
            $aeContent = $this->LocalService()->itemPatientAeContent->fetchCol('data',"item_id = $item_id and is_del = 0 and form_id = $aeFormId");
            foreach($aeContent as $key=>$value){
                $info = json_decode($value,true);
                $flag = false;
                foreach($field[$info['form_id']] as $v){
                    if(isset($info[$v['id']]) && $info[$v['id']] == ''){
                        $flag = true;
                        $info[$v['id']] = $fieldType[$v['type']];
                    }
                }
                if($flag == true) $this->LocalService()->itemPatientAeContent->update(['data'=>json_encode($info,true)],['id'=>$key]);
            }
        }
        return true;
    }


    public function formatDate($item_id)
    {
        $fieldData = $this->LocalService()->itemFormField->fetchAll(['where'=>"item_id = $item_id and type in (2,20,21,22,23) and is_del = 0",'columns'=>['id','form_id','type']]);

        $field = [];
        foreach($fieldData as $k=>$v){
            $field[$v['form_id']][] = $v;
        }
        $form = implode(',',array_unique(array_column($fieldData,'form_id')));

        $formContent = $this->LocalService()->patientFormContent->fetchCol('data',"item_id = $item_id and is_del = 0 and form_id in ($form)");
        foreach($formContent as $key=>$value){
            $info = json_decode($value,true);
            $flag = false;
            foreach($field[$info['form_id']] as $v){
                if(isset($info[$v['id']]) && $info[$v['id']] != ''){
                    $result = $this->normalizeTimeStringByType($info[$v['id']], $v['type']);
                    if(!empty($result)){
                        $flag = true;
                        $info[$v['id']] = $result;
                    }
                }
            }
            if($flag == true) $this->LocalService()->patientFormContent->update(['data'=>json_encode($info,true)],['id'=>$key]);
        }

        $aeFormId = $this->LocalService()->itemForm->getOneFieldVal('id',"is_del = 0 and group_id = 5 and item_id = $item_id and id in ($form)");
        if(!empty($aeFormId)){
            $aeContent = $this->LocalService()->itemPatientAeContent->fetchCol('data',"item_id = $item_id and is_del = 0 and form_id = $aeFormId");
            foreach($aeContent as $key=>$value){
                $info = json_decode($value,true);
                foreach($field[$info['form_id']] as $v){
                    if(isset($info[$v['id']]) && $info[$v['id']] != ''){
                        $result = $this->normalizeTimeStringByType($info[$v['id']], $v['type']);
                        if(!empty($result)){
                            $info[$v['id']] = $result;
                            $this->LocalService()->itemPatientAeContent->update(['data'=>json_encode($info,true)],['id'=>$key]);
                        }
                    }
                }


            }
        }

        echo "SUCCESS";die;
    }


    function normalizeTimeStringByType(string $time, int $type): string {
        $formatMap = [
            2  => 'Y-m-d',
            20 => 'Y-m-d H:i',
            21 => 'Y-m-d H:i:s',
            22 => 'H:i',
            23 => 'H:i:s',
        ];

        if (!isset($formatMap[$type])) {
            return '';
        }

        $targetFormat = $formatMap[$type];

        // 尝试直接格式化
        $dt = \DateTime::createFromFormat($targetFormat, $time);
        if ($dt instanceof \DateTime && $dt->format($targetFormat) === $time) {
            return $dt->format($targetFormat); // 已规范
        }

        // 使用正则补 0，例如 9:3:2 => 09:03:02
        $fixed = preg_replace_callback('/\b\d\b/', fn($m) => '0' . $m[0], $time);

        // 尝试修正后的时间
        $dt = \DateTime::createFromFormat($targetFormat, $fixed);
        if ($dt instanceof \DateTime) {
            return $dt->format($targetFormat);
        }

        return ''; // 非法时间，返回空
    }
}