import React, { useState, useEffect, useRef } from "react";
import { connect } from "react-redux";
import request from 'superagent'
import moment from "moment";
import { Request } from "@peace/utils";
import { ApiTable } from "$utils";
import './videoPlay.less';
import { DatePicker, Toast, ToastFactory, Space } from '@douyinfe/semi-ui';
import { checkAudioVideo, uploadVoice2Yingshi, sendVoice2YingshiCamera } from '$utils';
import AudioRecoder, { RecordState } from "./audioRecoder"

const VideoOperationTalk = ({
   videoObj,
}) => {
   const [recordState, setRecordState] = useState(RecordState.NONE)

   const ToastInCustomContainer = ToastFactory.create({
      getPopupContainer: () => document.getElementById('vcmp_videoplay'),
   });

   useEffect(() => {

   }, [])

   const startTalk = () => {
      setRecordState(RecordState.START)
   }

   const stopTalk = () => {
      setRecordState(RecordState.STOP)
   }

   const onStopTalk = async (data) => {
      setRecordState(RecordState.STOP)
      const { blob: audioData } = data;
      if (!audioData) return;
      let buffer = await audioData.arrayBuffer();
      let file = new File([buffer], Date.now() + "", {
         type: "audio/mpeg"
      });

      try {
         let uploadRes = await uploadVoice2Yingshi({ voiceFile: file, accessToken: videoObj.yingshiToken, })
         const { url } = uploadRes
         let sendRes = await sendVoice2YingshiCamera({
            accessToken: videoObj.yingshiToken,
            deviceSerial: videoObj.serialNo,
            channelNo: videoObj.channelNo,
            fileUrl: url
         });
         ToastInCustomContainer.success('已发送');
      } catch (error) {
         if (error.msg) {
            ToastInCustomContainer.error(error.msg);
         } else {
            ToastInCustomContainer.error('发送失败');
         }
      }
   }

   return (
      <div style={{
         position: 'absolute', top: 'calc(50% - 88px)', left: 'calc(50% - 156px)',
         width: 312, height: 186, backgroundColor: '#000000A5',
      }}>
         <img src={`/assets/images/background/${recordState == RecordState.START ? 'talking' : 'talk'}.png`} style={{ display: 'block', margin: '12px auto' }} />
         <div
            style={{
               height: 32, width: 88, textAlign: 'center', margin: 'auto', color: '#fff', backgroundColor: '#1859C1',
               lineHeight: '32px', cursor: 'pointer'
            }}
            onClick={() => {
               checkAudioVideo({ audio: true }).then(res => {
                  // console.log('已点击允许,开启成功');
                  if (recordState === RecordState.START) {
                     stopTalk()
                  } else {
                     startTalk()
                  }
               }).catch(err => {
                  ToastInCustomContainer.destroyAll()
                  if (err.code && err.code == 404) {
                     ToastInCustomContainer.error("浏览器不支持")
                  } else {
                     ToastInCustomContainer.error("请检查是否存在麦克风，或是否禁用麦克风")
                  }
               })
            }}
         >{recordState == RecordState.START ? '结束' : '开始'}讲话</div>
         <AudioRecoder state={recordState} onStop={onStopTalk} />
      </div>
   )
}

function mapStateToProps (state) {
   const { auth } = state;
   return {
      user: auth.user,
   };
}

export default connect(mapStateToProps)(VideoOperationTalk);