<?php

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

namespace Application\Service\DB\Item;

use Application\Service\Extension\Helper\StringHelper;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\Operator;

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

    /**
     * Notes: 随机方案复制yikeen_item_random
     * @param string old_item_id 要复制的项目ID
     * @param string new_item_id 新项目ID
     * @return string
     */
    function CopyRandom($old_item_id,$new_item_id){
        if(empty($old_item_id)){
            return 'old_item_id 为空';
        }else{
            if(!is_numeric($old_item_id)){
                return 'old_item_id 参数不正确';
            }
        }
        if(empty($new_item_id)){
            return 'new_item_id 为空';
        }else{
            if(!is_numeric($new_item_id)){
                return 'new_item_id 参数不正确';
            }
        }
        $where['where']= [
            'is_del' => 0,
            'item_id' => $old_item_id,
        ];
        $RandomDatas=$this->fetchAll($where);
        if(!empty($RandomDatas)){
            foreach ($RandomDatas as $key=>$val) {
                $insert_arr = [
                    'flowcat_id' => $val['flowcat_id'],
                    'random_name' => $val['random_name'],
                    'random_start' => $val['random_start'],
                    'random_time' => $val['random_time'],
                    'time_unit' => $val['time_unit'],
                    'random_remak' => $val['random_remak'],
                    'is_del' => $val['is_del'],
                    'item_id' => $new_item_id,
                    'random_order' => $val['random_order'],
                    'type' => $val['type'],
                ];
                $result=$this->LocalService()->itemRandom->insert($insert_arr);
                $this->LocalService()->itemChecktime->update(['random_id'=>$result],[
                    'item_id' => $new_item_id,
                    'random_id' => $val['id'],
                ]);
            }
        }
    }


    /**
     * Notes : 更新受试者表入组日期
     * @param $item_id
     * @param $type 1==随机分组  2==基点日期
     * @param $time
     * @return bool
     * Author:唐伯虎不虎
     * Date:2024/5/15 9:48
     */
    public function ChangeRandomTime($patient_id,$item_id,$type,$time,$form_id = 0):bool
    {

        if(empty($patient_id) || empty($item_id) || empty($type) || empty($time)) return false;

        //查询受试者筛选号
        $patientInfo = $this->LocalService()->patient->fetchOne(['where'=> [
            'id'=>$patient_id,
            'is_del' => 0,
        ],'columns'=>['patient_number','joining_date']]);
        $oper_type = 1;
        $joining_type = ($type == 1) ? '随机分组' : '基点日期';
        $log_arr = ['patient_number'=>$patientInfo['patient_number'],'joining_date'=>$time,'joining_type'=>$joining_type];
        //查询当前项目是否有随机表单  有随机表单更新随机表单时间，无随机表单更新第二个基点日期的时间
        $is_rand = $this->LocalService()->itemForm->getOneFieldVal('id',"item_id = $item_id and is_del = 0 and group_id = 2");

        $RandFormContent = [];
        if(!empty($is_rand)){
            $RandFormContent =  $this->LocalService()->itemCheckcontent->fetchAll([
                'where'=> [
                    'form_id' => $is_rand,
                    'is_del' => 0,
                ],
                'columns'=>['form_id','item_id'],
                'group'=>['form_id']
            ]);
        }

        if(!empty($RandFormContent) && $type == 1){
            //随机日期表单
            $this->LocalService()->patient->update(['joining_date'=>$time,'joining_type'=>$type],['id'=>$patient_id]);
            //记录日志
            $this->LocalService()->log->saveFileLog($patient_id,'patient',$log_arr,$oper_type,'暂无说明',$item_id,'',['item_id'=>$item_id,'patientAttrData'=>[]]);
        }elseif(empty($RandFormContent) && $type == 2){

            //基点日期表单  判断当前提交的表单是否是第二个基点日期
            $BasicPoint = $this->_GetBasicPoint($item_id);

            if($BasicPoint != $form_id) return true;

            $this->LocalService()->patient->update(['joining_date'=>$time,'joining_type'=>$type],['id'=>$patient_id]);
            //记录日志
            $this->LocalService()->log->saveFileLog($patient_id,'patient',$log_arr,$oper_type,'暂无说明',$item_id,'',['item_id'=>$item_id,'patientAttrData'=>[]]);
        }
        return true;
    }

    function _GetBasicPoint($item_id)
    {
        $checktime = $this->LocalService()->itemChecktime->fetchAll(
            [
                'where' => [
                    'item_id' => $item_id,
                    'is_del' => 0,
                    new Operator('field_id', Operator::OP_NE, 0),
                ],
                'columns' => ['id','field_id'],
                'order' => 'check_order'
            ]
        );
        $field = array_unique(array_column($checktime,'field_id'));

        $field = array_values($field);

        //不存在多个基点日期则获取第一个
        if(isset($field[1])) {
            $field_id = $field[1];
        }else{
            $field_id = $field[0];
        }

        $form_id = $this->LocalService()->itemFormField->getOneFieldVal('form_id',[
            'id' => $field_id,
        ]);

        return (!$form_id) ? false : $form_id;
    }

    /**
     * Notes : 处理随机号历史数据
     * Author:唐伯虎不虎
     * Date:2024/5/20 13:48
     */
    public function handlehistorydata()
    {
        //tips：按项目处理，并记录对应的日志

        //查询所有副项目
        $itemDatas = $this->LocalService()->itemInfo->fetchAll(
            ['where'=> [
                'is_del' => 0,
                'is_mainitem' => 0,
                'status' => 0,
            ],'columns'=>['id','name']]
        );

        //查询有随机分组的项目
        $ishaveRand = $this->LocalService()->itemForm->fetchCol('item_id',"is_del = 0 and group_id = 2");

        $formField = $this->LocalService()->itemFormField->fetchCol('form_id',"is_del = 0 and var_name = 'RANDDAT'");

        $checkcontent = $this->LocalService()->itemCheckcontent->fetchAll([
            'where'=> [
                'form_id' => StringHelper::toArray($formField),
                'is_del' => 0,
            ],
            'columns'=>['form_id','item_id'],
            'group'=>['form_id']
        ]);

        $UseForm = [];
        foreach($checkcontent as $k=>$v){
            $UseForm[$v['form_id']] = $v['item_id'];
        }

        $formField = array_flip($formField);

        foreach($formField as $k=>$v){
            if(!isset($UseForm[$v])) unset($formField[$k]);
            if(!isset($ishaveRand[$k])) unset($formField[$k]);
        }



        //无随机分组的项目 == $itemDatas

        //查询受试者填写表单内容
//        $formidStr = implode(',',array_keys($ishaveRand));
        $formidStr = implode(',',array_keys($UseForm));

        $patientformcontentDatas = $this->LocalService()->patientFormContent->fetchAll([
            'where'=> [
                'is_del' => 0,
                'form_id' => StringHelper::toArray($formidStr),
            ],'columns'=>['id', 'item_id','patient_id', 'checktime_id','form_id', 'data','create_time']]
        );
        $patientrandDatas = [];
        foreach($patientformcontentDatas as $key=>$value)
        {
            $patientrandDatas[$value['form_id']][] = $value;
        }

        //step 1  处理随机分组数据，如果有随机时间就按照随机时间，没有随机事件按照添加时间

        foreach($UseForm as $k=>$v)
        {
            $rule = $this->LocalService()->itemForm->getPreviewConfig($k,true);

            $prop = $this->getprop($rule);

            //判断当前项目有无随机时间字段
            if(isset($formField[$k])){

                //查询随机时间
                foreach($patientrandDatas[$k] as $kk=>$vv){
                    $SourceData = json_decode($vv['data'],true);

                    if(!empty($SourceData[$prop])){
                        $this->ChangeRandomTime($vv['patient_id'],$vv['item_id'],1,strtotime($SourceData[$prop]));
                    }

                }
            }else{

                //查询添加时间 create_time
                foreach($patientrandDatas[$k] as $kk=>$vv){
                    $this->ChangeRandomTime($vv['patient_id'],$vv['item_id'],1,$vv['create_time']);
                }
            }
            unset($itemDatas[$v]);
        }


        //step 2 处理第二次基点日期添加为入组时间
        //查询锚点日期字段
        $anchorField = $this->LocalService()->itemFormField->fetchCol('form_id',"is_del = 0 and is_anchor = 1");
        $anchorFieldVar = $this->LocalService()->itemFormField->fetchCol('var_name',"is_del = 0 and is_anchor = 1");

        $anchorField = array_flip($anchorField);



        $haveBasicPoint = [];
        foreach ($itemDatas as $itemK => $itemV){
            $twoBasicPoint = $this->_GetBasicPoint($itemV['id']);

            if(!$twoBasicPoint) continue;
            //符合第二个基点日期的表单

            $haveBasicPoint[$twoBasicPoint]['form_id'] = $twoBasicPoint;

//            if(empty($anchorField[$twoBasicPoint]))  continue;
            $rule = $this->LocalService()->itemForm->getPreviewConfig($twoBasicPoint,true);


            $haveBasicPoint[$twoBasicPoint]['prop'] = $this->getnodefaultprop($rule,$anchorFieldVar[$anchorField[$twoBasicPoint]]);
        }

        if(!empty($haveBasicPoint)){
            $patientformcontentDatas = $this->LocalService()->patientFormContent->fetchAll([
                    'where'=> [
                        'is_del' => 0,
                        'form_id' => array_column($haveBasicPoint,'form_id'),
                    ],'columns'=>['id', 'item_id','patient_id', 'checktime_id','form_id', 'data','create_time']]
            );

            foreach($patientformcontentDatas as $basicK=>$basicV){

                $SourceData = json_decode($basicV['data'],true);

                $prop = $haveBasicPoint[$basicV['form_id']]['prop'];

                if(!empty($SourceData[$prop])) $this->ChangeRandomTime($basicV['patient_id'],$basicV['item_id'],2,strtotime($SourceData[$prop]),$basicV['form_id']);
            }
        }
        return "SUCCESS";
    }

    public function getprop($data)
    {
        foreach($data['config']['form'] as $k=>$v){
            if($v['var_name'] == 'RANDDAT'){
                return $v['prop'];
            }
        }
        return false;
    }



    public function getnodefaultprop($data,$var_name)
    {

        foreach($data['config'] as $k=>$v){
            if(is_numeric($k)){
                foreach($v as $childK =>$childV){
                    foreach($childV as $childKK =>$childVV){
                        if ($childVV['var_name'] == $var_name) {
                            return $childVV['prop'];
                        }
                    }
                }
            }else{
                foreach($v as $key=>$value){
                    if ($value['var_name'] == $var_name) {
                        return $value['prop'];
                    }
                }
            }
        }


        return false;
    }




}
