/**
 * 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/emojiMap';
const { TextArea } = Input;
import tim from '../../../utils/imInitialize';
import { uploadBlobFile } from '../../../services/api';
import Record from '../Record';
import store from 'store';
@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 = {
      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.props.username
        }
      });
    }
  }
  //鍙戦€佸浘鐗�
  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) // 鎵嬪姩缁檓essage 瀹炰緥鍔犱釜鍝嶅簲寮忓睘鎬�: 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) // 鎵嬪姩缁檓essage 瀹炰緥鍔犱釜鍝嶅簲寮忓睘鎬�: 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>
    );
  }
}