import {FC, useEffect, useState} from "react";
import {Radio, RadioGroup, Text, View} from "@tarojs/components";
import './topic.scss'

interface Props {
  data: ShareSubject
  onAnswer: (isAnswer: boolean) => void
  validate: boolean
}

const Judge: FC<Props> = ({data, onAnswer, validate}) => {
  const [rightAnswer, setRightAnswer] = useState<string | null>(null) //答案
  const rightKey = data.right_answer === 'true' ? 'correct' : 'error'  // 正确答案数组
  const [error, setError] = useState(false)


  function onChange(e) {
    const value = e.detail.value
    setRightAnswer(value)

  }

  useEffect(() => {
    if (validate) {
      onAnswer(rightAnswer === rightKey)
      setError(rightAnswer !== rightKey)
    }
  }, [validate])

  return (
    <View className='topic'>

      <View className='mb-3'>
        <Text className='topicType'>判断题</Text>
        <Text>{data.question}</Text>
      </View>

      <RadioGroup onChange={onChange}>
        <Radio
          value={'correct'}
          className='option'
          color={validate ? 'correct' !== rightKey ? 'red' : '#45d4a8' : '#45d4a8'}
          disabled={validate ? 'correct' !== rightAnswer : false}
        >
          <Text>{data.right_value}</Text>
        </Radio>
        <Radio
          value={'error'}
          color={validate ? 'error' !== rightKey ? 'red' : '#45d4a8' : '#45d4a8'}
          disabled={validate ? 'error' !== rightAnswer : false}
          className='option'>
          <Text>{data.error_value}</Text>
        </Radio>
      </RadioGroup>


      {error && <View className='mt-3'>
        <View className='right_answer'>正确答案：{data.right_answer ? '正确' : '错误'}</View>
        <View className='font-weight my-3'>题目解析</View>
        <View>{data.analysis}</View>
      </View>}
    </View>
  )
}

export default Judge
