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

namespace Application\Service\DB\Item;

use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\DB\Dictionary\ItemFormGroup;
use Application\Service\Extension\ErrorHandler;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Db\Sql\Where;

class Checktime extends \Application\Service\DB\AbstractDb
{
    /**
     * is_del = 9 是受试者状态检查点
     */
    const STATUS_OUT = 9;

    public function __construct($dbAdapter, ContainerInterface $container)
    {
        $this->tableName = 'yikeen_item_checktime';
        parent::__construct($dbAdapter, $container);
    }

    /**
     * @note 获取阶段检查点名称
     * @param $checktime_id
     * @return mixed|string
     */
    public function getStageAndChecktimeName($checktime_id) {
        $checktimeData = $this->fetchOne([
            'where' => [
                'id' => $checktime_id,
                'is_del' => 0,
            ],
            'columns' => ['check_name', 'stage_id']
        ]);

        $researchStageName = $this->LocalService()->itemResearchstage->getOneFieldVal('stage_name', [
            'id' => $checktimeData['stage_id'],
        ]);

        return $checktimeData['stage_id'] ? sprintf('【%s】%s', $researchStageName, $checktimeData['check_name']) : $checktimeData['check_name'];
    }

    /**
     * 获取受试者状态检查点id
     * @return false|mixed
     */
    public function getOutCheckTimeId($itemId)
    {
        return $this->fetchOne([
                'where' => ['item_id' => $itemId, 'check_name' => '试验总结检查点', 'is_del' => self::STATUS_OUT]
            ])['id'] ?? false;
    }

    /**
     * Notes: 受试者与检查点关系
     * @param int $item_id 项目id
     * @param int $itemsig_id 中心id
     * @param int $patient_id 受试者id
     * @param int $random_id 随机方案id（表单调用随机号后传参）
     * @return string
     */
    public function insertPatientchecktime($item_id,$itemsig_id,$patient_id,$random_id=0){
//        echo $item_id.','.$itemsig_id.','.$patient_id.','.$random_id;
        $whereItemPatientchecktime['where'] = [
            'is_del' => 0,
            'patient_id' => $patient_id,
            'item_id' => $item_id,
        ];
        !empty($itemsig_id) &&  $whereItemPatientchecktime['where']['itemsig_id'] = $itemsig_id;
        $itemPatientchecktimeInfo = $this->LocalService()->itemPatientchecktime->fetchOne($whereItemPatientchecktime);
        if (empty($random_id)){

            $whereChecktime['where'] = [
                'is_del' => 0,
                'type' => 1,
                'item_id' => $item_id
            ];
        }else{
            $whereChecktime['where'] = [
                'is_del' => 0,
                'item_id' => $item_id,
                'random_id' => $random_id
            ];
            $wherePatientchecktimeS['where'] = [
                'is_del' => 0,
                'item_id' => $item_id,
                'patient_id' => $patient_id,
            ];
            $itemPatientchecktimeData = $this->LocalService()->itemPatientchecktime->fetchAll($wherePatientchecktimeS);
        }

        $whereChecktime['columns'] = ['checktime_id'=>'id','researchstage_id'=>'stage_id','plan_start_date'=>'start_time','plan_end_date'=>'end_time','check_order'=>'check_order','anchor_id'=>'field_id','random_id'];
        $whereChecktime['order'] = 'check_order';
        $itemChecktimeData = $this->LocalService()->itemChecktime->fetchAll($whereChecktime);

        if (!empty($itemChecktimeData)){
            foreach ($itemChecktimeData as $k=>&$v) {
                if (empty($v['anchor_id'])){
                    unset($v['anchor_id']);
                }
                if (empty($v['researchstage_id'])){
                    unset($v['researchstage_id']);
                }

                if (empty($itemPatientchecktimeInfo) && empty($k) && empty($random_id)){
//                    empty($random_id) && $v['is_now_state'] = 1;
                    $v['is_now_state'] = 1;
                    $upPatient['patient_check_id'] = $v['checktime_id'];
                    $upPatient['patient_stage_id'] = $v['researchstage_id'];
                    $upPatient['id'] = $patient_id;
                    $result = $this->LocalService()->patient->save($upPatient);

                }
//
                $v['item_id'] = $item_id;
                $v['patient_id'] = $patient_id;
                $v['itemsig_id'] = $itemsig_id;
                if($random_id==0){
                    $itemPatientchecktimeId = $this->LocalService()->itemPatientchecktime->save($v);
                }else{
                    $this->InsertChecktime($v['checktime_id'],$item_id,$patient_id,$itemPatientchecktimeData,$random_id);
                }
//                if (!empty($itemPatientchecktimeId)) $this->LocalService()->log->saveFileLog($itemPatientchecktimeId,'itemPatientchecktime',$v,0,'暂无说明',$item_id);
            }
            $this->LocalService()->itemPatientchecktime->EditPatientChecktimeStatus($item_id,$patient_id);
        }

    }


    public function InsertChecktime($checktime_id,$item_id,$patient_id,$itemPatientchecktimeData,$random_id){
        //查询当前检查点的排序值
        $wherechecktime['where'] = [
            'is_del' => 0,
            'id' => $checktime_id
        ];
        $itemchecktimeInfo = $this->LocalService()->itemChecktime->fetchOne($wherechecktime);

        $time_unit='';
        switch ($itemchecktimeInfo['time_unit']){
            case 0 :$time_unit='day';break;
            case 1 :$time_unit='week';break;
            case 2 :$time_unit='month';break;
            case 3 :$time_unit='year';break;
        }
        foreach ($itemPatientchecktimeData as $key=>$val){
            if($itemchecktimeInfo['field_id']==$val['anchor_id']){
                $plan_start_date=strtotime(+($itemchecktimeInfo['start_time']-1).' '.$time_unit,$val['anchor_date']);
                $plan_end_date=strtotime(+($itemchecktimeInfo['end_time']-1).' '.$time_unit,$val['anchor_date']);
                $anchor_date = $val['anchor_date'];
            }else{
                $plan_start_date=$itemchecktimeInfo['start_time'];
                $plan_end_date=$itemchecktimeInfo['end_time'];
                $anchor_date ='';
            }
            //检查点添加
            $insert_arr=[
                'item_id' => $item_id,
                'patient_id' => $patient_id,
                'checktime_id' => $checktime_id,
                'itemsig_id' => $val['itemsig_id'],
                'random_id' => $random_id,//$itemchecktimeInfo['random_id'],
                'plan_start_date' => $plan_start_date,
                'plan_end_date' => $plan_end_date,
                'anchor_date' => $anchor_date,
                'is_del' => 0,
                'anchor_id'=>$itemchecktimeInfo['field_id'],
                'researchstage_id' => $itemchecktimeInfo['stage_id'],
                'check_order' => $itemchecktimeInfo['check_order'],
            ];
            $id = $this->LocalService()->itemPatientchecktime->insert($insert_arr);
            break;
        }


    }

    /**
     * Notes: 受试者与检查点关系
     * @param int $time 起始时间
     * @param int $patient_id 受试者id
     * @return string
     */
    public function updateTimePatientchecktime($time,$patient_id){
        $wherePatientattr['where'] = [
            'is_del' => 0,
            'id' => $patient_id,
        ];
        $patientInfo = $this->LocalService()->patient->fetchOne($wherePatientattr);
        if (!empty($patientInfo)){
            $whereItemPatientchecktime['where'] = [
                'is_del' => 0,
                'item_id' => $patientInfo['item_id'],
                'itemsig_id' => $patientInfo['itemsig_id'],
                'patient_id' => $patient_id
            ];
            $whereItemPatientchecktime['columns'] = ['id','plan_start_date','plan_end_date'];
            $itemPatientchecktimeData = $this->LocalService()->itemPatientchecktime->fetchAll($whereItemPatientchecktime);
            if (!empty($itemPatientchecktimeData)){
                foreach ($itemPatientchecktimeData as $k=>$v){
                    if (!empty($v['plan_end_date'])){
                        $v['plan_end_date'] = strtotime($v['plan_end_date'].' day',$time);
                    }else{
                        $v['plan_end_date'] = $time;
                    }
                    if (!empty($v['plan_start_date'])){
                        $v['plan_start_date'] = strtotime($v['plan_start_date'].' day',$time);
                    }else{
                        $v['plan_start_date'] = $time;
                    }
                    $result = $this->LocalService()->itemPatientchecktime->save($v);
                }
            }

        }

    }
    /**
     * Notes: 检查点添加同步yikeen_item_patientchecktime
     * @param int $checktime_id 检查点ID
     * @param int $item_id 项目ID
     * @return string
     */
    public function EditPatientChecktime($checktime_id,$item_id)
    {
        //查询当前检查点的排序值
        $wherechecktime['where'] = [
            'is_del' => 0,
            'id' => $checktime_id
        ];
        $itemchecktimeInfo = $this->LocalService()->itemChecktime->fetchOne($wherechecktime);

        //判断检查点的随机分组是否是默认的，如果是默认的则所有受试者添加，如果不是则该随机分组的受试者添加

        $randomType = $this->LocalService()->itemRandom->getOneFieldVal('type',['id'=>$itemchecktimeInfo['random_id']]);

        $patientWhere = ['is_del'=>0,'item_id'=>$item_id];

        if($randomType == 2){
            $patientWhere['random_id'] = $itemchecktimeInfo['random_id'];
        }

        $patientDatas = $this->LocalService()->patient->fetchCol('id',$patientWhere);

        //根据排序值去查询之前的检查点有没有脱离
        $wherePatientchecktime['where'] = [
            'is_del' => 0,
            'item_id' => $item_id
        ];
        $itemPatientchecktimeInfo = $this->LocalService()->itemPatientchecktime->fetchAll($wherePatientchecktime);
        $insert_data = [];
        $insert_arr = [];

        //受试者转状态情况下不添加检查点
        foreach ($itemPatientchecktimeInfo as $k => $v) {
            if(!isset($patientDatas[$v['patient_id']])) continue;
            if ($v['check_order'] < $itemchecktimeInfo['check_order']  && $v['anchor_id'] == $itemchecktimeInfo['field_id']) {
                //无脱离
                $insert_data[] = [
                    'patient_id' => $v['patient_id'], 'itemsig_id' => $v['itemsig_id'], 'leave_type' => null,
                    'random_code' => null, 'anchor_id' => $v['anchor_id'], 'anchor_date' => $v['anchor_date'],
                ];
            }
//            else if ($v['check_order'] < $itemchecktimeInfo['check_order'] && $v['leave_type'] != '') {
//                //有脱离
//                $insert_arr[] = [
//                    'leave_type' => $v['leave_type'], 'random_code' => $v['random_code'], 'patient_id' => $v['patient_id'],
//                    'itemsig_id' => $v['itemsig_id'], 'anchor_id' => $v['anchor_id'], 'anchor_date' => $v['anchor_date'],
//                ];
//            }
        }
        $insert_data = array_values($this->unique_2d_array_by_key($insert_data, 'patient_id'));
//        var_dump($insert_data);die;
        //没有脱离的数据
        if (!empty($insert_data && !empty($insert_arr))) {
            foreach ($insert_data as $k => $v) {
                foreach ($insert_arr as $key => $val) {
                    if ($v['patient_id'] == $val['patient_id']) {
                        unset($insert_data[$k]);
                    }
                }
            }
        }

        if (!empty($insert_data)) {
            $this->SaveChecktimeData(1,$insert_data,$item_id,$checktime_id,$itemchecktimeInfo,0);
        }

        //查询当前检查点下是否包含贯穿全程表单

//        if (!empty($insert_arr)) {
//            $this->SaveChecktimeData(1,$insert_arr,$item_id,$checktime_id,$itemchecktimeInfo,1);
//        }
//        $this->throughoutForm($item_id,$checktime_id);
    }

    /**
     * 新增检查点下包含贯穿全程表单【贯穿全程表单颜色与其他检查点一致，如果是关联表单需新增关联记录】
     * @param $item_id
     * @param $checktime_id
     * @return void
     */
    public function throughoutForm($item_id,$checktime_id,$formArr)
    {
        $patientchecktimeDatas = $this->LocalService()->itemPatientchecktime->fetchAll([
            'where'=>"item_id = $item_id and is_del = 0 and checktime_id = $checktime_id",
            'columns'=>['id','patient_id','itemsig_id','plan_start_date','plan_end_date'],
        ]);
        $patientchecktime = [];
        foreach($patientchecktimeDatas as $patient){
            $patientchecktime[$patient['patient_id']] = $patient;
        }

        if($formArr){
            //获取relation
            $relation = $this->LocalService()->itemFormRelation->fetchCol('relation_form_id',"is_del = 0 and relation_form_id in (".implode(',',$formArr).")");
            if($relation){
                foreach($relation as $form){
                    $association = $this->LocalService()->itemPatientChecktimeForm->fetchAll([
                        'where'=>"item_id = $item_id and is_del = 0 and form_id = $form",
                        'columns'=>['patient_id'],
                        'group'=>['patient_id']
                    ]);
                    $arr['form_id'] = $form;
                    $arr['checktime_id'] = $checktime_id;
                    $arr['item_id'] = $item_id;
                    $arr['is_del'] = 0;
                    foreach ($association as $k=>$v){
                        if(!isset($patientchecktime[$v['patient_id']])) continue;
                        $arr['itemsig_id'] = $patientchecktime[$v['patient_id']]['itemsig_id'];
                        $arr['patient_id'] = $v['patient_id'];
                        $this->LocalService()->itemPatientChecktimeForm->insert($arr);
                    }

//                    $patientContent = $this->LocalService()->patientForm->fetchAll([
//                        'where'=>"item_id = $item_id and is_del = 0 and form_id = $form",
//                        'columns'=>['patient_id','is_complete'],
//                        'group'=>['patient_id']
//                    ]);
//
//                    $content['form_id'] = $form;
//                    $content['item_id'] = $item_id;
//                    $content['checktime_id'] = $checktime_id;
//                    foreach($patientContent as $vv){
//                        if(!isset($patientchecktime[$vv['patient_id']])) continue;
//                        $content['itemsig_id'] = $patientchecktime[$v['patient_id']]['itemsig_id'];
//                        $content['patient_id'] = $vv['patient_id'];
//                        $content['is_complete'] = $vv['is_complete'];
//                        $content['start_at'] = $patientchecktime[$vv['patient_id']]['plan_start_date'];
//                        $content['end_at'] = $patientchecktime[$vv['patient_id']]['plan_end_date'];
//                        $content['patientchecktime_id'] = $patientchecktime[$vv['patient_id']]['id'];
//                        $this->LocalService()->patientForm->insert($content);
//                    }

                }
            }
        }
    }

    /**
     * Notes: 二维数组去重
     * @param int $_2d_array 二维数组
     * @param int $unique_key key
     * @return array
     */
    function unique_2d_array_by_key($_2d_array, $unique_key) {
        $tmp_key[] = array();
        foreach ($_2d_array as $key => &$item) {
            if ( is_array($item) && isset($item[$unique_key]) ) {
                if ( in_array($item[$unique_key], $tmp_key) ) {
                    unset($_2d_array[$key]);
                } else {
                    $tmp_key[] = $item[$unique_key];
                }
            }
        }
        return $_2d_array;
    }
    /**
     * Notes: 检查点添加/编辑同步yikeen_item_patientchecktime
     * @param string type 1 添加 2 修改
     * @param array $data 当前项目下受试者检查点数据
     * @param string $item_id 项目ID
     * @param string $checktime_id 检查点ID
     * @param array $itemchecktimeInfo 要添加或修改检查点的数据单条
     * @param string $is_del 删除状态
     * @return string
     */
    function SaveChecktimeData($type,$data,$item_id,$checktime_id,$itemchecktimeInfo,$is_del=0){
        $time_unit='';
        switch ($itemchecktimeInfo['time_unit']){
            case 0 :$time_unit='day';break;
            case 1 :$time_unit='week';break;
            case 2 :$time_unit='month';break;
            case 3 :$time_unit='year';break;
        }
        foreach ($data as $k=>$v){
            if($itemchecktimeInfo['field_id']==$v['anchor_id']){
                $plan_start_date=strtotime(+($itemchecktimeInfo['start_time']-1).' '.$time_unit,$v['anchor_date']);
                $plan_end_date=strtotime(+($itemchecktimeInfo['end_time']-1).' '.$time_unit,$v['anchor_date']);
            }else{
                $plan_start_date=$itemchecktimeInfo['start_time'];
                $plan_end_date=$itemchecktimeInfo['end_time'];
            }
            if($type==1){

                //检查点添加
                $insert_arr=[
                    'item_id' => $item_id,
                    'patient_id' => $v['patient_id'],
                    'checktime_id' => $checktime_id,
                    'itemsig_id' => $v['itemsig_id'],
                    'plan_start_date' => $plan_start_date,
                    'plan_end_date' => $plan_end_date,
                    'is_del' => $is_del,
                    'anchor_id'=>$itemchecktimeInfo['field_id'],
                    'anchor_date'=>$v['anchor_date'],
                    'researchstage_id' => $itemchecktimeInfo['stage_id'],
                    'check_order' => $itemchecktimeInfo['check_order'],
                    'leave_type' => $v['leave_type'],
                    'random_code' => $v['random_code'],

                ];
                $this->LocalService()->itemPatientchecktime->insert($insert_arr);
            }else if($type==2){
                //检查点编辑
                $update_arr=[
                    'plan_start_date' => $plan_start_date,
                    'plan_end_date' => $plan_end_date,
                    'anchor_id'=>$itemchecktimeInfo['field_id'],
                ];
                $this->LocalService()->itemPatientchecktime->update($update_arr,"item_id = ".$item_id.' and patient_id='.$v['patient_id'].' and checktime_id='.$checktime_id);
            }
        }
    }
    //检查点数据同步
    function ChecktimeAdd($new_item_id,$old_item_id){
        $yikeen = new \mysqli('localhost','root','root3306',"mc5");

        $yikeen->set_charset('utf8') or die('设置字符集失败：'.$yikeen->error);

        $sql='select * from oa_item_checktime where item_id='.$old_item_id.' and is_del=0';

        $result = $yikeen->query($sql);

        $ChecktimeDatas=[];

        while($row = $result->fetch_assoc())
        {
            $ChecktimeDatas[]=$row;
        }
        foreach ($ChecktimeDatas as $k=>$v){
            //研究阶段
            $content_sql='select id,e_sd_id,start_time,end_time,frequency,item_id,is_required,file_ids from oa_item_checkcontent where check_id='.$v['id'].' and is_del=0 and item_id='.$old_item_id;
            $content_result=$yikeen->query($content_sql);
            $content_row=$content_result->fetch_assoc();
            //表单
            $file_ids_arr=[];
            $form_id_arr=[];
            if($content_row['e_sd_id']>0){
                $form_sql='select id,form_id from oa_item_formvisitstage where id='.$content_row['e_sd_id'].' and is_del=0 and item_id='.$old_item_id;
                $form_result=$yikeen->query($form_sql);
                $form_row=$form_result->fetch_assoc();
                $form_id_arr=explode(',',$form_row['form_id']);
            }else{
                //化验类表单
                $file_ids_arr=explode(',',$content_row['file_ids']);
            }
            foreach ($form_id_arr as $kk=>$vv){
                $form_insert=[
                    'form_id'=>$vv,
                    'check_id'=>$v['id'],
                    'start_time'=>$content_row['start_time'],
                    'end_time'=>$content_row['end_time'],
                    'frequency'=>$content_row['frequency'],
                    'item_id'=>$new_item_id,
                    'is_required'=>$content_row['is_required'],
                    'type'=>1
                ];
                $this->LocalService()->itemCheckcontent->insert($form_insert);
            }

            if(!empty($file_ids_arr)){
                foreach ($file_ids_arr as $kkk=>$vvv){
                    $form_data=[
                        'form_id'=>$vvv,
                        'check_id'=>$v['id'],
                        'start_time'=>$content_row['start_time'],
                        'end_time'=>$content_row['end_time'],
                        'frequency'=>$content_row['frequency'],
                        'item_id'=>$new_item_id,
                        'is_required'=>$content_row['is_required'],
                        'type'=>2
                    ];
                    $this->LocalService()->itemCheckcontent->insert($form_data);
                }
            }
            $type='';
            if($v['flowcat_id']==0){
                $type=1;
            }else{
                $type=2;
            }
            $insert_arr=[
                'flowcat_id'=>$v['flowcat_id'],
                'stage_id'=>$v['stage_id'],
                'check_name'=>$v['check_name'],
                'check_start'=>$v['check_start'],
                'start_time'=>$v['start_time'],
                'time_unit'=>$v['time_unit'],
                'end_time'=>$v['end_time'],
                'content_num'=>$v['content_num'],
                'e_sd_num'=>$v['e_sd_num'],
                'file_num'=>$v['file_num'],
                'check_remak'=>$v['check_remak'],
                'formcontent_id'=>$v['formcontent_id'],
                'item_id'=>$new_item_id,
                'is_del'=>$v['is_del'],
                'check_order'=>$v['check_order'],
                'is_copy'=>$v['is_copy'],
                'random_id'=>'',
                'type'=>$type,
                'old_checktime_id'=>$v['id'],
                'field_id'=>$v['formcontent_id'],
            ];

            $result=$this->LocalService()->itemChecktime->insert($insert_arr);
            if(!empty($result)){
                $this->LocalService()->itemCheckcontent->update(['check_id'=>$result],'item_id='.$new_item_id.' and check_id='.$v['id']);
                $this->LocalService()->itemPatientchecktime->update(['checktime_id'=>$result],'item_id='.$new_item_id.' and checktime_id='.$v['id']);
                echo '<span style="color：green">'.$v['check_name'].'-'.'同步成功'.'<span>'.'<br>';
            }else{
                echo '<span style="color：red">'.$v['check_name'].'-'.'同步失败'.'<span>'.'<br>';
            }
        }
    }
    /**
     * Notes: 检查点复制yikeen_item_checktime
     * @param string old_item_id 要复制的项目ID
     * @param string new_item_id 新项目ID
     * @return string
     */
    public function CopyChecktime($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 参数不正确';
            }
        }

        $randomwhere['where']='is_del=0  and item_id='.$old_item_id;
        $randomwhere['columns']=['id','random_name'];
        $random = $this->LocalService()->itemRandom->fetchAll($randomwhere);
        $randomDatas = [];
        foreach($random as $k=>$v){
            $randomDatas[$v['id']] = $v;
        }

        $stagewhere['where']='is_del=0  and item_id='.$old_item_id;
        $stagewhere['columns']=['id','stage_name'];
        $stage = $this->LocalService()->itemResearchstage->fetchAll($stagewhere);
        $stageDatas = [];
        foreach($stage as $k=>$v){
            $stageDatas[$v['id']] = $v;
        }

        $new_randomwhere['where']='is_del=0  and item_id='.$new_item_id;
        $new_randomwhere['columns']=['id','random_name'];
        $new_random = $this->LocalService()->itemRandom->fetchAll($new_randomwhere);
        $newrandomDatas = [];
        foreach($new_random as $k=>$v){
            $newrandomDatas[$v['random_name']] = $v;
        }

        $new_stagewhere['where']='is_del=0  and item_id='.$new_item_id;
        $new_stagewhere['columns']=['id','stage_name'];
        $new_stage = $this->LocalService()->itemResearchstage->fetchAll($new_stagewhere);
        $newstageDatas = [];
        foreach($new_stage as $k=>$v){
            $newstageDatas[$v['stage_name']] = $v;
        }


        $where['where']='(is_del=0 || is_del = 9) and item_id='.$old_item_id;
        //检查点数据
        $ChecktimeDatas=$this->fetchAll($where);
        $versionData = [];
        if(!empty($ChecktimeDatas)){
            foreach ($ChecktimeDatas as $k=>$v){
                $insert_arr=[
                    'flowcat_id'=>$v['flowcat_id'],  'check_name'=>$v['check_name'],
                    'check_start'=>$v['check_start'], 'start_time'=>$v['start_time'], 'time_unit'=>$v['time_unit'],
                    'end_time'=>$v['end_time'], 'content_num'=>$v['content_num'], 'e_sd_num'=>$v['e_sd_num'],
                    'file_num'=>$v['file_num'], 'check_remak'=>$v['check_remak'], 'formcontent_id'=>$v['formcontent_id'],
                    'item_id'=>$new_item_id, 'is_del'=>$v['is_del'], 'check_order'=>$v['check_order'],
                    'is_copy'=>$v['is_copy'], 'field_id'=>$v['field_id'],'type'=>$v['type'],'is_skip'=>$v['is_skip']
                    ,'var_name'=>$v['var_name'],'is_isolate'=>$v['is_isolate']
                ];
                //分类ID
                $insert_arr['random_id'] = $newrandomDatas[$randomDatas[$v['random_id']]['random_name']]['id'];
                //阶段ID
                $insert_arr['stage_id'] = $newstageDatas[$stageDatas[$v['stage_id']]['stage_name']]['id'];

                $Checktime_id=$this->LocalService()->itemChecktime->insert($insert_arr);
                $versionData[$v['id']] = $Checktime_id;
                //表单Q
                $CheckContentwhere['where']='is_del=0 and check_id=' . $v['id'].' and item_id='.$old_item_id;
                $CheckContentDatas = $this->LocalService()->itemCheckcontent->fetchAll($CheckContentwhere);
                if(!empty($CheckContentDatas)){
                    foreach ($CheckContentDatas as $key=>$val){
                        $add_arr=[
                            'check_id'=>$Checktime_id, 'form_id'=>$val['form_id'], 'e_sd_id'=>$val['e_sd_id'],
                            'start_time'=>$val['start_time'], 'end_time'=>$val['end_time'], 'file_ids'=>$val['file_ids'],
                            'frequency'=>$val['frequency'], 'is_del'=>$val['is_del'], 'is_choose'=>$val['is_choose'],
                            'item_id'=>$new_item_id, 'is_required'=>$val['is_required'], 'time_unit'=>$val['time_unit'],
                            'annex_ids'=>$val['annex_ids'], 'order'=>$val['order'], 'is_hide'=>$val['is_hide'],'associated_ishide'=>$val['associated_ishide'],
                        ];
                        $res=$this->LocalService()->itemCheckcontent->insert($add_arr);
                    }
                }
            }
        }
        return $versionData;
    }

    /**
     * Notes:获取指定键值下的检查点信息
     * User: lltyy
     * DateTime: 2022/9/21 14:53
     *
     * @param $where //获取条件
     * @param array $columns //查询字段
     * @param array $order //排序
     * @param array $key_arr //键值数组【键值=>键值下数据类型（0 单笔 1 多笔）】
     * @return array
     */
    public function getChecktimeByKey($where,$columns=[],$order=[],$key_arr=[]){
        $datas = [];
        $where_cond = [
            'where'=>$where,
            'columns'=>$columns,
            'order'=>$order
        ];
        $checktimes = $this->fetchAll($where_cond);
        if(!empty($checktimes)){
            foreach($checktimes as $checktime){
                foreach($key_arr as $key=>$value_type){
                    $key_id = $checktime[$key];
                    if($value_type == 1){
                        $datas[$key][$key_id][] = $checktime;
                    }else{
                        $datas[$key][$key_id] = $checktime;
                    }
                }
            }
        }
        return $datas;
    }


    public function defaultchektime($item_id)
    {
        $new_arr=[
            'random_id'=>0, 'field_id'=>0, 'flowcat_id'=>0,
            'stage_id'=>0, 'item_id'=>$item_id, 'check_name'=>'试验总结检查点',
            'start_time'=>1, 'end_time'=>1,
            'time_unit'=>0, 'check_order'=>99999, 'check_remak'=>'',
            'is_copy'=>0,'is_skip'=>0,'is_del'=>9,'type'=>1
        ];
        $resultid = $this->insert($new_arr);
    }

    public function handlecheckcontent($params)
    {

        $arr = $params['arr'];
        $item_id = $params['item_id'];
        if(!empty($item_id)){
            $formwhere= [
                'is_del' => 0,
                'item_id' => $params['item_id']
            ];
            $FormDatas = $this->LocalService()->itemForm->fetchCol('group_id',$formwhere);
        }

        $routine = [];
        $special = [];
        $DS = []; //试验总结
        $RDG = []; //随机分组
        $SAE = [];//SAE类
        $WP = [];//贯穿全程类
        $AE = [];//AE类
        $other = [];
        $yz = [];
        $yz_identify = [];
        $routine_OCR = [];
        foreach($arr as $k=>$v){
            if(!isset($v['group_id'])){
                $v['group_id'] = $FormDatas[$v['form_id']];
            }
//            if($v['group_id'] == 1){
//                $DS[] = $v;
//            }elseif($v['group_id'] == 2){
//                $RDG[] = $v;
//            }elseif($v['group_id'] == 3){
//                $SAE[] = $v;
//            }elseif($v['group_id'] == 4){
//                $WP[] = $v;
//            }elseif($v['group_id'] == 5){
//                $AE[] = $v;
//            }elseif($v['group_id'] == 6){
//                $routine[] = $v;
//            }elseif($v['group_id'] == 7){
//                $special[] = $v;
//            }elseif($v['group_id'] == 8){
//                $yz[] = $v;
//            }elseif($v['group_id'] == 9){
//                $yz_identify[] = $v;
//            }elseif($v['group_id'] == 10){
//                $routine_OCR[] = $v;
//            }else{
//                $other[] = $v;
//            }
            $data[$v['group_id']][] = $v;

        }

//        $data[1] = $DS;
//        $data[2] = $RDG;
//        $data[3] = $SAE;
//        $data[4] = $WP;
//        $data[5] = $AE;
//        $data[6] = $routine;
//        $data[7] = $special;
//        $data[8] = $yz;
//        $data[9] = $yz_identify;
//        $data[10] = $routine_OCR;

        $group = $this->LocalService()->dictionaryFormGroup->fetchAll(['where'=>'is_del = 0','columns'=>['id'],'order'=>'order']);

        $formData = [];
        foreach($group as $k=>$v){
            if(!empty($data[$v['id']])){
                foreach($data[$v['id']] as $key=>$value){
                    $newArr[] = $value;
                }
            }

//            $formData[$k+1] = $data[$v['id']] ?: [];
        }

//        $newArr = array_merge($formData[1],$formData[2],$formData[3],$formData[4],$formData[5],$formData[6],$formData[7],$formData[8],$formData[9],$formData[10]);

        return $newArr;
    }

    public function getchecktimestatus(int $checktime_id)
    {
        $checktimeInfo = $this->LocalService()->itemChecktime->getOneFieldVal('patient_id',[
            'id' => $checktime_id,
            'is_del' => 0
        ]);

         return !empty($checktimeInfo) ? true : false;
    }
}