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

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


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


    /**
     * Notes: 删除真实数据
     * return int 受影响的行数
     */
    public function delete($where){
        return $this->tableGateway->delete($where);
    }

    public function updateWorkChecktime($where = []){
        if (empty($where)){
            echo '参数不正确';die;
        }
        $wheres = [
            'is_del' => 0,
            'item_id' => explode(',', $where['item_id']),
        ];
        if (isset($where['patient_id']) && !empty($where['patient_id'])){
            $wheres['patient_id'] = explode(',', $where['patient_id']);
        }
        if (isset($where['itemsig_id']) && !empty($where['itemsig_id'])){
            $wheres['itemsig_id'] = explode(',', $where['itemsig_id']);
        }
        $patientChecktimeWhere = [
            'where'=>$wheres,

        ];
        $patientChecktimeListEdcData = $this->LocalService()->patientChecktimeListEdc->fetchAll($patientChecktimeWhere);
        $patientWorkCountData = $this->LocalService()->patientWorkCountEdc->fetchAll($patientChecktimeWhere);
        $itemcheckNameArr = $this->LocalService()->itemChecktime->fetchCol('check_name',[
            'item_id' => $where['item_id'],
            new Operator('is_del', Operator::OP_NE, 1),
        ]);

        $newPatientCheckFormCount = [];
        $newPatientWorkCount = [];
        if (!empty($patientChecktimeListEdcData)){
            $patientCheckFormCountData = $this->patientCheckFormCount($patientChecktimeListEdcData,$itemcheckNameArr);
            $patientCheckFormCount = $patientCheckFormCountData['temp'];
//            echo '<pre>';print_r($patientCheckFormCount);die;
            if (!empty($patientCheckFormCount)){
                foreach ($patientChecktimeListEdcData as $patientChecktimeEdcK=>$patientChecktimeEdcV){
                    $item_checktime_list = [];
                    !empty($patientChecktimeEdcV['item_checktime_list']) && $item_checktime_list = json_decode($patientChecktimeEdcV['item_checktime_list'],true);
                    if (!empty($item_checktime_list)){
                        $work_count = 0;
                        $work_complete_count = 0;
                        $listFlag = 0;
                        foreach ($item_checktime_list as $oldChecktimeK=>&$oldChecktimeV) {

                            if (isset($patientCheckFormCount[$patientChecktimeEdcV['patient_id']][$oldChecktimeV['id']])){
                                $newPatientCheckFormCount = $patientCheckFormCount[$patientChecktimeEdcV['patient_id']][$oldChecktimeV['id']];
                                $oldChecktimeV['count'] = $newPatientCheckFormCount['count'];
                                if (isset($newPatientCheckFormCount['form_ids']) && !empty($newPatientCheckFormCount['form_ids'])){
                                    $form_id_arr = array_unique(explode(',',$newPatientCheckFormCount['form_ids']));
                                    $oldChecktimeV['form_ids'] = implode(',',$form_id_arr);
                                }else{
                                    $oldChecktimeV['form_ids'] = '';
                                }
                                if (isset($oldChecktimeV['is_complete'])){
                                    if ($oldChecktimeV['is_complete'] > $oldChecktimeV['count']){
                                        $oldChecktimeV['is_complete'] = $oldChecktimeV['count'];
                                    }
                                }else{
                                    $oldChecktimeV['is_complete'] = 0;
                                }
                                $listFlag = 1;

                            }else{
                                if ($oldChecktimeV['check_name'] == 'ae' && !isset($oldChecktimeV['is_complete'])){
                                    $oldChecktimeV['is_complete'] = 0;
                                    $listFlag = 1;

                                }
                                if ($oldChecktimeV['check_name'] == 'sae' && !isset($oldChecktimeV['is_complete'])){
                                    $oldChecktimeV['is_complete'] = 0;
                                    $listFlag = 1;

                                }
                            }
                            $work_count = $work_count+$oldChecktimeV['count'];
                            $work_complete_count = $work_complete_count+$oldChecktimeV['is_complete'];



                        }
                        $newPatientWorkCount[$patientChecktimeEdcV['patient_id']]['work_count'] = $work_count;
                        $newPatientWorkCount[$patientChecktimeEdcV['patient_id']]['work_complete_count'] = $work_complete_count;

                        $oldChecktimeV['item_checktime_list'] = json_encode($item_checktime_list);
                        $ChecktimeListEdc = [
                            'item_checktime_list'=>$oldChecktimeV['item_checktime_list'],
                            'update_time'=>$oldChecktimeV['update_time'],
                            'update_user_id'=>$oldChecktimeV['update_user_id'],
                        ];

                        if (!empty($listFlag)){
                            $resultChecktime = $this->LocalService()->patientChecktimeListEdc->update($ChecktimeListEdc, [
                                'is_del' => 0,
                                'id' => $patientChecktimeEdcV['id'],
                            ]);
                        }
                    }

                }

            }
        }


        if (!empty($patientWorkCountData)){
            foreach ($patientWorkCountData as $patientWorkCountDataK=>$patientWorkCountDataV){
                if (isset($newPatientWorkCount[$patientWorkCountDataV['patient_id']])){
                    $workCount = $newPatientWorkCount[$patientWorkCountDataV['patient_id']];
                    $update = [];
                    if ($patientWorkCountDataV['work_count'] != $workCount['work_count'] || $patientWorkCountDataV['work_complete_count'] != $workCount['work_complete_count']){
                        $update = [
                            'work_count'=>$workCount['work_count'],
                            'work_complete_count'=>$workCount['work_complete_count'],
                            'update_user_id'=>$patientWorkCountDataV['update_user_id'],
                            'update_time'=>$patientWorkCountDataV['update_time'],
                        ];
//                        echo '<pre>';print_r($update);die;
                        $resultCount = $this->LocalService()->patientWorkCountEdc->update($update, [
                            'is_del' => 0,
                            'id' => $patientWorkCountDataV['id'],
                        ]);
                    }
                }
            }
        }
        return true;

    }

//每个受试者检查点下总数
    public function patientCheckFormCount($patientChecktimeListData = [],$itemcheckNameArr = []){
        $newPatientChecktime = [];
        $temp = [];
        $item_id = 0;
        $aeAndsae = [];
        foreach ($patientChecktimeListData as $itemChecktimeK=>$itemChecktimeV) {
            $item_id = $itemChecktimeV['item_id'];
            $item_checktime_list = [];
            if (!empty($itemChecktimeV['item_checktime_list'])){
                $itemChecktimeList = json_decode($itemChecktimeV['item_checktime_list'],true);
                $checktimeIdArr = array_column($itemChecktimeList,'id');
                $checktimeNameArr = array_column($itemChecktimeList,'check_name');
//                $checktimeCountArr = array_column($itemChecktimeList,'count');
                $aeAndsaeCount = 0;
                if (in_array('ae',$checktimeNameArr)){

                    $aeAndsaeCount ++;
                }
                if (in_array('sae',$checktimeNameArr)){
                    $aeAndsaeCount ++;
                }
                $newPatientChecktime[$itemChecktimeV['patient_id']] = !empty($checktimeIdArr)?array_flip($checktimeIdArr):[];
                $aeAndsae[$itemChecktimeV['patient_id']] = $aeAndsaeCount;

            }
        }
//        echo '<pre>';print_r($aeAndsae);die;
        if (!empty($newPatientChecktime)){
            //项目下所有的表单
            $itemFormWhere = [
                'where'=>[
                    'item_id'=>$item_id,
                    'is_del'=>0,
                ],
                'columns'=>[
                    'id',
                    'name',
                    'item_id',
                    'group_id',
                    'except_checktime',

                ],
            ];
            $itemFormIdData = $this->LocalService()->itemForm->fetchAll($itemFormWhere);


            $formIdArr = array_column($itemFormIdData,'id');
            $form = array_column($itemFormIdData,null,'id');
            $itemCheckcontentWhere = [
                'where'=>[
                    'check_id'=>array_keys($itemcheckNameArr),
                    'item_id'=>$item_id,
                    'form_id'=>$formIdArr,//表单未删除的
                    'is_del'=>0,
                ],
                'columns'=>[
                    'count'=>new Expression('count(*)'),
                    'form_ids'=>new Expression('GROUP_CONCAT(form_id)'),
                    'id',
                    'check_id',
                    'item_id',
                    'form_id',
                ],
                'group' => ['check_id'],

            ];
            $itemCheckcontentData = $this->LocalService()->itemCheckcontent->fetchAll($itemCheckcontentWhere);

            if(!empty($itemCheckcontentData)){
                foreach ($itemCheckcontentData as $contentK => $contentV)
                {
                    $formArr = explode(',',$contentV['form_ids']);

                    if (!empty($formArr)){
                        foreach ($formArr as $formK => $formV){
                            if (isset($form[$formV])){
                                if(!empty($form[$formV]['except_checktime'])  && $form[$formV]['group_id'] == 4){
                                    if(in_array($contentV['check_id'],explode(',',$form[$formV]['except_checktime']))){
                                        $itemCheckcontentData[$contentK]['count'] -= 1;
                                        unset($formArr[$formK]);
                                        continue;
                                    }
                                }
                            }

                        }
                        $itemCheckcontentData[$contentK]['form_ids'] = implode(',',$formArr);
                    }

                }


                $itemCheckcontentDatas = array_column($itemCheckcontentData,null,'check_id');

                foreach ($newPatientChecktime as $itemPatientId => &$itemChecktimeDatum) {
                    $itemChecktimeDatum['count'] = 0;
                    foreach ($itemChecktimeDatum as $checktimeId=> $checktimeV){
                        $itemChecktimeDatum['form_ids'] = '';
                        if (isset($itemCheckcontentDatas[$checktimeId])){

                            $itemChecktimeDatum[$checktimeId] = $itemChecktimeDatum['count'] = $itemCheckcontentDatas[$checktimeId]['count'];
                            $itemChecktimeDatum['form_ids'] = $itemCheckcontentDatas[$checktimeId]['form_ids'];
                            $whereData = [
                                'count'=>$itemChecktimeDatum[$checktimeId],
                                'checktime_id'=>$checktimeId,
                                'item_id'=>$item_id,
                                'patient_id'=>$itemPatientId,
                                'form_ids'=>$itemCheckcontentDatas[$checktimeId]['form_ids'],
                            ];
                            $itemChecktimeCountData = $this->itemChecktimeCount($whereData);

                            $temp[$itemPatientId][$checktimeId]['count'] = $itemChecktimeCountData['count'];
                            $temp[$itemPatientId][$checktimeId]['count_Y'] = $itemChecktimeDatum[$checktimeId];
                            $temp[$itemPatientId][$checktimeId]['form_ids'] = $itemChecktimeCountData['form_ids'];
                            $temp[$itemPatientId][$checktimeId]['checktime_id'] = $checktimeId;
                            $temp[$itemPatientId][$checktimeId]['patient_id'] = $itemPatientId;
                            $temp[$itemPatientId][$checktimeId]['item_id'] = $item_id;
                            $temp[$itemPatientId][$checktimeId]['count_Relation'] = $itemChecktimeCountData['count_Relation'];



                        }
                    }

                }

            }




        }

        return ['temp'=>$temp,'aeAndsae'=>$aeAndsae];
//        echo '<pre>';print_r($newPatientChecktime);die;


    }

    //处理工作总数
    public function itemChecktimeCount($whereData = []){
        $whereData['count_Relation'] = 0;
        if (!empty($whereData['form_ids'])){
            $FormRelationwhere['where'] = [
                'is_del' => 0,
                'relation_form_id' => $whereData['form_ids'],
            ];
            $FormRelationwhere['columns'] = ['form_id','relation_form_id'];
            $FormRelationData=$this->LocalService()->itemFormRelation->fetchAll($FormRelationwhere);
            $formIdArr = explode(',',$whereData['form_ids']);
            $unsetArr = [];
            if (!empty($FormRelationData)){
                foreach ($FormRelationData as $FormRelationDataKey=>$FormRelationDataValue) {

                    $Pformwhere = [
                        'is_del' => 0,
                        'item_id' => $whereData['item_id'],
                        'patient_id' => $whereData['patient_id'],
                        'form_id' => $FormRelationDataValue['relation_form_id'],
                        'checktime_id' => $whereData['checktime_id'],
                    ];

                    $PatientformInfo=$this->LocalService()->itemPatientChecktimeForm->getCount($Pformwhere);

                    if (empty($PatientformInfo)){
                        $unsetArr[] = $FormRelationDataValue['relation_form_id'];
                    }
                }
            }
            $whereData['count'] = $whereData['count'] - count($unsetArr);
            $whereData['count_Relation'] = count($unsetArr);
            $newFormIdArr = array_diff($formIdArr,$unsetArr);
            !empty($newFormIdArr) && $whereData['form_ids']  = implode(',',$newFormIdArr);
        }
        return $whereData;
    }


}