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

use Application\Service\Extension\Helper\ArrayHelper;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Where;


class PatientWorkCount 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 patientWorkcountInsert($item_id = 94){
        if(empty($item_id)) return false;
        //受试者
        $patientWhere['where'] = [
            'is_del' => 0,
            'item_id' => $item_id,
        ];

        $patientWhere['columns'] = ['id','patient_name','patient_number','item_id','itemsig_id'];
        $patientData = $this->LocalService()->patient->fetchAll($patientWhere);
        if (empty($patientData)) return false;
        $resultDel = $this->LocalService()->patientWorkCount->delete([
            'item_id' => $item_id,
        ]);

        $patientIdArr = array_column($patientData,'id');
        //检查点
        $itemChecktimeWhere['where'] = (new Where())->nest()
                                                        ->equalTo('is_del', 0)
                                                        ->or
                                                        ->nest()
                                                            ->equalTo('is_del', 2)
                                                            ->in('patient_id', $patientIdArr)
                                                        ->unnest()
                                                    ->unnest()
                                                    ->equalTo('item_id', $item_id);
        $itemChecktimeWhere['columns'] = ['id','check_name','check_order','is_del','is_skip','patient_id','patientchecktime_id'];
        $itemChecktimeData = $this->LocalService()->itemChecktime->fetchAll($itemChecktimeWhere);
        $itemCheckcontentData = [];
        if (!empty($itemChecktimeData)){
            $itemChecktimeIdArr = array_column($itemChecktimeData,'id');
            $itemPatientchecktimeWhere = [
                'where'=>[
                    'checktime_id' =>$itemChecktimeIdArr,
                    'patient_id'=>$patientIdArr,
                    'is_skip'=>1,
                    'is_del'=>0,
                ],
                'columns'=>[
                    'id',
                    'item_id',
                    'patient_id',
                    'checktime_id',
                    'itemsig_id',
                ],
            ];

            //是否跳过===yikeen_item_patientchecktime
            $itemPatientchecktimeData = $this->LocalService()->itemPatientchecktime->fetchAll($itemPatientchecktimeWhere);
            if (!empty($itemPatientchecktimeData)){
                foreach ($itemChecktimeData as $itemChecktimeDataKey=>$itemChecktimeDataValue) {
                    if (in_array($itemChecktimeDataValue,array_column($itemPatientchecktimeData,'checktime_id'))){
                        unset($itemChecktimeData[$itemChecktimeDataKey]);
                    }

                }
            }

            if (!empty($itemChecktimeData)){
                $itemChecktimeIds = implode(',',array_column($itemChecktimeData,'id'));
                $itemChecktimeDatas = ArrayHelper::index($itemChecktimeData, 'id');

                //检查点设置-研究内容管理==yikeen_item_checkcontent
                $itemCheckcontentWhere['where'] = [
                    'is_del' => 0,
                    'check_id' => array_column($itemChecktimeData,'id'),
                    'item_id' => $item_id,
                ];
                $itemCheckcontentWhere['columns'] = ['id','check_id','item_id'];
                $itemCheckcontentData = $this->LocalService()->itemCheckcontent->fetchAll($itemCheckcontentWhere);
                if (!empty($itemCheckcontentData)){
                    foreach ($itemCheckcontentData as $itemCheckcontentDataKey=>&$itemCheckcontentDataDataValue) {
                        $itemCheckcontentDataDataValue['patient_id'] = isset($itemChecktimeDatas[$itemCheckcontentDataDataValue['check_id']])?$itemChecktimeDatas[$itemCheckcontentDataDataValue['check_id']]['patient_id']:0;
                        $itemCheckcontentDataDataValue['check_is_del'] = isset($itemChecktimeDatas[$itemCheckcontentDataDataValue['check_id']])?$itemChecktimeDatas[$itemCheckcontentDataDataValue['check_id']]['is_del']:0;
                    }
                }

                //受试者检查点工作内容表===计划外===yikeen_item_patientcheckcontent
                $patientchecktimeIdArr = array_filter(array_column($itemChecktimeData,'patientchecktime_id','id'));
                if (!empty($patientchecktimeIdArr)){
                    $itemPatientcheckcontentWhere = [
                        'where'=>[
                            'patientchecktime_id' =>$patientchecktimeIdArr,
                            'patient_id'=>$patientIdArr,
                            'item_id'=>$item_id,
                            'is_del'=>0,
                        ],
                        'columns'=>[
                            'itemPatientcheckcontent_id'=>'id',
                            'item_id',
                            'patient_id',
                            'itemsig_id',
                            'patientchecktime_id',

                        ],
                    ];
                    $itemPatientcheckcontentData = $this->LocalService()->itemPatientcheckcontent->fetchAll($itemPatientcheckcontentWhere);
                    if (!empty($itemPatientcheckcontentData)){
                        foreach ($itemPatientcheckcontentData as $itemPatientcheckcontentDataKey=>&$itemPatientcheckcontentDataValue) {
                            $itemPatientcheckcontentDataValue['check_id'] = 0;
                            $itemPatientcheckcontentDataValue['check_is_del'] = 2;
                            $check_id = array_search($itemPatientcheckcontentDataValue['patientchecktime_id'],$patientchecktimeIdArr);
                            !empty($check_id) && $itemPatientcheckcontentDataValue['check_id'] = $check_id;
                        }
                        $itemCheckcontentData = array_merge($itemCheckcontentData,$itemPatientcheckcontentData);

                    }

                }
            }

        }

        //已完成的工作===yikeen_item_patient_form
        empty($patientIdArr) && $patientIdArr = 0;
        $patientFormWhere = [
            'where'=>['patient_id'=>$patientIdArr,'is_del'=>0,'is_complete'=>1],
            'columns'=>['item_id','itemsig_id','patient_id'],
        ];
        $itemPatientFormData = $this->LocalService()->patientForm->fetchAll($patientFormWhere);
        $itemPatientFormDatas = [];
        foreach ($itemPatientFormData as $itemPatientFormDataKey=>$itemPatientFormDataValue){
            $key = $itemPatientFormDataValue['item_id'].'-'.$itemPatientFormDataValue['itemsig_id'].'-'.$itemPatientFormDataValue['patient_id'];
            if (isset($itemPatientFormDatas[$key])){
                $itemPatientFormDatas[$key] =  $itemPatientFormDatas[$key]+1;
            }else{
                $itemPatientFormDatas[$key] =  1;

            }
        }

        foreach ($patientData as $patientDataKey=>&$patientDataValue){
            $patientDataValue['work_count'] = count($itemCheckcontentData);
            $patientDataValue['itemsig_name'] = '';
            $patientDataValue['work_complete_count'] = 0;
            $patientDataValue['plan'] = 0;
            $patientDataValue['patient_number_name'] = '';
            if (!empty($itemCheckcontentData)){
                foreach ($itemCheckcontentData as $itemCheckcontentDataKeys=>$itemCheckcontentDataDataValues) {
                    if ($itemCheckcontentDataDataValues['check_is_del'] == 2 ){
                        if($patientDataValue['id'] == $itemCheckcontentDataDataValues['patient_id']){
                            $patientDataValue['plan'] = 1;
                        } else{
                            $patientDataValue['work_count'] = $patientDataValue['work_count']-1;
                        }

                    }
                }
            }
            $patientCompleteKey = $patientDataValue['item_id'].'-'.$patientDataValue['itemsig_id'].'-'.$patientDataValue['id'];
            isset($itemPatientFormDatas[$patientCompleteKey]) &&  $patientDataValue['work_complete_count'] = $itemPatientFormDatas[$patientCompleteKey];
            $itemSigninfo = $this->LocalService()->itemSignatory->itemSigninfo($patientDataValue['itemsig_id']);
            if (!empty($itemSigninfo)){
                $itemsig_number = !empty($itemSigninfo[0]['number'])?'【'.$itemSigninfo[0]['number'].'】':'';
                $patientDataValue['itemsig_name'] = !empty($itemSigninfo[0]['info_name'])?$itemsig_number.$itemSigninfo[0]['info_name']:$itemsig_number.'';
            }
            !empty($patientDataValue['patient_number']) && $patientDataValue['patient_number_name'] = '【'.$patientDataValue['patient_number'].'】';
            !empty($patientDataValue['patient_name']) && $patientDataValue['patient_number_name'] .= $patientDataValue['patient_name'];

        }
//        echo '<pre>';print_r($patientData);die;

        foreach ($patientData as $patientDatum) {
            $patientDatum['patient_id'] = $patientDatum['id'];
            $patientDatum['is_plan'] = $patientDatum['plan'];
            unset($patientDatum['id']);
            unset($patientDatum['plan']);
            unset($patientDatum['patient_name']);
            unset($patientDatum['patient_number']);
            unset($patientDatum['patient_number_name']);
            unset($patientDatum['itemsig_name']);
            $result = $this->LocalService()->patientWorkCount->save($patientDatum);

        }
        return true;
    }

    //质疑总数
    public function questionUpdate($item_id = 1085){
        $ErrorData = $this->LocalService()->patientFormLogicError->fetchAll(['where'=> [
            'is_del' => 0,
            'item_id' => $item_id,
        ]]);
        $update = [];
        if(!empty($ErrorData)){
            $ErrorDatas = ArrayHelper::index($ErrorData, 'id',['patient_id']);
            $patientWorkCountData = $this->LocalService()->patientWorkCount->fetchAll(['where'=> [
                'is_del' => 0,
                'item_id' => $item_id,
            ]]);
            foreach ($patientWorkCountData as $patientWorkCountDataKey=>$patientWorkCountDataValue) {
                if ($ErrorDatas[$patientWorkCountDataValue['patient_id']]){
                    $update[$patientWorkCountDataKey]['id'] = $patientWorkCountDataValue['id'];
                    $update[$patientWorkCountDataKey]['patient_id'] = $patientWorkCountDataValue['patient_id'];
                    $update[$patientWorkCountDataKey]['question_count'] = count($ErrorDatas[$patientWorkCountDataValue['patient_id']]);
                }
            }
            if(!empty($update)){
                foreach ($update as $updateValue) {
                    $result = $this->LocalService()->patientWorkCount->save($updateValue);
                }
            }
        }
        return true;
    }

    //处理完成质疑
    public function questionClearUpdate($whereData = []){
        //$whereData['clear_question_count'] 为1时，处理完成; 为-1时新增未完成
        if (empty($whereData) || empty($whereData['patient_id']) || empty($whereData['clear_question_count'])) return false;
        $wherePatientWorkCount['where'] = [
            'is_del' => 0,
            'patient_id' => $whereData['patient_id'],
        ];
        !empty($whereData['item_id']) && isset($whereData['item_id']) && $wherePatientWorkCount['where']['item_id'] = $whereData['item_id'];
        $patientWorkCountInfo = $this->LocalService()->patientWorkCount->fetchOne($wherePatientWorkCount);
        if (empty($patientWorkCountInfo))  return false;
        if ($patientWorkCountInfo['clear_question_count'] > $patientWorkCountInfo['work_count']){
            //质疑数不能大于质疑总数
            return false;
        }
        $update['id'] = $patientWorkCountInfo['id'];
        $update['clear_question_count'] = $patientWorkCountInfo['clear_question_count'] + $whereData['clear_question_count'];
        $resultQuestion = $this->LocalService()->patientWorkCount->save($update);
        return true;
    }

    //审核and复核数
    public function approveUpdate($whereData = []){
        if (empty($whereData) || empty($whereData['patient_id']) || empty($whereData['approve_type'])) return false;
        $wherePatientWorkCount['where'] = [
            'is_del' => 0,
            'patient_id' => $whereData['patient_id'],
        ];
        !empty($whereData['item_id']) && isset($whereData['item_id']) && $wherePatientWorkCount['where']['item_id'] = $whereData['item_id'];
        $patientWorkCountInfo = $this->LocalService()->patientWorkCount->fetchOne($wherePatientWorkCount);
        if (empty($patientWorkCountInfo))  return false;
        $update['id'] = $patientWorkCountInfo['id'];
        if($whereData['approve_type'] == 1){
            //审核数据
            $update['approve_count'] = $patientWorkCountInfo['approve_count'] + 1;
        }else if($whereData['approve_type'] == 2){
            //复核数据
            $update['confirm_approve_count'] = $patientWorkCountInfo['confirm_approve_count'] + 1;
        }
        $resultApprove = $this->LocalService()->patientWorkCount->save($update);
        return true;
    }


}