<?php
/**
 *
 * @author：llbjj
 * @DateTime：2024/6/27 11:19
 * @Description：
 *
 */

namespace Application\Controller\Temple;

use Application\Mvc\Controller\BasicController;
use Application\Service\Exceptions\InvalidArgumentException;
use Laminas\Db\Sql\Predicate\NotIn;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Mvc\Controller\AbstractActionController;
use Zend\Stdlib\ArrayUtils;

class ChecklistController extends BasicController
{
    public function siglistAction() {
        $type = $this->params()->fromPost('type', 0);

        $sigList = $this->LocalService()->ocrSigpatient->fetchAll([
            'where' => "pid = 0 and is_del = 0",
            'columns' => ['id', 'name'],
            'order' => ['number']
        ]);

        $patientList = $this->LocalService()->ocrSigpatient->fetchCol('pid', "is_del = 0 and have_status < 2 and pid > 0");
        $patientCountData = [];
        if(!empty($patientList)) {
            foreach($patientList as $pid) {
                $patientCountData[$pid]++;
            }
        }

        $checklistList = $this->LocalService()->templeChecklist->fetchAll([
            'where' => 'is_del = 0',
            'columns' => ['id', 'sig_id', 'patient_id', 'is_lock']
        ]);
        $checklistPatientCountData = [];
        $checklistNoLockPatientCountData = [];
        if(!empty($checklistList) ) {
            foreach($checklistList as &$checklist) {
                $checklistPatientCountData[$checklist['sig_id']][$checklist['patient_id']] = $checklist['patient_id'];

                if(!$checklist['is_lock'] && !$type ) $checklistNoLockPatientCountData[$checklist['sig_id']][$checklist['patient_id']] = $checklist['patient_id'];
            }
        }

        $result = [];
        if(!empty($sigList)) {
            foreach ($sigList as &$sig) {
                if(!$type) {
                    if( ! count( $checklistPatientCountData[$sig['id']] ?? [] )  ) continue;
                    $sig['patientCount'] = count( $checklistNoLockPatientCountData[$sig['id']] ?? [] ) . ' / ' .  count( $checklistPatientCountData[$sig['id']] ?? [] ) . ' / ' . ( $patientCountData[$sig['id']] ?? 0 );
                    $result[] = &$sig;
                }else if($type == 1) {
                    if(! ($patientCountData[$sig['id']] ?? 0)) continue;
                    $sig['patientCount'] = ( $patientCountData[$sig['id']] - count( $checklistPatientCountData[$sig['id']] ?? [] ) ) . ' / ' . $patientCountData[$sig['id']];
                    $result[] = &$sig;
                }

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

    public function patientlistAction() {
        $type = $this->params()->fromPost('type', 0);
        $sig_id = $this->params()->fromPost('sig_id', 0);

        $patientDatas = $this->LocalService()->ocrSigpatient->fetchAll([
           'where' => [
               'pid' => $sig_id,
               'is_del' => 0,
               new Operator('have_status', Operator::OP_LT, 2),
           ],
            'columns' => ['id', 'name', 'pid', 'number'],
            'order' => ['number']
        ]);

        $result = [];
        $annexCount = [];
        if(!empty($patientDatas)) {

            $templeChecklistList = $this->LocalService()->templeChecklist->fetchAll([
                'where' => [
                    'is_del' => 0,
                    'sig_id' => $sig_id,
                ],
                'columns' => ['id', 'annex_id', 'patient_id', 'is_lock']
            ]);

            $checklistData = [];

            if(!empty($templeChecklistList)) {
                foreach($templeChecklistList as $key => &$templeChecklist) {
                    $checklistData[$templeChecklist['patient_id']]['count'] ++;
                    if($templeChecklist['is_lock']) $checklistData[$templeChecklist['patient_id']]['lock_count'] ++;
                    else $checklistData[$templeChecklist['patient_id']]['nolock_count'] ++;
                }
            }

            if($type == 1) {
                $annexList = $this->LocalService()->templeAnnex->fetchAll([
                    'where' => "is_del = 0",
                    'columns' => ['id', 'patient_id']
                ]);

                if(!empty($annexList)) {
                    foreach($annexList as $annex) {
                        $annexCount[$annex['patient_id']]['annexCount'] ++;
                    }
                }
            }

            foreach($patientDatas as &$patientData) {
                $key = $patientData['number'];
                for ($i = 0; $i < 8 - strlen($patientData['number']); $i++ ) {
                    $key = '0' . $key;
                }
                $patientData = ArrayUtils::merge($patientData, $checklistData[$patientData['id']] ?? []);
                if( !$type ) {
                    if($patientData['nolock_count']) $result["0.{$key}"] = &$patientData;
                    else if($patientData['lock_count']) $result["1.{$key}"] = &$patientData;
                }else {
                    $patientData = ArrayUtils::merge($patientData, $annexCount[$patientData['id']] ?? []);
                    if( !$patientData['count'] ) {
                        if(!$patientData['annexCount']) $result["3.{$key}"] = &$patientData;
                        else $result["2.{$key}"] = &$patientData;
                    }
                }
            }

            ksort($result, SORT_NUMERIC );
        }

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

    public function annexlistAction() {
        $patient_id = $this->params()->fromPost('patient_id', 0);

        if(empty($patient_id)) return $this->RenderApiJson()->Success();

        $patientSex = $this->LocalService()->ocrSigpatient->getOneFieldVal('sex', ['id' => $patient_id]);
        $sex_code = $patientSex == 1 ? 'boy' : 'girl';

        $checklistAnnexIdArr = array_unique($this->LocalService()->templeChecklist->fetchCol('annex_id', ['patient_id' => $patient_id, 'is_del' => 0]));

        $annexWhere = ['patient_id' => $patient_id];
        if(!empty($checklistAnnexIdArr)) $annexWhere[] = new NotIn('id', $checklistAnnexIdArr);
        $annexList = $this->LocalService()->templeAnnex->fetchAll([
            'where' => $annexWhere,
            'columns' => [ 'id', 'annex_path', 'annex_name' ]
        ]);

        $keywordList = $this->LocalService()->ocrKeyword->fetchAll([
            'where' => "is_del = 0 and keyword_code in ('CRP', 'hscrp')",
            'columns' => [ 'category_name', 'keyword_code', 'keyword_name', 'keyword_unit', 'min' => "{$sex_code}_min", 'max' => "{$sex_code}_max"]
        ]);

        $keywordData = [];
        foreach($keywordList as &$keyword) {
            $keywordData[$keyword['keyword_code']] = &$keyword;
        }


        return $this->RenderApiJson()->Success([
            'annexlist' => $annexList,
            'keywordData' => $keywordData
        ]);
    }

    public function listAction() {
        $patient_id = $this->params()->fromPost('patient_id', 0);

        $patientSex = $this->LocalService()->ocrSigpatient->getOneFieldVal('sex', ['id' => $patient_id]);
        $sex_code = $patientSex == 1 ? 'boy' : 'girl';

        $keywordList = $this->LocalService()->ocrKeyword->fetchAll([
            'where' => "is_del = 0 and keyword_code in ('CRP', 'hscrp')",
            'columns' => [ 'category_name', 'keyword_code', 'keyword_name', 'keyword_unit', 'min' => "{$sex_code}_min", 'max' => "{$sex_code}_max"]
        ]);

        $keywordData = [];
        foreach($keywordList as &$keyword) {
            $keywordData[$keyword['keyword_code']] = &$keyword;
        }

        $result = $this->LocalService()->templeChecklist->fetchAll([
            'where' => ['is_del' => 0, 'patient_id' => $patient_id],
            'columns' => [ 'id', 'patient_id', 'sig_id', 'annex_id', 'raw_date', 'raw_code', 'raw_name', 'raw_result','raw_range','raw_unit', 'is_lock'],
            'order' => ['raw_date']
        ]);

        if(!empty($result)) {
            $templeAnnexIdData = array_column($result, 'annex_id');

            $annexNameData = $this->LocalService()->templeAnnex->fetchCol('annex_path', 'id in (' . implode(',', $templeAnnexIdData) . ')');


            foreach($result as &$checklist) {
                $checklist['annex_path'] = $annexNameData[$checklist['annex_id']] ?? '';
                if($checklist['is_lock'] != 1){
                    $checklist['raw_unit'] = $keywordData[$checklist['raw_code']]['keyword_unit'];
                    $checklist['raw_range'] = implode(' - ', array_filter([
                        $keywordData[$checklist['raw_code']]['min'],
                        $keywordData[$checklist['raw_code']]['max']
                    ], function($val) {
                        return strlen($val);
                    }));
                }
            }

        }

        return $this->RenderApiJson()->Success([
            'checklist' => $result,
            'keywordData' => $keywordData
        ]);
    }

    public function saveAction() {
        $checklistData = $this->params()->fromPost();
        $checklistData['is_lock'] = 1;  // 默认提交就锁定
        $this->LocalService()->templeChecklist->save($checklistData);

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

    public function lockAction() {
        $id = $this->params()->fromPost('id', 0);
        $is_lock = $this->params()->fromPost('is_lock', 1);
        if(!$id) throw new InvalidArgumentException('无效的操作信息！');

        $this->LocalService()->templeChecklist->updateField($id, 'is_lock', $is_lock);
        return $this->RenderApiJson()->Success();
    }

    public function deleteAction() {
        $id = $this->params()->fromPost('id', 0);

        if(!$id) throw new InvalidArgumentException('无效的操作信息！');

        $this->LocalService()->templeChecklist->upDelState("id = " . $id);
        return $this->RenderApiJson()->Success();
    }
}