/**
 * IM可视化视图
 */
import React, { Component } from 'react';
import TIM from 'tim-js-sdk';
import { connect } from 'dva';
import { Tooltip, Button, Input, Icon, Popover, message } from 'antd';
import './im.less';
import { emojiMap, emojiName, emojiUrl } from '../../../utils/im/emojiMap';
const { TextArea } = Input;
import tim from '../../../utils/im/imInitialize';
import { uploadBlobFile } from '../../../services/api';
import Record from '../Record';
import store from 'store';
import { gup } from '../../../utils/utils';

@connect(state => ({
  imIsLogin: state.global.imIsLogin,
  isSDKReady: state.im.isSDKReady,
  // username: state.global.companyInfo.adminPhone,
  imSig: state.im.imSig,
  currentConversation: state.im.currentConversation,
  currentMessageList: state.im.currentMessageList
}))
export default class MessageSendBox extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mobilePhone:gup('mobilePhone',window.location.href),
      name:decodeURI(gup('username',window.location.href)),
      emojiMap: emojiMap,
      emojiName: emojiName,
      emojiUrl: emojiUrl,
      messageContent: '', //文本值
      messageSendSoundURL: null, //发送的录音地址
      messageSendSoundTime: null, //发送的录音时长
      // startRecord: false //是否开始录音
      // account: '@TGS#12U4JMAGX', //发送给谁的账号
      // currentConversationType:'',//是个人，还是群组
      startRecord:false,//是否开始录音
    };
  }

  componentDidMount() {}
  componentWillReceiveProps(nextProps) {
    //如果有进来要发送的录音地址,就发送一条自定义的消息
    if (nextProps.messageSendSoundURL !== this.state.messageSendSoundURL) {
      this.sendSound(
        nextProps.messageSendSoundURL,
        nextProps.messageSendSoundTime
      );
      this.setState({
        messageSendSoundURL: nextProps.messageSendSoundURL,
        messageSendSoundTime: nextProps.messageSendSoundTime
      });
    }
  }
  getAccount() {
    if (
      !this.props.currentConversation ||
      !this.props.currentConversation.conversationID
    ) {
      return '';
    }
    switch (this.props.currentConversation.type) {
      case 'C2C':
        return this.props.currentConversation.conversationID.replace('C2C', '');
      case 'GROUP':
        return this.props.currentConversation.conversationID.replace(
          'GROUP',
          ''
        );
      default:
        return this.props.currentConversation.conversationID;
    }
  }
  //获取是个人，还是群组
  getType() {
    if (
      !this.props.currentConversation ||
      !this.props.currentConversation.type
    ) {
      return '';
    }
    return this.props.currentConversation.type;
  }
  //发送文字跟表情
  sendTextMessage() {
    const account = this.getAccount();
    const currentConversationType = this.getType();
    if (
      this.state.messageContent === '' ||
      this.state.messageContent.trim().length === 0
    ) {
      this.setState({
        messageContent: ''
      });
      message.warning('不能发送空消息哦！');
      return;
    }
    const messageData = tim.createTextMessage({
      to: account,
      conversationType: currentConversationType, //会话类型，端到端，或者是群组
      payload: { text: this.state.messageContent }
    });
    if (this.props.imIsLogin) {
      this.pushCurrentMessageList(messageData);
      this.sendMessage(messageData);
    } else {
      ///这里还要完善，没有登录的时候先登录，然后在发送
      this.props.dispatch({
        type: `global/imLogin`,
        payload: {
          username: this.state.mobilePhone,
          name:this.state.name
        }
      });
    }
  }
  //发送图片
  sendImage() {
    const account = this.getAccount();
    const currentConversationType = this.getType();
    const messageImage = tim.createImageMessage({
      to: account,
      conversationType: currentConversationType,
      payload: {
        file: document.getElementById('imagePicker') // 或者用event.target
      }
      // onProgress: percent => {
      // this.$set(message, 'progress', percent) // 手动给message 实例加个响应式属性: progress
      // }
    });
    if (this.props.imIsLogin) {
      this.pushCurrentMessageList(messageImage);
      this.sendMessage(messageImage);
    }
    // this.$store.commit('pushCurrentMessageList', message)
    // this.tim.sendMessage(message).catch(imError => this.$message.error(imError.message))
    this.refs.imageRef.value = null;
  }
  //发送文件
  sendFile() {
    const account = this.getAccount();
    const currentConversationType = this.getType();
    const messageFile = tim.createFileMessage({
      to: account,
      conversationType: currentConversationType,
      payload: {
        file: document.getElementById('filePicker') // 或者用event.target
      }
      // onProgress: percent => {
      //   this.$set(message, 'progress', percent) // 手动给message 实例加个响应式属性: progress
      // }
    });
    if (this.props.imIsLogin) {
      this.pushCurrentMessageList(messageFile);
      this.sendMessage(messageFile);
    }
    this.refs.fileRef.value = null;
  }
  //发送自定义（语音）
  sendSound(soundRUL, soundTime) {
    const account = this.getAccount();
    const currentConversationType = this.getType();
    const content = {
      url: soundRUL,
      time: soundTime
    };
    const messageSound = tim.createCustomMessage({
      to: account,
      conversationType: currentConversationType,
      payload: {
        data: 'Sound', // 用于标识该消息是音频类型消息
        description: '[语音]',  // 获取音频路径
        extension: JSON.stringify(content)
      }
    });
    if (this.props.imIsLogin) {
      this.pushCurrentMessageList(messageSound);
      this.sendMessage(messageSound);
    }
    this.setState({
      messageSendSoundURL: ''
    });
    // };
  }
  pushCurrentMessageList(messageData) {
    if (!this.props.currentConversation.conversationID) {
      return;
    }
    if (Array.isArray(messageData)) {
      // console.log(message);
      // 筛选出当前会话的消息
      // const result = messageData.filter(
      //   item =>
      //     item.conversationID === this.props.currentConversation.conversationID
      // );
      // this.props.dispatch({
      //   type: 'im/pushCurrentMessageList',
      //   payload: [...this.props.currentMessageList, messageData]
      // });
      // state.currentMessageList = [...state.currentMessageList, ...result]
      // console.log(result);
    } else if (
      messageData.conversationID ===
      this.props.currentConversation.conversationID
    ) {
      this.props.dispatch({
        type: 'im/pushCurrentMessageList',
        payload: [...this.props.currentMessageList, messageData]
      });
    }
  }
  sendMessage(message) {
    tim
      .sendMessage(message)
      .then(res => {
        console.log('发送成功');
        console.log(res);
        this.setState({
          messageContent: ''
        });
      })
      .catch(err => {
        console.log('发送失败');
        console.log(err);
        message.error('发送失败');
      });
  }
  render() {
    return (
      <div id="message-send-box-wrapper">
        <div className="send-header-bar">
          <Popover
            placement="topLeft"
            content={
              <div className="emojis">
                {this.state.emojiName.map((item, index) => {
                  return (
                    <div
                      className="emoji"
                      key={index}
                      onClick={() => {
                        this.setState({
                          messageContent: this.state.messageContent + item
                        });
                      }}
                    >
                      <img
                        src={this.state.emojiUrl + this.state.emojiMap[item]}
                        style={{ width: '25px', height: '25px' }}
                      />
                    </div>
                  );
                })}
              </div>
            }
            trigger="click"
          >
            <Tooltip placement="bottom" title="发表情">
              <Icon type="smile" style={{ fontSize: '17px' }} />
            </Tooltip>
          </Popover>
          {/* <Tooltip placement="bottom" title="发图片">
            <Icon
              type="file-image"
              onClick={() => {
                console.log('发图片');
                let imagePicker = this.refs.imageRef;
                imagePicker.click();
              }}
            />
          </Tooltip>
          <input
            type="file"
            id="imagePicker"
            ref="imageRef"
            accept=".jpg, .jpeg, .png, .gif"
            onChange={e => {
              this.sendImage();
            }}
            style={{ display: 'none' }}
          /> */}
          <Tooltip placement="bottom" title="发文件">
            <Icon
              type="folder"
              onClick={() => {
                this.refs.fileRef.click();
              }}
              style={{ fontSize: '17px' }}
            />
          </Tooltip>
          <input
            type="file"
            id="filePicker"
            ref="fileRef"
            onChange={() => {
              this.sendFile();
            }}
            style={{ display: 'none' }}
          />
          <Tooltip placement="bottom" title="录音">
            <Icon
              type="audio"
              style={{ fontSize: '17px' }}
              onClick={() => {
                this.setState({
                  startRecord: !this.state.startRecord
                });
                this.props.startRecord(!this.state.startRecord);
              }}
            />
          </Tooltip>
          {/* 发语音 */}
          {/* <Record
            soundBlob={e => {
              this.sendSound(e);
            }}
          /> */}
        </div>
        <TextArea
          style={{ background: 'none', border: 'none' }}
          rows={4}
          className="text-input"
          value={this.state.messageContent}
          onChange={e => {
            this.setState({
              messageContent: e.target.value
            });
          }}
          onPressEnter={() => this.sendTextMessage()}
        />
        <Button
          size="small"
          className="btn-send"
          onClick={() => this.sendTextMessage()}
        >
          发送
        </Button>
      </div>
    );
  }
}
