<?php

namespace Application\Controller\project;


use Application\Common\Ocr;
use Application\Common\StatusCode;
use Application\Form\item\patient\PatientFormModel;
use Application\Mvc\Controller\BasicController;
use Application\Service\DB\Dictionary\Form;
use Application\Service\DB\Dictionary\FormGroup;
use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\DataHelper;
use Application\Service\Extension\Helper\SDMHelper;
use Application\Service\Extension\Laminas;
use Laminas\Db\Sql\Predicate\IsNotNull;
use Laminas\Db\Sql\Predicate\Like;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\View\Model\JsonModel;
use Laminas\View\Model\ViewModel;

class SaeController extends BasicController
{
    /**
     * @return JsonModel|ViewModel
     */
    public function indexAction(): JsonModel
    {
        $MINI = $this->LocalService()->identity->getPlatform();
        $user_id = $this->LocalService()->identity->getId();

        $flag = 0;
        if (stripos($MINI, 'MINI') !== false) {
            $flag = 1;
        }

        $itemId = $this->params()->fromPost('item_id', 0);
        // 0为小项目, 1为大项目
        $type = $this->params()->fromPost('type', 0);

        $search =$_POST['search']?:'';

        $condition = ['id' => $itemId];

        $query = $this->LocalService()->itemInfo->fetchOne(['columns' => ['id', 'name', 'fid'], 'where' => $condition]);

        if (!isset($query['fid'])) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR,'参数不太对呀');
        }

        if (!empty($flag)) {
            $user_id = $this->LocalService()->signatoryUser->findsignatoryUser($user_id);
            $res = $this->LocalService()->itemSignatory->userRoleSignInfo($itemId, $user_id, $search,0,1) ?: [];

            foreach ($res as &$item) {
                $item['name'] = $item['info_name'];
                $item['signatory_id'] = $item['id'];
                unset($item['info_name']);
            }
        } else {
            $allSignatoryId = $this->LocalService()->itemSignatory->fetchAll([
                    'order' => ['order ASC'],
                    'columns' => ['id', 'signatory_id', 'number'],
                    'where' => ['item_id' => $query['fid']]]
            );

            $res = [];

            foreach ($allSignatoryId as $item) {
                if (
                    $childData = $this->LocalService()->signatoryInfo->fetchOne([
                        'columns' => ['info_name AS name'],
                        'where' => ['id' => $item['signatory_id']]
                    ])
                ) {
                    $childData['id'] = $itemId;
                    $childData['signatory_id'] = $item['id'];
                    $childData['name'] = "【{$item['number']}】{$childData['name']}";
                    $res[] = $childData;
                }
            }
        }

        return $this->RenderApiJson()->Success($res);
    }

    /**
     * @url xxx.com/v1/item/sae/patient
     * @return JsonModel
     */
    public function patientAction(): JsonModel
    {
        $itemsig_id = $this->params()->fromPost('itemsig_id');
        if($itemsig_id == 'undefined'){
            $itemsig_id = 0;
        }
        $item_id    = $this->params()->fromPost('item_id');
        if($item_id == 'undefined'){
            $item_id = 0;
        }
        $search_keyword = $this->params()->fromPost('search_keyword');  //受试者关键字 可以是编号 或者名称 或者缩写

        if(empty($itemsig_id) || empty($item_id)){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '项目或中心参数有误！');
        }

        $patient_where = [
            'is_del' => 0,
            'itemsig_id' => $itemsig_id,
            'item_id' => $item_id,
        ];

        if(!empty($search_keyword)){
            $patient_where[] = [
                'or' => [
                    new Like('patient_number', "%{$search_keyword}%"),
                    new Like('patient_name', "%{$search_keyword}%"),
                    new Like('patient_name_easy', "%{$search_keyword}%"),
                ]
            ];
        }

        $query = $this->LocalService()->patient->fetchAll([
            'where' =>$patient_where,
            'columns' => ['patient_name', 'id', 'patient_number'],
            'order' => ['patient_order','id']
        ]);

        //总sea数据量
        $total = 0;
        $no_sae_arr = [];
        if(!empty($query)){
            $form_id = $this->LocalService()->itemForm->getOneFieldVal('id',[
                'item_id' => $item_id,
                'group_id' => FormGroup::SAE,
                'is_del' => 0,
            ]);
            if(empty($form_id)){
                return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '请先设置该项目的SAE表单信息');
            }
            $all_total = $this->LocalService()->patientFormContent->getsaeNum([
                'item_id' => $item_id,
                'itemsig_id' => $itemsig_id,
                'form_id' => $form_id,
                'is_del' => 0,
            ]);
            $all_total = !empty($all_total) ? $all_total : [];
            $total = !empty($all_total[$item_id][$itemsig_id][$form_id]['allnum']) ? $all_total[$item_id][$itemsig_id][$form_id]['allnum'] : 0;
            foreach ($query as $queryKey=>&$item) {
                $patient_saenum = !empty($all_total[$item_id][$itemsig_id][$form_id][$item['id']]['patientnum']) ? $all_total[$item_id][$itemsig_id][$form_id][$item['id']]['patientnum']: 0;
                if($item['patient_number'] != ''){
                    $item['patient_name'] = "【".$item['patient_number']."】".$item['patient_name'];
                }
                $item = [
                    'id' => $item['id'],
                    'patient_name' => $item['patient_name']."(".$patient_saenum.")",
                ];
                $item['patient_saenum'] = $patient_saenum;
                if(empty($patient_saenum)){
                    $no_sae_arr[] = $item;
                    unset($query[$queryKey]);
                }
                unset($item['patient_number']);
            }
        }
        $query = array_values($query);
        if(!empty($no_sae_arr)){
            $query = !empty($query) ? array_merge($query,$no_sae_arr) : $no_sae_arr;
        }
        unset($no_sae_arr);
        //搜索表结构
        $serchFormFileData[] = [
            "type" => "Input",
            "label" => "关键字",
            "placeholder" => "请输入关键字",
            "prop" => "search_keyword",
        ];


        return $this->RenderApiJson()->Success($query,'',['total'=>$total,'SerchFormFileData'=>$serchFormFileData]);
    }


    /**
     * Notes: 获取SAE数量
     * @param
     * @return
     * @author haojinhua
     * @date 2024-09-06
     */
    public function saecountAction(){
        $itemsig_id = $this->params()->fromPost('itemsig_id');
        $item_id    = $this->params()->fromPost('item_id');

        if(empty($itemsig_id || empty($item_id))){
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '项目或中心参数有误！');
        }
        //总sea数据量
        $total = 0;
        $form_id = $this->LocalService()->itemForm->getOneFieldVal('id',[
            'item_id' => $item_id,
            'group_id' => FormGroup::SAE,
            'is_del' => 0,
        ]);
        if(!empty($form_id)){
            $all_total = $this->LocalService()->patientFormContent->getsaeNum([
                'item_id' => $item_id,
                'itemsig_id' => $itemsig_id,
                'form_id' => $form_id,
                'is_del' => 0,
            ]);
            $all_total = !empty($all_total) ? $all_total : [];
            $total = !empty($all_total[$item_id][$itemsig_id][$form_id]['allnum']) ? $all_total[$item_id][$itemsig_id][$form_id]['allnum'] : 0;
        }
        //获取cm的数据量
        $cm_total = call_user_func(fn() => $this->LocalService()->patientFormContentCm->getCount(['status' => 0, 'is_del' => 0, 'sign_id' => $itemsig_id, 'item_id' => $item_id]));
        //获取待判断AE的数据量
        $ae_total = $this->LocalService()->itemCsae->getCount([
            'is_del' => 0,
            'item_id' => $item_id,
            'itemsig_id' => $itemsig_id,
            'is_ae_sure' => 0,
            'is_normal_type' => 2,
        ]);
        return $this->RenderApiJson()->Success(['sae_total'=>$total,'cm_total'=>$cm_total,'ae_total'=>$ae_total]);
    }

    /**
     * @url http://xx.com/v1/item/sae/form
     * @return JsonModel
     * @throws \Exception
     */
    public function formAction(): JsonModel
    {
        $itemId = $this->params()->fromPost('item_id', 0);

        $saeForm = $this->LocalService()->itemForm->fetchOne([
            'columns' => ['id', 'type', 'show_type'],
            'where' => ['item_id' => $itemId, 'group_id' => FormGroup::SAE, 'is_del' => 0]
        ]);

        if (!$saeForm) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, "未发现SAE表单呢 /(ㄒoㄒ)/~~");
        }

        return $this->RenderApiJson()->Success(ArrayHelper::merge($this->LocalService()->itemForm->getPreviewConfig($saeForm['id']), [
            'type' => $saeForm['type'],
            'show_type' => $saeForm['show_type'] ?: 'right',
            'form_id' => $saeForm['id']
        ]));
    }

    public function generateFormData(array $postData)
    {
        foreach ($postData as $key => $datum) {
            if (stripos($datum, ',') !== false && stripos($datum, '[{') === false) {
                $postData[$key] = explode(',', $datum);
            }
        }

        return json_encode($postData);
    }


    public function oldcreateAction()
    {
        $request = $this->params();

        $postData = $this->generateFormData($this->params()->fromPost());

        if ($request->fromPost('id')) {
            Laminas::$serviceManager->patientFormContent->save([
                'id' => $request->fromPost('id'),
                'patient_id' => $this->validator->attributes['patient_id'],
                'form_id' => $this->validator->attributes['form_id'],
                'data' => $postData,
                'item_id' => $this->validator->attributes['item_id'],
                'itemsig_id' => $this->validator->attributes['itemsig_id'],
            ]);
        } else {
            Laminas::$serviceManager->patientFormContent->save([
                'patient_id' => $this->validator->attributes['patient_id'],
                'form_id' => $this->validator->attributes['form_id'],
                'data' => $postData,
                'item_id' => $this->validator->attributes['item_id'],
                'checktime_id' => 0,
                'itemsig_id' => $this->validator->attributes['itemsig_id'],
            ]);
        }

        return $this->RenderApiJson()->Success();
    }


    /**
     * Notes: SAE保存
     * User: lltyy
     * DateTime: 2025/3/25 10:06
     *
     * @return JsonModel
     * @throws \Exception
     */
    public function createAction(): JsonModel
    {
        $this->validator->attributes['checktime_id'] = 0;
        $this->validator->attach(
            [['patient_id', 'form_id', 'item_id', 'itemsig_id'], 'required'],
            [['patient_id', 'form_id', 'item_id', 'itemsig_id'], 'integer'],
            [[Form::ATTACH_SDTX], 'default', 'value' => '[]']
        );

        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        $model = new PatientFormModel($this->validator);

        $postData = DataHelper::handleFormData($this->validator->attributes, $this->params()->fromPost('form_id'));

        if (SDMHelper::app()->setAttributes(['form_id' => $this->params()->fromPost('form_id')])->form->getIsUsingScore() == 1) {
            throw new InvalidArgumentException('评分类表单不允许操作。');
        }

        $reason = $this->validator->attributes['reason'];
        if(!empty($reason)){
            $reason_res = [];
            $reason_datas = json_decode($reason,true);
            foreach ($reason_datas as $reason_data){
                $reason_res[] = [
                    'filed_id'=>$reason_data['filed_id'],
                    'modify_reason'=>$reason_data['modify_reason'],
                ];
            }
            unset($reason_datas);
            $reason = json_encode($reason_res,true);
        }
        unset($this->validator->attributes['reason']);
        $postData['note'] = $reason;

        if ($this->validator->attributes['id']) {
            $model->editForm($postData);
        } else {
            $insertId = $model->createForm($postData);
            return $this->RenderApiJson()->Success([
                'id' => $insertId
            ]);
        }

        return $this->RenderApiJson()->Success();
    }

    public function viewAction(): JsonModel
    {
        if($this->request->isPost()){
            $patient_id     = $this->params()->fromPost('patient_id');
            $form_id        = $this->params()->fromPost('form_id',0);

            //获取表单类型
            $addFalseMes = '';
            $formGroup = 0;
            if(!empty($form_id)){
                $formGroup = Laminas::$serviceManager->itemForm->getOneFieldVal('group_id',[
                    'id' => $this->validator->attributes['form_id'],
                ]);
            }
            //判断SAE表单操作时该患者是否已经开始访视【即判断是否存在有基点日期的访视期数据】
            if(!empty($patient_id) && $formGroup == FormGroup::SAE){
                $patientChecktimeCount = $this->LocalService()->itemPatientchecktime->getCount([
                    'is_del' => 0,
                    'patient_id' => $this->validator->attributes['patient_id'],
                    new Operator('anchor_date', Operator::OP_GT, 0),
                    NEW IsNotNull('anchor_date')
                ]);
                if(empty($patientChecktimeCount)){
                    $addFalseMes = '该患者的访视还未开始，不可增加SAE数据！';
                }
                unset($patientChecktimeCount);
            }
            unset($formGroup);

            $this->validator->setAttributes([
                'patient_id' => $patient_id,
                'form_id'    => $form_id,
            ]);

            $model = new PatientFormModel($this->validator);

            $form_count = $this->LocalService()->itemForm->getCount([
                'is_del' => 0,
                'id' => $form_id
            ]);
            if(empty($form_count)){
                return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, "无此表单信息！");
            }

            return $this->RenderApiJson()->Success($model->setDataHaveDel(true)->view(), 'OK', [
                'total' => $model->getFormMultiTotalCount(),
                'addFalseMes'=>$addFalseMes
            ]);
        }else{
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR,'非法请求');
        }

    }
}
