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

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

const Multi: FC<Props> = ({data, onAnswer, validate}) => {
  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 RadioChange(e) {
    const value = e.detail.value
    setRightAnswer([value])
  }

  const changeCheckbox = useCallback((value: string) => {
    const index = rightAnswer.indexOf(value)
    if (index === -1) {
      setRightAnswer([...rightAnswer, value])
    } else {
      const oldRightAnswer: string[] = JSON.parse(JSON.stringify(rightAnswer))
      oldRightAnswer.splice(index, 1)
      setRightAnswer(oldRightAnswer)
    }
  }, [rightAnswer])

  useEffect(() => {
    if (validate) {
      if (rightAnswer.length !== rightKey.length) {
        onAnswer(false)
        setError(false)
      } else {
        const isAnswer = rightAnswer.reduce((pre, cut) => {
          if (!pre) {
            return false
          }
          return rightKey.indexOf(cut) !== -1
        }, true)
        onAnswer(isAnswer)
        setError(!isAnswer)
      }
    }
  }, [validate])

  return (
    <View className='topic'>
      <View className='mb-3'>
        <Text className='topicType'>{data.type ? "多选题" : '单选题'}</Text>
        <Text>{data.question}</Text>
      </View>

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

      {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 Multi
