import React, { useRef, useState, useCallback, useEffect } from 'react';
import { TinyColor } from '@ctrl/tinycolor';
import { Button, Card, Space, Row, Col } from 'antd';
import { CameraOutlined } from '@ant-design/icons';
import { useLocation, useNavigate } from 'react-router-dom';
import './style.css'

let defaultContext = ''

const VoicePage = () => {
  const [transcript, setTranscript] = useState('');
  const [recognition, setRecognition] = useState(null);
  const [type, setType] = useState(false);

  useEffect(() => {
    const SpeechRecognition = window.webkitSpeechRecognition;
    const recognition = new SpeechRecognition() as any;
    setRecognition(recognition);

    // recognition.lang = 'yue-Hant-HK'; // 粤语 ，广东话（方言）
    // recognition.lang = 'wuu-SH'; // 上海话（方言）

    recognition.interimResults = false;
    recognition.maxAlternatives = 1;
    recognition.continuous = true;
    recognition.interimResultsTimeout = 30000;
    recognition.lang = 'zh-CN';
    recognition.maxSpeechTime = 60000;

    recognition.onresult = (event: any) => {
      const newTranscript = Array.from(event.results).at(-1)[0].transcript;
      defaultContext = defaultContext + newTranscript
      setTranscript(defaultContext);

    };

    recognition.onsoundstart = function (e: any) {
      console.log("开始收听了");
      console.log(e);
    }

    recognition.onspeechstart = (e: any) => {
      console.log("开始讲话了");
      console.log(e);
    }

    recognition.onspeechend = (e: any) => {
      console.log("讲话完毕");
      console.log(e);
    }

    recognition.onerror = (e: any) => {
      console.log("发生异常");
      console.log(e);
    }



    return () => {
      recognition.stop();
    };
  }, []);

  const startListening = () => {
    if (recognition) {
      recognition.start();
      setType(true)

    }
  };

  const stopListening = () => {
    if (recognition) {
      recognition.stop();
      setType(false)
    }
  };



  return (
    <>
      <div className="voice">
        <Card title={false} bordered={false} style={{ width: 800 }}>
          <Row>
            <Col span={20}>
              <Space>
                <Button type="primary" size="large" danger={type ? true : false} onMouseDown={startListening} onMouseUp={stopListening}>
                  {`${type ? "松开停止" : '按下识别 '}  `}
                </Button>
              </Space>
              <p className='result'>识别结果: {transcript}</p>
            </Col>
            <Col span={4}>
              <i className={`${type ? "on" : 'off'} typeIcon `} > </i>
            </Col>
          </Row>
        </Card>
      </div>
    </>
  );
};
export default VoicePage;
