import {Button, View} from "@tarojs/components";
import {getCurrentInstance} from "@tarojs/runtime";
import {curriculum} from "@/api";
import {useEffect, useState} from "react";
import ShortAnswer from "@/components/topic/shortAnswer";
import Judge from "@/components/topic/judge";
import Multi from "@/components/topic/multi";
import {Profile} from '@/store'
import Taro from "@tarojs/taro";
import styles from './text.module.scss'
import unique_ident from "@/hooks/unique_ident";

const record: boolean[] = []
const Test = () => {
  const {testId} = getCurrentInstance()?.router?.params as { testId: string }
  const [validate, setValidate] = useState(false)
  const [answers, setAnswers] = useState<boolean[]>([])
  const [data, setData] = useState<Record<string, Multi[]> | null>(null)
  const [hourId, setHourId] = useState<number>(0)
  const {user} = Profile.useContainer()

  async function getData() {
    const res = await curriculum.getText(testId)
    setHourId((res.hour_test as any).hour_id)
    setData(res)
  }

  function init() {
    record.splice(0, record.length)
    setValidate(false)
    setAnswers([])
  }

  function onAnswer(answer: boolean) {
    record.push(answer)
    setAnswers(record)
  }


  useEffect(() => {
    if (answers.length) {

      unique_ident.put(undefined, Date.now())

      const isPass = answers.every(d => d)
      curriculum.recordText(hourId, {
        is_pass: isPass,
        test_id: Number(testId),
        test_info: answers.join(','),
        user_id: user?.id!,
        test_score: 0
      }).then()
      curriculum.putRecordText(hourId, isPass).then()
      if (isPass) {
        Taro.showModal({
          title: '考卷已完成',
          showCancel: false,
          success() {
            Taro.navigateBack()
          }
        })
      } else {
        Taro.showModal({
          title: '未及格,请再次作答',
          showCancel: false,
          content: '加油！',
          success() {
            init()
          }
        })
      }
    }
  }, [answers])

  function onSubmit() {
    setValidate(true)
  }

  useEffect(() => {
    getData()
  }, [])


  return (
    <View className={styles.content}>
      {data?.fill.map((d) => <ShortAnswer
        key={d.id}
        data={d}
        onAnswer={onAnswer}
        validate={validate}
      />)}

      {data?.judge.map((d) => <Judge
        key={d.id}
        data={d}
        onAnswer={onAnswer}
        validate={validate}
      />)}

      {
        data?.multi.map((d) => <Multi
          key={d.id}
          data={d}
          onAnswer={onAnswer}
          validate={validate}/>)
      }

      <View className='bg-white pb-3'>
        <Button className='button' onClick={onSubmit}>交卷</Button>
      </View>
    </View>
  )
}


export default Test
