/**
 * 录音页面
 */
import React, { Component } from 'react';
import {
  Radio,
  Collapse,
  Button,
  Modal,
  Input,
  Form,
  Slider,
  Row,
  Col,
  message
} from 'antd';
import './record.less';
import { getHostByPath } from '../../../utils/request';
import AudioAnalyser from 'react-audio-analyser';
export default class Record extends Component {
  constructor(props) {
    super(props);
    this.state = {
      status: '',
      audioSrc: null, //下载的路径
      whichPlace: '', //是在哪里引用的音频样式
      // uploadVideoStr: '', //下载下来的mp3路径
      recordRun: false, //录音是否有在运行，默认是没有在运行的
      recordStop: false, //是否停止了
      timer: 0, //该录音真正的时长
      idx: 0, //用来记录时长(包括暂停的动作)
      playState: false, //是否播放音频
      where: props.where || 'dialog', //'index是在地图页面，dialog是在对话中'
      blob: null, //录制完的音频流
      startRecord: props.startRecord||false //是否开始录音
    };
  }

  componentDidMount() {
    if (this.state.startRecord) {
      //开始录音
      this.controlAudio('recording');
      this.setState({
        recordRun: true,
        recordStop: false
      });
      this.timer();
    }
    // 隐藏左侧菜单栏
    // document.querySelector('.ant-layout-header').style.display = 'none';
    // document.querySelector('.ant-layout-sider').style.display = 'none';
    // document.querySelector('.ant-layout-content').style.margin = '0px';
    // document.querySelector('.oneKeySearchHidden').style.display = 'none';
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      startRecord: nextProps.startRecord
    });
  }
  //设置计时器
  timer() {
    // let idx = 0;
    const that = this;
    const interval = setInterval(function() {
      //还没停止
      if (!that.state.recordStop) {
        if (that.state.recordRun) {
          // idx += 1;
          that.setState({
            timer: that.state.idx + 1,
            idx: that.state.idx + 1
          });
          //如果时长等于1分钟的话,就停止录音
          if (that.state.idx === 60) {
            message.warning('最长录音一分钟');
            that.controlAudio('inactive');
            that.setState({
              recordStop: true
            });
          }
        }
      } else {
        console.log('停止了');
        //停止的时候就清空计时器
        clearInterval(interval);
        that.setState({
          idx: 0
        });
      }
    }, 1000);
  }
  //发送出去im的语音消息(发送之前先把音频流上传到服务器，拿服务器返回的地址发送给im)
  sendIm() {
    const that = this;
    let formData = new FormData();
    formData.append('xfile', this.state.blob);
    let oReq = new XMLHttpRequest();
    oReq.open(
      'POST',
      getHostByPath() + '/public/common/file/upload-blob-file',
      // 'http://192.168.30.232:9093/public/common/file/upload-blob-file',
      true
    );
    oReq.onload = function(success) {
      const data = JSON.parse(success.target.responseText);
      if(data.retType==='0'){
        that.props.sendSound(data.data, that.state.timer);
      }else{
        message.error("发送失败，请重新尝试")
      }
      that.resetSound();//发送出去之后,重新计算录音
    };
    oReq.onerror = function(err) {
      console.log(err + '出错了');
    };
    oReq.send(formData);
  }
  //重新录音
  resetSound() {
    this.controlAudio('inactive');
    this.setState({
      timer: 0,
      idx: 0,
      recordStop: true,
      blob: null
    });
  }
  controlAudio(status) {
    this.setState({
      status
    });
  }
  render() {
    const { status, audioSrc, audioType } = this.state;
    const audioProps = {
      audioType: 'audio/mp3',
      // audioOptions: {sampleRate: 30000}, // 设置输出音频采样率
      status,
      audioSrc,
      timeslice: 1000, // timeslice（https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/start#Parameters）
      strokeColor: '#0F71FF',
      backgroundColor: '#ffffff',
      width: 300,
      startCallback: e => {
        console.log('succ start', e);
      },
      pauseCallback: e => {
        console.log('succ pause', e);
      },
      stopCallback: e => {
        console.log(e);
        this.setState({
          audioSrc: window.URL.createObjectURL(e),
          blob: e
        });
        let messageListNode = this.refs.videoDom;
        messageListNode.src = window.URL.createObjectURL(e);
        // let messageListNode = this.refs.down;
        // messageListNode.click();
      },
      onRecordCallback: e => {
        console.log('recording', e);
      },
      errorCallback: err => {
        console.log('error', err);
        if(err.name==='NotAllowedError'){
          message.error("请允许打开麦克风，才能收集到声音")
        }else{
          message.error("当前浏览器已禁止录音功能，请更换浏览器")
        }
        // message.warning('请检查是');
      }
    };
    return (
      <div
        className="record"
        // style={{ marginLeft: '-300px', marginTop: '370px' }}
        style={{
          marginLeft: this.state.where === 'dialog' ? '-300px' : '',
          marginTop: this.state.where === 'dialog' ? '370px' : '',
          position: this.state.where === 'dialog' ? 'absolute' : '',
          width: this.state.where === 'index' ? '' : '300px'
        }}
      >
        <div
          style={{
            display:
              this.state.recordStop && this.state.timer > 0 ? 'none' : 'block'
          }}
        >
          <AudioAnalyser {...audioProps} />
        </div>
        <div
          className="record-sound"
          style={{
            display:
              this.state.recordStop && this.state.timer > 0 ? 'block' : 'none'
          }}
          onClick={() => {
            //播放自己录音的音频
            this.setState({
              playState: true
            });
            let messageListNode = this.refs.videoDom;
            const promise = messageListNode.play();
            if (promise) {
              promise
                .catch(err => {
                  console.log('播放失败');
                })
                .then(res => {
                  console.log('播放成功');
                });
            }
            const that = this;
            messageListNode.onended = function() {
              console.log('音频播放结束');
              that.setState({
                playState: false
              });
            };
          }}
        >
          <img
            className="sound-img"
            src={
              this.state.playState
                ? require('../../../assets/images/vedio-player.gif')
                : require('../../../assets/images/vedio-player.png')
            }
          />
          {this.state.timer + '"'}
        </div>
        <audio controls ref="videoDom" style={{ display: 'none' }}></audio>
        <div className="btn-box">
          <span
            style={{
              display: this.state.timer > 0 ? 'inline-block' : 'none',
              width: '60px'
            }}
            onClick={() => {
              this.resetSound();
            }}
          >
            重新录音
          </span>
          {status !== 'recording' && (
            <span
              style={{ display: 'inline-block', width: '50px' }}
              onClick={() => {
                this.controlAudio('recording');
                this.setState({
                  recordRun: true,
                  recordStop: false
                });
                this.timer();
              }}
            >
              开始
            </span>
          )}
          {status === 'recording' && (
            <span
              style={{ display: 'inline-block', width: '50px' }}
              onClick={() => {
                this.controlAudio('paused');
                this.setState({
                  recordRun: false
                });
              }}
            >
              暂停
            </span>
          )}
          <span
            style={{ display: 'inline-block', width: '50px' }}
            onClick={() => {
              //还没有开始录音就点击了停止
              if (this.state.timer === 0) {
                message.warning('请先开始录音');
                return;
              }
              this.controlAudio('inactive');
              this.setState({
                recordStop: true
              });
            }}
          >
            停止
          </span>
          <span
            style={{
              display:
                this.state.recordStop && this.state.timer > 0
                  ? 'inline-block'
                  : 'none',
              width: '50px'
            }}
            onClick={() => {
              this.sendIm();
            }}
          >
            发送
          </span>
        </div>
        {/* <a
          href={this.state.audioSrc}
          download="语音.mp3"
          ref="down"
          style={{ display: 'none' }}
        >
          下载 rec-938ms-16kbps-16000hz.mp3
        </a> */}
        {/* <audio controls ref="videoDom"></audio> */}
        {/* <button
          onClick={() => {
            let messageListNode = this.refs.videoDom;
            messageListNode.src = this.state.uploadVideoStr;
            // messageListNode.click();
            console.log(messageListNode);
            const promise = messageListNode.play();
            if (promise) {
              promise
                .catch(err => {
                  console.log('失败');
                })
                .then(res => {
                  console.log(res);
                  console.log('成功');
                });
            }
          }}
        >
          点击播放
        </button> */}
      </div>
    );
  }
}
