<?php
declare(strict_types=1);

namespace app\controller;

use think\App;
use think\facade\Request;
use think\response\Json;
use app\model\PatientAuxiliaryDiagnosis;
use app\controller\Cdss;
use think\facade\Db;

/**
 * 患者辅助诊疗控制器
 * Class PatientAuxiliary
 * @package app\controller
 */
class PatientAuxiliary extends CommonTwoController
{
    /**
     * CDSS控制器实例
     * @var Cdss
     */
    protected $cdss;

    /**
     * 构造函数
     * @param App $app 应用实例
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->cdss = new Cdss($app);
    }

    /**
     * 保存患者辅助诊疗信息
     * @return Json
     */
    public function savePatientAuxiliaryInfo(): Json
    {
        // 获取请求参数
        $params = $this->request->param();
        
        // 设置默认值
        $params = array_merge([
            'ZYH' => '',
            'ZSZZ' => '',
            'name' => '',
            'tag' => '',
            'XB' => '',
            'NL' => 0,
            'document' => '',
            'docter' => '',
            'YGDM' => '',
            'KSDM' => ''
        ], $params);

        // 参数验证
        $validate = validate([
            'ZYH' => 'require|number', // 只验证住院号必填
        ]);

        if (!$validate->check($params)) {
            return $this->_json_error($validate->getError());
        }

        // 准备基础数据
        $baseData = [
            'name' => $params['name'],
            'tag' => $params['tag'],
            'zszz' => $params['ZSZZ'],
            'xb' => $params['XB'],
            'nl' => intval($params['NL']),
            'document' => $params['document'],
            'docter' => $params['docter'],
            'ygdm' => $params['YGDM'],
            'ksdm' => $params['KSDM']
        ];

        try {
            // 1. 辅助诊疗 - 只要有zszz和性别年龄就调用
            if (!empty($params['ZSZZ']) && !empty($params['XB']) && !empty($params['NL'])) {
                try {
                    // 从主诉症状中提取关键词
                    $mainSymptoms = '';
                    $symptomKeywords = Db::table('jm_cdss_symptom_keywords')
                        ->column('keyword');
                        
                    foreach ($symptomKeywords as $keyword) {
                        // 确保keyword是字符串类型
                        $keyword = (string)$keyword;
                        // 确保ZSZZ是字符串类型
                        $zszz = (string)$params['ZSZZ'];
                        
                        if (stripos($zszz, $keyword) !== false) {
                            if ($mainSymptoms === '') {
                                $mainSymptoms = $keyword;
                            } else {
                                $mainSymptoms .= ',' . $keyword;
                            }
                        }
                    }

                    // 如果提取到了症状关键词,才调用辅助诊疗
                    if (!empty($mainSymptoms)) {
                        $auxiliaryResult = $this->cdss->getSymptomAboutDisease(
                            $mainSymptoms,  // 使用提取的症状关键词
                            $params['NL'],
                            $params['XB'] == '男' ? 2 : 1
                        );
                        
                        if (!empty($auxiliaryResult)) {
                            $data = array_merge($baseData, [
                                'content' => json_encode($auxiliaryResult, JSON_UNESCAPED_UNICODE)
                            ]);
                            PatientAuxiliaryDiagnosis::updateOrInsert(
                                (string)$params['ZYH'],
                                PatientAuxiliaryDiagnosis::TAG_AUXILIARY,
                                $data
                            );
                        }
                    }
                } catch (\Exception $e) {
                    return $this->_json_error('辅助诊疗调用失败: ' . $e->getMessage());
                }
            }

            // 2. 知识库 - 需要name和tag
            if ($params['name'] && $params['tag']) {
                try {
                    // 调用detail方法
                    $response = $this->cdss->detail([
                        'name' => $params['name'],
                        'tag' => $params['tag']
                    ]);
                    
                    // 从Json响应中获取数据
                    $knowledgeResult = $response->getData();
                    
                    if (!empty($knowledgeResult)) {
                        $data = array_merge($baseData, [
                            'content' => json_encode($knowledgeResult, JSON_UNESCAPED_UNICODE)
                        ]);
                        PatientAuxiliaryDiagnosis::updateOrInsert(
                            (string)$params['ZYH'],
                            PatientAuxiliaryDiagnosis::TAG_KNOWLEDGE,
                            $data
                        );
                    }
                } catch (\Exception $e) {
                    return $this->_json_error('知识库调用失败: ' . $e->getMessage());
                }
            }

            // 3. 医嘱审核 - 需要name和性别
            $hasReviewResult = false;
            if ($params['name'] && $params['XB']) {
                $gender = stripos($params['XB'], '男') !== false ? 1 : 2;
                try {
                    $reviewResult = $this->cdss->yzEamine([
                        'name' => $params['name'],
                        'gender' => $gender
                    ]);
                    
                    if (!empty($reviewResult)) {
                        $data = array_merge($baseData, [
                            'content' => json_encode($reviewResult, JSON_UNESCAPED_UNICODE)
                        ]);
                        PatientAuxiliaryDiagnosis::updateOrInsert(
                            (string)$params['ZYH'],
                            PatientAuxiliaryDiagnosis::TAG_REVIEW,
                            $data
                        );
                        $hasReviewResult = true;
                    }
                } catch (\Exception $e) {
                    return $this->_json_error('医嘱审核调用失败: ' . $e->getMessage());
                }
            }
            
            // 检查辅助诊疗结果
            $hasAuxiliaryResult = !empty($auxiliaryResult) && count($auxiliaryResult) > 0;
            
            // 检查知识库结果 - detail()返回的是Json对象
            
            $hasKnowledgeResult = !empty($knowledgeResult) && count($knowledgeResult) > 0;
            
            
           

            // 返回结果 - 任何一个匹配就设置req=1
            return $this->_json_succ(
                ['req' => ($hasAuxiliaryResult || $hasKnowledgeResult || $hasReviewResult) ? 1 : 0],
                0,
                '保存成功'
            );
        } catch (\Exception $e) {
            return $this->_json_error('保存失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取患者辅助诊疗信息
     * @return Json
     */
    public function getPatientAuxiliaryInfo(): Json
    {
        // 获取住院号
        $zyh = $this->request->param('zyh');
        if (!$zyh) {
            return $this->_json_error('住院号不能为空');
        }

        try {
            // 获取该住院号的所有记录
            $records = PatientAuxiliaryDiagnosis::where('zyh', $zyh)->select()->toArray();
            
            // 整理返回数据
            $result = [];
            foreach ($records as $record) {
                $result[] = [
                    'tag' => $record['tag'],  // auxiliary/knowledge/review
                    'name' => $record['name'],
                    'content' => json_decode($record['content'], true), // 解码JSON字符串为数组
                    'xb' => $record['xb'],
                    'nl' => $record['nl'],
                    'document' => $record['document'],
                    'docter' => $record['docter'],
                    'ygdm' => $record['ygdm'],
                    'ksdm' => $record['ksdm'],
                    'create_time' => $record['create_time'],
                    'update_time' => $record['update_time']
                ];
            }

            return $this->_json_succ($result);
        } catch (\Exception $e) {
            return $this->_json_error('获取失败: ' . $e->getMessage());
        }
    }
} 