import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { BrowserMultiFormatReader } from '@zxing/library'
import history from '@/utils/history'
import didiMp3 from '@/assets/img/didi.mp3'

function A3code() {
  // 扫码错误
  const [codeErr, setCodeErr] = useState(false)

  const [tit, setTit] = useState('正在尝试识别....')

  // 异常扫码情况的处理
  const errTitFu = useCallback((val: string) => {
    codeReaderRef.current.reset()
    setCodeErr(true)
    setTit(val)
  }, [])

  const didiRef = useRef<HTMLAudioElement>(null)

  const codeReaderRef = useRef(new BrowserMultiFormatReader())

  const decodeFromInputVideoFunc = useCallback(
    (firstDeviceId: string) => {
      codeReaderRef.current.reset()
      codeReaderRef.current.decodeFromInputVideoDeviceContinuously(
        firstDeviceId,
        'myVideo',
        (result: any, err) => {
          setTit('正在尝试识别...')
          if (result && result.text) {
            const txt: string = result.text
            console.log('txt', txt)
            if (txt) {
              // 识别成功了，播放音频
              if (didiRef.current) {
                // 音频在播放中为 false
                let flag = didiRef.current.paused

                console.log('00', flag)

                if (!flag) return
                else {
                  didiRef.current.play()
                  didiRef.current.addEventListener('ended', () => {
                    console.log('11播放完毕')

                    if (txt.includes('HQ_CODE/')) {
                      codeReaderRef.current.reset()
                      const id = txt.split('/')[1]
                      if (id) history.replace(`/codeSucc/${id}`)
                      else errTitFu('参数错误')
                    } else errTitFu('二维码格式错误,请重试')
                  })
                }
              }
            }
          }
          if (err && !err) {
            errTitFu('识别失败,请重试')
          }
        }
      )
    },
    [errTitFu]
  )

  const openScan = useCallback(async () => {
    codeReaderRef.current
      .getVideoInputDevices()
      .then(videoInputDevices => {
        setTit('正在调用后置摄像头...')
        // 默认获取第一个摄像头设备id
        let firstDeviceId = videoInputDevices[0].deviceId
        // 获取第一个摄像头设备的名称
        const videoInputDeviceslablestr = JSON.stringify(videoInputDevices[0].label)
        if (videoInputDevices.length > 1) {
          // 判断是否后置摄像头
          if (videoInputDeviceslablestr.indexOf('back') > -1) {
            firstDeviceId = videoInputDevices[0].deviceId
          } else {
            firstDeviceId = videoInputDevices[1].deviceId
          }
        }
        decodeFromInputVideoFunc(firstDeviceId)
      })
      .catch(err => {
        errTitFu('识别失败,请重试')
      })
  }, [decodeFromInputVideoFunc, errTitFu])

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

  // 重新扫描 刷新页面
  const newCode = useCallback(() => {
    window.location.reload()
  }, [])

  return (
    <div className={styles.A3code}>
      {codeErr ? (
        <div className='A3err'>
          <div>二维码格式错误</div>
          <div className='A3errNew' onClick={newCode}>
            重 试
          </div>
        </div>
      ) : (
        <>
          <video id='myVideo' autoPlay></video>
          <div className='A3tit'>{tit}</div>
          <audio ref={didiRef} src={didiMp3}></audio>

          {/* 右上角返回按钮 */}
          <div className='A3Back' onClick={() => history.replace('/')}>
            返 回
          </div>

          {/* <div className='A3Back aa' onClick={() => history.replace(`/codeSucc/${63}`)}>
            模拟
          </div> */}
        </>
      )}
    </div>
  )
}

const MemoA3code = React.memo(A3code)

export default MemoA3code
