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

interface Props {
  data: Multi
  onAnswer: (isAnswer: boolean) => void
  onUpAndDown?: (index: number) => void
  index: number
  validate: boolean
  frequency?: number
  end: boolean
}

const Multi: FC<Props> = ({data, onAnswer, onUpAndDown, index, validate, frequency, end}) => {
  const [rightAnswer, setRightAnswer] = useState<string[]>([]) //答案

  const rightKey = data?.right_answer?.split(',') || []  // 正确答案数组
  const [error, setError] = useState(false)

  const answers = [
    {value: "A", title: data.answerA},
    {value: "B", title: data.answerB},
    {value: "C", title: data.answerC},
    {value: "D", title: data.answerD},
  ]

  function onChange(e) {
    const value = e.detail.value
    if (data.type) {
      setRightAnswer(value)
    } else {
      setRightAnswer([value])
    }
  }

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

  return (
    <View className='topic'>
      <View className='mb-3'>
        <Text style={{
          display: 'inline-block',
          verticalAlign: 'middle',
          fontSize: '20rpx',
          height: '34rpx',
          background: '#45D4A8',
          borderRadius: '8rpx',
          color: '#fff',
          padding: '0 2px',
          marginRight: '8px'
        }}>{data.type ? "多选题" : '单选题'}</Text>
        <Text>{data.question}</Text>
      </View>

      <View>
        {data.type ? <CheckboxGroup onChange={onChange}>
            {answers.map(d => <Checkbox
              value={d.value}
              className='option'
              disabled={validate}
            >
              {d.title}
            </Checkbox>)}
          </CheckboxGroup>
          : <RadioGroup onChange={onChange}>
            {answers.map(d => <Radio
              value={d.value}
              className='option'
              color={validate ? rightKey.includes(d.value) ? '#45d4a8' : 'red' : '#45d4a8'}
              disabled={validate ? !rightAnswer.includes(d.value) : false}
            >
              {d.title}
            </Radio>)}
          </RadioGroup>
        }
      </View>

      {onUpAndDown && <View className='upAndDown'>
        {index > 0 && <Button className='button' onClick={() => onUpAndDown?.(index - 1)}>上一题</Button>}
        {!end && <Button onClick={() => onUpAndDown?.(index + 1)} className='button'>下一题{end}</Button>}
      </View>}


      {error && frequency == 0 && <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 Multi
