<?php
declare (strict_types = 1);

namespace app\controller;

use think\response\Json;
use app\model\MedicalCalculator;
use app\model\MedicalQuestion;
use app\model\MedicalOption;

class MedicalCalculatorApiController extends CommonTwoController
{
    /**
     * 获取计算器列表
     */
    public function index(): Json
    {
        $page = $this->request->param('page/d', 1);
        $limit = $this->request->param('limit/d', 20);
        
        $calculators = MedicalCalculator::withoutField(['formula', 'results'])
            ->page($page, $limit)
            ->select();
        
        $total = MedicalCalculator::count();
        
        return $this->_json_succ([
            'list' => $calculators,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ]);
    }

    /**
     * 创建计算器
     */
    public function create(): Json
    {
        $data = $this->request->param();
        
        try {
            $calculator = new MedicalCalculator;
            $calculator->save($data);
            
            // 保存问题和选项
            if (!empty($data['questions'])) {
                $this->saveQuestions($calculator, $data['questions']);
            }
            
            return $this->_json_succ($calculator);
        } catch (\Exception $e) {
            return $this->_json_error('创建失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取计算器详情
     */
    public function show(string $id): Json
    {
        $calculator = MedicalCalculator::with([
            'questions' => function($query) {
                $query->with(['options' => function($query) {
                    $query->order('id', 'asc');
                }]);
            }
        ])->where('id', $id)->find();
        
        // 调试输出 - 使用 json_encode 转换为字符串
        trace('Calculator data: ' . json_encode($calculator, JSON_UNESCAPED_UNICODE));
        
        if ($calculator) {
            trace('Questions count: ' . $calculator->questions->count());
            if (!$calculator->questions->isEmpty()) {
                trace('First question options: ' . json_encode($calculator->questions[0]->options, JSON_UNESCAPED_UNICODE));
            }
        }
        
        if (empty($calculator)) {
            return $this->_json_error('计算器不存在');
        }

        return $this->_json_succ($calculator);
    }

    /**
     * 更新计算器
     */
    public function update(string $id): Json
    {
        $calculator = MedicalCalculator::find($id);
        if (!$calculator) {
            return $this->_json_error('计算器不存在');
        }

        $data = $this->request->param();
        try {
            $calculator->save($data);
            
            // 更新问题和选项
            if (isset($data['questions'])) {
                $this->saveQuestions($calculator, $data['questions']);
            }
            
            return $this->_json_succ($calculator);
        } catch (\Exception $e) {
            return $this->_json_error('更新失败: ' . $e->getMessage());
        }
    }

    /**
     * 删除计算器
     */
    public function destroy(string $id): Json
    {
        $calculator = MedicalCalculator::find($id);
        if (!$calculator) {
            return $this->_json_error('计算器不存在');
        }

        try {
            // 开启事务
            \think\facade\Db::startTrans();
            
            // 删除关联的选项
            MedicalOption::whereIn('medical_question_id', function($query) use ($id) {
                $query->name('medical_questions')->where('medical_calculator_id', $id)->field('id');
            })->delete();
            
            // 删除关联的问题
            MedicalQuestion::where('medical_calculator_id', $id)->delete();
            
            // 删除计算器
            $calculator->delete();
            
            \think\facade\Db::commit();
            return $this->_json_succ(null, '删除成功');
        } catch (\Exception $e) {
            \think\facade\Db::rollback();
            return $this->_json_error('删除失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取计算器问题
     */
    public function getQuestions(string $id): Json
    {
        $questions = MedicalQuestion::with(['options'])
            ->where('medical_calculator_id', $id)
            ->select();
            
        if ($questions->isEmpty()) {
            return $this->_json_error('未找到相关问题');
        }

        return $this->_json_succ($questions);
    }

    /**
     * 计算
     */
    public function calculate(string $id): Json
    {
        $calculator = MedicalCalculator::find($id);
        if (!$calculator) {
            return $this->_json_error('计算器不存在');
        }

        $inputs = $this->request->param();
        
        try {
            $result = $calculator->calculateResult($inputs);
            $interpretation = $calculator->getResultInterpretation($result);
            
            return $this->_json_succ([
                'value' => $result,
                'interpretation' => $interpretation
            ]);
        } catch (\Exception $e) {
            return $this->_json_error('计算失败: ' . $e->getMessage());
        }
    }

    /**
     * 保存问题和选项
     */
    protected function saveQuestions(MedicalCalculator $calculator, array $questions)
    {
        foreach ($questions as $questionData) {
            if (empty($questionData['question']) || empty($questionData['type'])) {
                continue;
            }

            $question = new MedicalQuestion([
                'medical_calculator_id' => $calculator->id,
                'question' => $questionData['question'],
                'variable_name' => $questionData['variable_name'] ?? '',
                'type' => $questionData['type'],
                'score' => $questionData['score'] ?? 0,
            ]);
            $question->save();

            // 保存选项
            if (!empty($questionData['options']) && is_array($questionData['options'])) {
                foreach ($questionData['options'] as $optionData) {
                    if (empty($optionData['content'])) {
                        continue;
                    }

                    $option = new MedicalOption([
                        'medical_question_id' => $question->id,
                        'content' => $optionData['content'],
                        'score' => $optionData['score'] ?? 0,
                    ]);
                    $option->save();
                }
            }
        }
    }
}