File size: 8,516 Bytes
a697439
35c394f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a697439
 
35c394f
 
a697439
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35c394f
 
 
5068b22
 
 
 
a697439
 
 
 
 
 
5068b22
 
 
a697439
 
 
 
 
 
 
5068b22
 
35c394f
5068b22
a697439
35c394f
 
 
 
a697439
35c394f
 
a697439
5068b22
 
 
35c394f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a697439
35c394f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5068b22
 
 
a697439
5068b22
 
35c394f
5068b22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a697439
5068b22
 
 
35c394f
 
 
 
 
5068b22
 
 
a697439
5068b22
 
35c394f
 
 
a697439
 
5068b22
35c394f
 
 
 
 
 
 
a697439
35c394f
 
 
 
 
 
 
 
 
 
 
 
 
a697439
35c394f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Radio,
  RadioGroup,
  FormControlLabel,
  TextField,
  Button,
  Alert,
  Collapse,
  Stack,
  Paper,
  Divider
} from '@mui/material';
import LightbulbIcon from '@mui/icons-material/Lightbulb';
import NavigateNextIcon from '@mui/icons-material/NavigateNext';
import axios from 'axios';

function Exercise({ exercise, onSubmit, onNextExercise, selectedAnswer: externalSelectedAnswer, onAnswerSelect, result: externalResult }) {
  const [localSelectedAnswer, setLocalSelectedAnswer] = useState('');
  const [showHints, setShowHints] = useState(false);
  const [currentHintIndex, setCurrentHintIndex] = useState(0);
  const [localResult, setLocalResult] = useState(null);
  
  // 使用外部傳入的 selectedAnswer 和 result,如果有的話
  const selectedAnswer = externalSelectedAnswer || localSelectedAnswer;
  const result = externalResult || localResult;
  
  // 當外部 selectedAnswer 變化時更新本地狀態
  useEffect(() => {
    if (externalSelectedAnswer) {
      setLocalSelectedAnswer(externalSelectedAnswer);
    }
  }, [externalSelectedAnswer]);
  
  // 當外部 result 變化時更新本地狀態
  useEffect(() => {
    if (externalResult) {
      setLocalResult(externalResult);
    }
  }, [externalResult]);

  const handleOptionClick = (value) => {
    setLocalSelectedAnswer(value);
    
    // 找到選中選項的文本
    if (exercise.type === 'multiple_choice' && exercise.options) {
      const optionIndex = parseInt(value, 10);
      const optionText = exercise.options[optionIndex];
      
      // 通知父組件選擇變化
      if (onAnswerSelect) {
        onAnswerSelect(value, optionText);
      }
    } else {
      // 對於文本輸入,直接傳遞值
      if (onAnswerSelect) {
        onAnswerSelect(value, value);
      }
    }
  };

  const handleSubmit = async () => {
    try {
      if (!selectedAnswer.trim()) {
        return;
      }

      // 找到選中選項的文本
      let answerText = selectedAnswer;
      if (exercise.type === 'multiple_choice' && exercise.options) {
        const optionIndex = parseInt(selectedAnswer, 10);
        answerText = exercise.options[optionIndex];
      }
      
      // 通知父組件
      if (onSubmit) {
        await onSubmit(selectedAnswer, answerText);
      } else {
        // 如果沒有提供 onSubmit,則使用本地邏輯
        const response = await axios.post(`/api/exercises/check/${exercise.id}`, {
          answer: selectedAnswer
        });
        setLocalResult(response.data);
      }
      
    } catch (error) {
      console.error('Error submitting answer:', error);
      setLocalResult({ correct: false, explanation: "檢查答案時發生錯誤" });
    }
  };

  const handleNextExercise = () => {
    setLocalSelectedAnswer('');
    setShowHints(false);
    setCurrentHintIndex(0);
    setLocalResult(null);
    if (onNextExercise) {
      onNextExercise();
    }
  };

  const showNextHint = () => {
    if (currentHintIndex < exercise.hints.length - 1) {
      setCurrentHintIndex(prev => prev + 1);
    }
    setShowHints(true);
  };

  return (
    <Box sx={{ 
      mb: 4,
      display: 'flex',
      gap: 3,
      minHeight: 200
    }}>
      {/* 左側:題目和作答區域 */}
      <Paper sx={{ 
        flex: 2,
        p: 2,
        display: 'flex',
        flexDirection: 'column',
        backgroundColor: '#f8f9fa'
      }}>
        <Typography variant="h6" sx={{ mb: 2, color: 'text.primary' }}>
          題目
        </Typography>
        <Typography variant="body1" sx={{ 
          mb: 3,
          fontWeight: 500,
          whiteSpace: 'pre-wrap'
        }}>
          {exercise.question}
        </Typography>

        {/* 作答區域整合到題目下方 */}
        <Box sx={{ mb: 2 }}>
          {exercise.type === 'multiple_choice' ? (
            <RadioGroup
              value={selectedAnswer}
              onChange={(e) => {
                // 只有在還沒有結果或答錯的情況下才允許更改答案
                if (!result?.correct) {
                  handleOptionClick(e.target.value);
                }
              }}
            >
              {exercise.options.map((option, index) => {
                const isSelected = selectedAnswer === index.toString();
                const isWrongAnswer = result && !result.correct && isSelected;
                
                return (
                  <FormControlLabel
                    key={index}
                    value={index.toString()}
                    control={<Radio />}
                    label={`${String.fromCharCode(65 + index)}. ${option}`}
                    sx={{ 
                      mb: 1,
                      color: isWrongAnswer ? 'error.main' : 'text.primary',
                      '&.Mui-disabled': {
                        color: result?.correct ? 'success.main' : 'text.disabled'
                      }
                    }}
                    disabled={result?.correct}
                  />
                );
              })}
            </RadioGroup>
          ) : (
            <TextField
              fullWidth
              value={selectedAnswer}
              onChange={(e) => {
                // 只有在還沒有結果或答錯的情況下才允許更改答案
                if (!result?.correct) {
                  handleOptionClick(e.target.value);
                }
              }}
              placeholder="請輸入答案"
              variant="outlined"
              size="small"
              disabled={result?.correct}
              error={result && !result.correct}
              helperText={result && !result.correct ? "答案不正確" : ""}
            />
          )}
        </Box>
      </Paper>

      {/* 右側:操作和反饋區域 */}
      <Paper sx={{ 
        flex: 1,
        p: 2,
        display: 'flex',
        flexDirection: 'column'
      }}>
        <Typography variant="h6" sx={{ mb: 2, color: 'text.primary' }}>
          操作區
        </Typography>
        
        {/* 按鈕組 */}
        <Stack spacing={2} sx={{ mb: 2 }}>
          <Button
            variant="contained"
            onClick={handleSubmit}
            disabled={!selectedAnswer.trim() || result?.correct}
            fullWidth
          >
            提交答案
          </Button>
          <Button
            variant="outlined"
            startIcon={<LightbulbIcon />}
            onClick={showNextHint}
            disabled={showHints && currentHintIndex >= exercise.hints.length - 1}
            fullWidth
          >
            {showHints ? '下一個提示' : '顯示提示'}
          </Button>
          {onNextExercise && (
            <Button
              variant="contained"
              color="success"
              endIcon={<NavigateNextIcon />}
              onClick={handleNextExercise}
              disabled={!result?.correct}
              fullWidth
            >
              下一題
            </Button>
          )}
        </Stack>

        {/* 提示和結果區域 */}
        <Box sx={{ mt: 'auto' }}>
          <Collapse in={showHints}>
            <Box sx={{ mb: 2 }}>
              {exercise.hints.slice(0, currentHintIndex + 1).map((hint, index) => (
                <Alert key={index} severity="info" sx={{ mb: 1 }}>
                  提示 {index + 1}: {hint}
                </Alert>
              ))}
            </Box>
          </Collapse>

          {result && (
            <Alert 
              severity={result.correct ? "success" : "error"}
              sx={{
                '& .MuiAlert-message': { width: '100%' }
              }}
            >
              <Box sx={{ 
                display: 'flex', 
                flexDirection: 'column',
                gap: 1
              }}>
                <Typography>
                  {result.correct ? '答對了!' : '再試一次!'}
                </Typography>
                {result.explanation && (
                  <Typography 
                    sx={{ 
                      mt: 1,
                      p: 1,
                      backgroundColor: 'rgba(0, 0, 0, 0.04)',
                      borderRadius: 1
                    }}
                  >
                    解釋:{result.explanation}
                  </Typography>
                )}
              </Box>
            </Alert>
          )}
        </Box>
      </Paper>
    </Box>
  );
}

export default Exercise;