import {FC, useEffect, useMemo, useState} from "react";
import {View} from "@tarojs/components";
import Taro from "@tarojs/taro";
import styles from './single.module.scss'

interface Props {
  full: boolean
  topic?: ShareSubject
  examination: (result: boolean) => void
}

type AnswerType = "true" | 'false'

export const Single: FC<Props> = (props) => {
  let timer: NodeJS.Timeout
  const [lastState, setLastState] = useState<0 | 1>(0) // 0为竖屏，1为横屏
  const [result, setResult] = useState<AnswerType | undefined>(undefined)
  let lastTime = Date.now()
  Taro.startAccelerometer()
  Taro.onAccelerometerChange((res) => {
    const now = Date.now();
    if (now - lastTime < 500) return;

    lastTime = now;
    let nowState;
    const Roll = Math.atan2(-res.x, Math.sqrt(res.y * res.y + res.z * res.z)) * 57.3;
    const Pitch = Math.atan2(res.y, res.z) * 57.3;

    // 横屏状态
    if (Roll > 50) {
      if ((Pitch > -180 && Pitch < -60) || (Pitch > 130)) {
        nowState = 1;
      } else {
        nowState = lastState;
      }

    } else if ((Roll > 0 && Roll < 30) || (Roll < 0 && Roll > -30)) {
      let absPitch = Math.abs(Pitch);
      // 如果手机平躺，保持原状态不变，40容错率
      if ((absPitch > 140 || absPitch < 40)) {
        nowState = lastState;
      } else if (Pitch < 0) {
        // 收集竖向正立的情况
        nowState = 0;
      } else {
        nowState = lastState;
      }
    } else {
      nowState = lastState;
    }

    // 状态变化时，触发
    if (nowState !== lastState) {
      setLastState(nowState);
    }
  })

  useEffect(() => {
    timer = setTimeout(() => {
      props.examination(false)
    }, 4000)
  }, [props.topic])

  const style: React.CSSProperties = useMemo(() => ({
    transform: lastState === 1 && props.full ? "rotate(90deg)" : 'none'
  }), [lastState, props.full])

  function examination(answer: AnswerType) {
    if (result) return;
    clearTimeout(timer)
    setResult(answer)

    setTimeout(() => {
      props.examination(props.topic?.right_value === result)
      setResult(undefined)
    }, 2000)
  }

  function judgment(answer: AnswerType): string {
    if (result !== answer) return ''
    if (props.topic?.right_answer === answer && result === answer) {
      return styles.correct
    }
    return styles.mistake
  }

  return (
    <>
      {
        props.topic && <View className={styles.singleCover} style={style}>
          <View>{props.topic.question}</View>
          <View className={judgment("true")}
                onClick={() => examination("true")}>
            {props.topic.right_value}
          </View>
          <View className={judgment("false")}
                onClick={() => examination("false")}>
            {props.topic.error_value}
          </View>
        </View>
      }
    </>
  )
}

export default Single
