// /**
//  * Sample React Native App
//  * https://github.com/facebook/react-native
//  * @flow
//  */

import React, {Component} from 'react';
import {
  StyleSheet,
  View,
  Alert,
  Dimensions,
  Platform,
  TouchableOpacity,
  Text,
} from 'react-native';
import Modal, {ModalContent} from 'react-native-modals';
import BackHeader from '../../components/backHeader';
var Sound = require('react-native-sound');
import Icon from 'react-native-vector-icons/FontAwesome5';
var RNFS = require('react-native-fs');
import {colors} from '../../assets/styles/colors-theme';

import {Fonts} from '../../assets/styles/fonts-theme';
import ImagePicker from 'react-native-image-crop-picker';
import history from '../../common/history';
import IMUI from 'aurora-imui-react-native';
var InputView = IMUI.ChatInput;
var MessageListView = IMUI.MessageList;
import {width, height} from '../../common/screen';
const AuroraIController = IMUI.AuroraIMUIController;
const window = Dimensions.get('window');
import {observable} from 'mobx';
import monent from 'moment';
import {inject, observer} from 'mobx-react';
import JMessage from 'jmessage-react-plugin';
const options = {
  title: 'Select Avatar',
  //customButtons: [{ name: 'fb', title: 'Choose Photo from Facebook' }],
  storageOptions: {
    skipBackup: true,
    path: 'images',
  },
};
@inject('appStore')
@observer
export default class Chat extends Component {
  @observable
  selectPhotoOrVideo = false;
  takePhotoOrVideo = false;
  static navigationOptions = {
    title: 'Chat',
  };

  constructor(props) {
    super(props);
    let initHeight;
    this.store = props.appStore;
    if (Platform.OS == 'android') {
      initHeight = 100;
    } else {
      initHeight = 86;
    }
    this.state = {
      inputLayoutHeight: initHeight,
      messageListLayout: {},
      inputViewLayout: {width: window.width, height: initHeight},
      menuContainerHeight: 625,
      from: 0,
      limit: 10,
    };

    this.updateLayout = this.updateLayout.bind(this);
    this.onTouchMsgList = this.onTouchMsgList.bind(this);
    this.conversation = this.props.navigation.state.params.conversation;
    console.log(JSON.stringify(this.conversation));

    JMessage.getMyInfo(myInfo => {
      this.myInfo = myInfo;
      console.log(this.myInfo);
    });
  }

  convertJMessageToAuroraMsg(jmessage) {
    console.log(jmessage);
    var auroraMsg = {};
    auroraMsg.msgType = jmessage.type;
    auroraMsg.msgId = jmessage.id;

    if (jmessage.type === 'text') {
      auroraMsg.text = jmessage.text;
    }

    if (jmessage.type === 'image') {
      auroraMsg.mediaPath = jmessage.thumbPath;
    }

    if (jmessage.type === 'voice') {
      auroraMsg.mediaPath = jmessage.path;
      auroraMsg.duration = jmessage.duration;
    }

    if (jmessage.type === 'file') {
      if (jmessage.extras.fileType === 'video') {
        auroraMsg.mediaPath = jmessage.path;
        auroraMsg.duration = jmessage.duration;
        auroraMsg.msgType = 'video';
      } else {
        console.log("cann't parse this file type ignore");
        return {};
      }
    }
    if (jmessage.type == 'custom') {
      if (jmessage.hasOwnProperty('customObject')) {
        if (jmessage.customObject.hasOwnProperty('image')) {
          auroraMsg.msgType = 'image';
          auroraMsg.mediaPath = jmessage.customObject.image;
        } else if (jmessage.customObject.hasOwnProperty('audio')) {
          auroraMsg.msgType = 'voice';
          auroraMsg.mediaPath = jmessage.customObject.audio;
          auroraMsg.duration = jmessage.customObject.duration;
        } else if (jmessage.customObject.hasOwnProperty('video')) {
          auroraMsg.mediaPath = jmessage.customObject.video;
          auroraMsg.msgType = 'video';

          console.log(auroraMsg.mediaPath);
        } else {
          auroraMsg.msgType = 'text';
          auroraMsg.text = jmessage.customObject.text;
        }
      } else if (jmessage.hasOwnProperty('eventType')) {
        auroraMsg.msgType = 'event';
        auroraMsg.text = jmessage.eventType;
      } else {
        auroraMsg.msgType = 'text';
        auroraMsg.text = '';
      }
      //console.log(jmessage.customObject.text)
      //auroraMsg.text = jmessage.customObject
    }

    if (jmessage.type === 'event') {
      //   Alert.alert('event', jmessage.eventType);
      auroraMsg.text = jmessage.eventType;
    }

    if (jmessage.type === 'prompt') {
      auroraMsg.msgType = 'event';
      auroraMsg.text = jmessage.promptText;
    }

    var user = {
      userId: '1',
      displayName: '',
      avatarPath: require('../../assets/images/chat/head.png').toString(),
    };
    console.log('from user: ' + jmessage.from.avatarThumbPath);
    user.userId = jmessage.from.username;
    user.displayName = jmessage.from.nickname;
    user.avatarPath = jmessage.from.avatarThumbPath.toString();
    if (user.displayName == '') {
      user.displayName = jmessage.from.username;
    }
    if (user.avatarPath == '') {
      user.avatarPath = require('../../assets/images/chat/head.png').toString();
    }
    auroraMsg.fromUser = user;
    auroraMsg.status = 'send_succeed';

    auroraMsg.isOutgoing = true;

    if (this.myInfo.username === jmessage.from.username) {
      auroraMsg.isOutgoing = true;
    } else {
      auroraMsg.isOutgoing = false;
    }

    auroraMsg.timeString = '';

    if (auroraMsg.msgType == 'voice') {
      if (jmessage.hasOwnProperty('customObject')) {
        this.getfile(jmessage, auroraMsg);
      }
    } else if (auroraMsg.msgType == 'video') {
      if (jmessage.hasOwnProperty('customObject')) {
        this.getfile(jmessage, auroraMsg);
      }
    }

    return auroraMsg;
  }

  getNormalMessage() {
    var msg = {};
    if (this.conversation.type === 'single') {
      msg.username = this.conversation.username;
    } else if (this.conversation.type === 'group') {
      msg.groupId = this.conversation.id;
    } else {
      msg.roomId = this.conversation.roomId;
    }
    msg.type = this.conversation.type;
    return msg;
  }

  sendCustomMessage = () => {
    var messages = [];
    for (var i = 0; i < 10; i++) {
      var message = this.getNormalMessage();
      message.msgType = 'custom';
      message.msgId = '10';
      message.status = 'send_going';
      message.isOutgoing = true;
      message.content =
        '<body bgcolor="#ff3399"><h5>This is a custom message. </h5>\
      <img src="/storage/emulated/0/XhsEmoticonsKeyboard/Emoticons/wxemoticons/icon_040_cover.png"></img></body>';
      message.contentSize = {height: 200, width: 200};
      message.extras = {extras: 'fdfsf'};
      var user = {
        userId: '1',
        displayName: '',
        avatarPath: require('../../assets/images/chat/head.png').toString(),
      };
      user.displayName = '0001';
      user.avatarPath = require('../../assets/images/chat/head.png').toString();
      message.fromUser = user;
      messages[i] = message;
    }

    AuroraIController.appendMessages(messages);
    var customMessage = {
      type: 'single',
      username: 'Wicked002',
      appKey: '58067d5678c387f20831a956',
      customObject: {key: 'value'},
    };
    JMessage.sendCustomMessage(
      customMessage,
      success => {
        console.log('JS sendCustomMessage success:' + JSON.stringify(success));
      },
      error => {
        console.log('JS sendCustomMessage error:' + JSON.stringify(error));
      },
    );
  };

  getVideo(message) {
    console.log('load image');
    var parames = {
      type: this.conversation.type,
      username: this.conversation.username,
      groupId: this.conversation.id,
      messageId: message.msgId,
    };
    JMessage.downloadFile(
      parames,
      result => {
        console.log(message);
        console.log(result);
        // var msgId = result.messageId
        // var imgPath = result.filePath
        var newMessage = {
          msgType: message.msgType,
          msgId: message.msgId,
          mediaPath: result.filePath,
          duration: message.duration,
          fromUser: message.fromUser,
          status: message.status,
          isOutgoing: message.isOutgoing,
          timeString: message.timeString,
        };
        this.loading = false;
        Alert.alert('onSendGalleryFiles', JSON.stringify(result.filePath));

        AuroraIController.updateMessage(newMessage);
        console.log(result);
      },
      error => {
        var code = error.code;
        var desc = error.description;
        Alert.alert('get video error:', JSON.stringify(error));
        this.loading = false;
      },
    );
  }

  async getVoiceDuration(name, uri) {
    var whoosh = await new Sound(
      name,
      uri,

      error => {
        if (error) {
          console.log('failed to load the sound', error);
          return;
        }
        console.log(
          'duration in seconds: ' +
            whoosh.getDuration() +
            'number of channels: ' +
            whoosh.getNumberOfChannels(),
        );
        return whoosh.getDuration();
      },
    );
  }

  async getfile(jmessage, auroraMsg) {
    console.log(jmessage);
    console.log(auroraMsg);

    var existing = await RNFS.exists(
      RNFS.DocumentDirectoryPath + '/' + jmessage.customObject.name,
    );
    if (existing) {
      var newMessage = {
        msgType: auroraMsg.msgType,
        msgId: auroraMsg.msgId,
        mediaPath:
          RNFS.DocumentDirectoryPath + '/' + jmessage.customObject.name,
        duration: auroraMsg.duration,
        fromUser: auroraMsg.fromUser,
        status: auroraMsg.status,
        isOutgoing: auroraMsg.isOutgoing,
        timeString: auroraMsg.timeString,
      };
     
      if (auroraMsg.msgType == 'voice') {
      }
    

      AuroraIController.updateMessage(newMessage);
    } else {
      console.log('not');
      var messageFromUrl = '';
      if (auroraMsg.msgType == 'video') {
        messageFromUrl = jmessage.customObject.video;
      } else {
        messageFromUrl = jmessage.customObject.audio;
      }
      RNFS.downloadFile({
        fromUrl: messageFromUrl,
        toFile: `${RNFS.DocumentDirectoryPath}/${jmessage.customObject.name}`,
      }).promise.then(r => {
        console.log(r);
        var newMessage = {
          msgType: auroraMsg.msgType,
          msgId: auroraMsg.msgId,
          mediaPath:
            RNFS.DocumentDirectoryPath + '/' + jmessage.customObject.name,
          duration: auroraMsg.duration,
          fromUser: auroraMsg.fromUser,
          status: auroraMsg.status,
          isOutgoing: auroraMsg.isOutgoing,
          timeString: auroraMsg.timeString,
        };
        AuroraIController.updateMessage(newMessage);
      });
    }
  }

  componentWillMount() {
    // RNFS.readDir(RNFS.DocumentDirectoryPath) // On Android, use "RNFS.DocumentDirectoryPath" (MainBundlePath is not defined)
    //   .then(result => {
    //     console.log('GOT RESULT', result);

    //     // stat the first file
    //     return Promise.all([RNFS.stat(result[0].path), result[0].path]);
    //   });
    if (this.conversation.type === 'group') {
      console.log('reset all group unread');
      JMessage.resetUnreadMessageCount(
        {type: 'group', groupId: this.conversation.id},
        conversation => {
          console.log(conversation);
        },
        error => {
          var code = error.code;
          var desc = error.description;
        },
      );
    } else {
      console.log('reset all user unread');
      JMessage.resetUnreadMessageCount(
        {type: 'single', username: this.conversation.username},
        conversation => {
          console.log(conversation);
        },
        error => {
          var code = error.code;
          var desc = error.description;
        },
      );
    }
    console.log(this.conversation);
    if (this.conversation.hasOwnProperty('msgContent')) {
      if (this.conversation.msgContent != undefined) {
        this.onSendText(this.conversation.msgContent);
      }
    }
  }

  componentDidMount() {
    JMessage.setBadge(0, success => {});
    this.resetMenu();
    this.setState({
      messageListLayout: {flex: 1, margin: 0, width: window.width},
    });
    var parames = {
      from: this.state.from, // 开始的消息下标。
      limit: this.state.limit, // 要获取的消息数。比如当 from = 0, limit = 10 时，是获取第 0 - 9 条历史消息。
      type: this.conversation.type,
      username: this.conversation.username,
      groupId: this.conversation.id,
      roomId: this.conversation.roomId,
    };
    console.log(parames);
    this.messageListDidLoadCallback = () => {
      JMessage.getHistoryMessages(
        parames,
        messages => {
          //  Alert.alert('messages',JSON.stringify(messages))
          console.log('JS getHistoryMessage:' + JSON.stringify(messages));
          this.setState({
            from: this.state.from + 10,
          });
          var auroraMessages = messages.map(message => {
            var normalMessage = this.convertJMessageToAuroraMsg(message);
            console.log(normalMessage);
            if (normalMessage.msgType === 'unknow') {
              return;
            }
            return normalMessage;
          });
          console.log(auroraMessages);
          AuroraIController.insertMessagesToTop(auroraMessages);
        },
        error => {
          Alert.alert('error!', JSON.stringify(error));
        },
      );

      this.receiveMessageCallBack = message => {
        console.log('JS receiveMessage:' + JSON.stringify(message));
        // Alert.alert(
        //   'message.from.group',
        //   JSON.stringify(message),
        // );
        const readParams = {
          type: 'single',
          username: message.from.username,
          appKey: message.from.appKey,
          id: message.id,
        };

        if (this.conversation.type === 'single') {
          if (message.target.type === 'user') {
            JMessage.setMsgHaveRead(
              readParams,
              result => {
                console.log(result);
              },
              error => {
                console.log(error);
              },
            );
            if (message.from.username === this.conversation.username) {
              var msg = this.convertJMessageToAuroraMsg(message);
              AuroraIController.appendMessages([msg]);
            }
            if (msg.msgType == 'video') {
              //this.getVideo(msg);
            } else if (msg.msgType == 'voice') {
              //this.getVoice(message,msg)
            }
            console.log(msg);
            console.log(message);
            // Alert.alert(
            //   'message.from.username',
            //   message.from.username + ',message:' + message.text,
            // );
          }
        } else if (this.conversation.type === 'group') {
          if (message.target.type === 'group') {
            readParams.groupId = message.target.id;
            readParams.type = 'group';
            JMessage.setMsgHaveRead(
              readParams,
              result => {
                console.log(result);
              },
              error => {
                console.log(error);
              },
            );
            if (message.target.id === this.conversation.id) {
              var msg = this.convertJMessageToAuroraMsg(message);
              AuroraIController.appendMessages([msg]);
              //   Alert.alert(
              //   'message.from.group',
              //   message.from.id  + ',message:' + message.text,
              // );
            }
          }
        } else {
          if (message.target.type === 'chatroom') {
            if (message.target.roomId === this.conversation.roomId) {
              var msg = this.convertJMessageToAuroraMsg(message);
              AuroraIController.appendMessages([msg]);
            }
          }
        }
      };
      JMessage.addReceiveMessageListener(this.receiveMessageCallBack);
      JMessage.addReceiptMessageListener(result => {});
    };
    AuroraIController.addMessageListDidLoadListener(
      this.messageListDidLoadCallback,
    );
    // this.timer = setTimeout(() => {
    //   console.log("Sending custom message")
    //   this.sendCustomMessage();
    // }, 2000)
  }

  onInputViewSizeChange = size => {
    console.log('height: ' + size.height);
    if (this.state.inputLayoutHeight != size.height) {
      this.setState({
        inputLayoutHeight: size.height,
        inputViewLayout: {width: size.width, height: size.height},
        messageListLayout: {flex: 1, width: window.width, margin: 0},
      });
    }
  };

  componentWillUnmount() {
    JMessage.removeReceiveMessageListener(this.receiveMessageCallBack);
    AuroraIController.removeMessageListDidLoadListener(
      this.messageListDidLoadCallback,
    );
    this.timer && clearTimeout(this.timer);
    if (this.conversation.type === 'chatroom') {
      JMessage.leaveChatRoom(
        {roomId: this.conversation.roomId},
        code => {
          console.log('Leave chat room succeed');
        },
        error => {
          alert('error: ' + JSON.stringify(error));
        },
      );
    } else {
      JMessage.exitConversation();
    }
  }

  resetMenu() {
    if (Platform.OS === 'android') {
      this.refs['ChatInput'].showMenu(false);
      this.setState({
        messageListLayout: {flex: 1, width: window.width, margin: 0},
      });
    } else {
      this.setState({
        inputViewLayout: {width: window.width, height: 86},
      });
    }
  }

  updateLayout(layout) {
    this.setState({inputViewLayout: layout});
  }

  onAvatarClick = message => {};

  onTouchMsgList() {
    AuroraIController.hidenFeatureView(true);
  }

  onTouchEditText = () => {
    console.log('scroll to bottom');
    this.refs['ChatInput'].showMenu(false);
    this.setState({
      inputViewLayout: {
        width: window.width,
        height: this.state.inputLayoutHeight,
      },
    });
  };

  onFullScreen = () => {
    var navigationBar = 50;
    this.setState({
      messageListLayout: {flex: 0, width: 0, height: 0},
      inputViewLayout: {flex: 1, width: window.width, height: window.height},
    });
  };

  onRecoverScreen = () => {
    this.setState({
      messageListLayout: {flex: 1, width: window.width, margin: 0},
      inputViewLayout: {
        flex: 0,
        width: window.width,
        height: this.state.inputLayoutHeight,
      },
    });
  };

  onMsgClick = message => {
    console.log(message);
    var msgType = message.msgType;
    // alert(JSON.stringify(message))
    // Alert.alert('onSendGalleryFiles', JSON.stringify(message));
    if (message.msgType == 'image' || message.msgType == 'video') {
      var parames = {
        type: this.conversation.type,
        username: this.conversation.username,
        groupId: this.conversation.id,
        messageId: message.msgId,
        messageType: msgType,
        mediaPath: message.mediaPath,
      };
      console.log(parames);
      history.push(this, '/imageDetails', {data: parames});
    }
  };

  onMsgLongClick = message => {
    var msg = {};
    msg.type = 'group';
    msg.groupId = this.conversation.id;
    msg.messageId = message.msgId;
    //Alert.alert('撤回消息', '撤回消息');
    JMessage.retractMessage(
      msg,
      success => {
        var eventMsg = {};
        eventMsg.msgId = message.msgId;
        eventMsg.msgType = 'event';
        eventMsg.text = '撤回的消息';
        AuroraIController.updateMessage(eventMsg);
      },
      error => {},
    );
  };

  onStatusViewClick = message => {
    console.log(message);
    message.status = 'send_succeed';
    message.fromUser.avatarPath = message.mediaPath.toString();
    AuroraIController.updateMessage(message);
  };

  onBeginDragMessageList = () => {
    this.updateLayout({width: window.width, height: 86});
    AuroraIController.hidenFeatureView(true);
  };

  onPullToRefresh = () => {
    console.log('on pull to refresh');
    var parames = {
      from: this.state.from, // 开始的消息下标。
      limit: this.state.limit, // 要获取的消息数。比如当 from = 0, limit = 10 时，是获取第 0 - 9 条历史消息。
      type: this.conversation.type,
      username: this.conversation.username,
      groupId: this.conversation.id,
      roomId: this.conversation.roomId,
    };
    console.log(parames);
    JMessage.getHistoryMessages(
      parames,
      messages => {
        if (Platform.OS == 'android') {
          this.refs['MessageList'].refreshComplete();
        }
        this.setState({
          from: this.state.from + 10,
        });
        console.log(messages);
        var auroraMessages = messages.map(message => {
          var normalMessage = this.convertJMessageToAuroraMsg(message);
          if (normalMessage.msgType === 'unknow') {
            return;
          }
          return normalMessage;
        });
        AuroraIController.insertMessagesToTop(auroraMessages);
      },
      error => {
        Alert.alert('error!', JSON.stringify(error));
      },
    );
  };

  setMessageTarget = msg => {
    if (this.conversation.type === 'single') {
      msg.username = this.conversation.username;
    } else if (this.conversation.type === 'group') {
      msg.groupId = this.conversation.id;
    } else {
      msg.roomId = this.conversation.roomId;
    }
    msg.type = this.conversation.type;
  };

  onSendText = text => {
    var message = this.getNormalMessage();
    message.text = text;
    message.messageType = 'text';
    // message.messageType = "custom"
    // message.customObject = {'key':'value'}
    JMessage.createSendMessage(message, msg => {
      console.log('JS createSendMessage:' + JSON.stringify(msg));
      var auroraMsg = this.convertJMessageToAuroraMsg(msg);
      if (auroraMsg.msgType === undefined) {
        return;
      }

      auroraMsg.status = 'send_going';
      AuroraIController.appendMessages([auroraMsg]);
      AuroraIController.scrollToBottom(true);
      this.setMessageTarget(msg);
      console.log(msg.from.nickname);
      //Alert.alert('send text', JSON.stringify(msg));

      msg.messageSendingOptions = {
        needReadReceipt: true,
        isShowNotification: true,
        isRetainOffline: true,
        isCustomNotificationEnabled: true,
        notificationTitle: msg.from.nickname,
        notificationText: text,
      };

      JMessage.sendMessage(
        msg,
        jmessage => {
          var auroraMsg = this.convertJMessageToAuroraMsg(jmessage);
          AuroraIController.updateMessage(auroraMsg);
          console.log('JS sendMessage success:' + JSON.stringify(jmessage));
        },
        error => {
          console.log('JS sendMessage error:' + JSON.stringify(error));
        },
      );
    });
  };

  async onSendCustomMessage(customObj, objName, msgType, msgDuration) {
    var message = this.getNormalMessage();
    var userid = '';
    var nickname = '';
    var type = '';
    if (this.conversation.type === 'group') {
      userid = this.conversation.id;
      nickname = 'Helper';
      type = 'group';
    } else {
      userid = this.myInfo.username;
      nickname = this.myInfo.nickname;
      type = 'single';
    }
    message.text = '';
    message.extras = {
      id: userid,
      nickname: nickname,
      type: type,
    };
    var customnotificationText = '';
    message.messageType = 'custom';
    switch (msgType) {
      case 0:
        message.customObject = {
          text: customObj,
          name: objName,
        };
        customnotificationText = customObj;
        break;
      case 1:
        message.customObject = {
          image: customObj,
          name: objName,
        };
        customnotificationText = '發來圖片';
        break;
      case 2:
        message.customObject = {
          audio: customObj,
          name: objName,
          duration: msgDuration,
        };
        customnotificationText = '發來一段錄音';
        break;
      case 3:
        message.customObject = {
          video: customObj,
          name: objName,
          //duration: msgDuration,
        };
        customnotificationText = '發來一段影片';
        break;
    }

    // message.messageType = "custom"
    // message.customObject = {'key':'value'}
    JMessage.createSendMessage(message, msg => {
      console.log('JS createSendMessage:' + JSON.stringify(msg));
      var auroraMsg = this.convertJMessageToAuroraMsg(msg);
      if (auroraMsg.msgType === undefined) {
        return;
      }

      auroraMsg.status = 'send_going';
      AuroraIController.appendMessages([auroraMsg]);
      AuroraIController.scrollToBottom(true);
      this.setMessageTarget(msg);
      console.log(msg.from.nickname);
      //Alert.alert('send text', JSON.stringify(msg));

      var notifTitle = '';
      if (this.conversation.type === 'group') {
        notifTitle = this.conversation.id + '&&' + 'group';
      } else {
        notifTitle = msg.from.username + '&&' + 'single';
      }

      msg.messageSendingOptions = {
        needReadReceipt: true,
        isShowNotification: true,
        isRetainOffline: true,
        isCustomNotificationEnabled: true,
        notificationTitle: msg.from.nickname,
        notificationText: customnotificationText,
      };

      JMessage.sendMessage(
        msg,
        jmessage => {
          var toId = '';
          if (jmessage.target.type == 'user') {
            toId = jmessage.target.username;
          } else {
            toId = jmessage.target.id;
          }
          console.log(msg);
          console.log(jmessage);
          const backupMsgData = {
            msgID: jmessage.id,
            fromID: jmessage.from.username,
            toID: toId,
            type: msgType,
            content: JSON.stringify(jmessage.customObject),
          };
          this.store.chatBackup(backupMsgData);
          var auroraMsg = this.convertJMessageToAuroraMsg(jmessage);
          AuroraIController.updateMessage(auroraMsg);
          console.log('JS sendMessage success:' + JSON.stringify(jmessage));
        },
        error => {
          console.log('JS sendMessage error:' + JSON.stringify(error));
        },
      );
    });
  }

  onTakePicture = media => {
    console.log(media);
    // var message = this.getNormalMessage();
    // message.messageType = 'image';
    // message.path = media.mediaPath;

    // JMessage.createSendMessage(message, msg => {
    //   var auroraMsg = this.convertJMessageToAuroraMsg(msg);
    //   auroraMsg.status = 'send_going';
    //   AuroraIController.appendMessages([auroraMsg]);
    //   AuroraIController.scrollToBottom(true);
    //   this.setMessageTarget(msg);
    //   JMessage.sendMessage(
    //     msg,
    //     jmessage => {
    //       var auroraMsg = this.convertJMessageToAuroraMsg(jmessage);
    //       AuroraIController.updateMessage(auroraMsg);
    //     },
    //     error => {
    //       Alert.alert(`send image fail ${JSON.stringify(error)}`);
    //     },
    //   );
    // });
    var fileName = monent().format('DDMMYYYYssmmhh') + '.jpg';
    this.store.chatUploadFile(1, media.mediaPath, fileName, this);
  };

  onStartRecordVoice = e => {
    console.log('on start record voice');
  };

  onFinishRecordVoice = mediaPath => {
    //Alert.alert('onFinishRecordVoice', JSON.stringify(mediaPath));
    console.log(mediaPath);
    console.log(RNFS.DocumentDirectoryPath);

    var fileName = mediaPath.replace(RNFS.DocumentDirectoryPath + '/', '');
    console.log(fileName);
    var whoosh = new Sound(
      fileName,
      RNFS.DocumentDirectoryPath,

      error => {
        if (error) {
          console.log('failed to load the sound', error);
        }
        console.log(
          'duration in seconds: ' +
            whoosh.getDuration() +
            'number of channels: ' +
            whoosh.getNumberOfChannels(),
        );
        this.store.chatUploadFile(
          2,
          mediaPath,
          fileName,
          this,
          whoosh.getDuration(),
        );
      },
    );

    // var message = this.getNormalMessage();
    // message.messageType = 'voice';
    // message.path = mediaPath;

    // JMessage.createSendMessage(message, msg => {
    //   var auroraMsg = this.convertJMessageToAuroraMsg(msg);
    //   auroraMsg.status = 'send_going';
    //   AuroraIController.appendMessages([auroraMsg]);
    //   AuroraIController.scrollToBottom(true);
    //   this.setMessageTarget(msg);
    //   msg.messageSendingOptions = {
    //     needReadReceipt: true,
    //     isShowNotification: true,
    //     isRetainOffline: true,
    //     isCustomNotificationEnabled: true,
    //     notificationTitle: msg.from.nickname,
    //     notificationText: '發來一段錄音',
    //   };
    //   JMessage.sendMessage(
    //     msg,
    //     jmessage => {
    //       var auroraMsg = this.convertJMessageToAuroraMsg(jmessage);
    //       AuroraIController.updateMessage(auroraMsg);
    //     },
    //     error => {
    //       Alert.alert(`send image fail ${JSON.stringify(error)}`);
    //     },
    //   );
    // });
  };

  onCancelRecordVoice = () => {
    console.log('on cancel record voice');
  };

  onStartRecordVideo = () => {
    console.log('on start record video');
  };

  onFinishRecordVideo = async video => {
    console.log(video);
    if (Platform.OS == 'ios') {
      const filename = video.mediaPath.slice(
        video.mediaPath.indexOf('tmp/') + 4,
      );

      console.log(filename);

      await RNFS.moveFile(
        video.mediaPath,
        RNFS.DocumentDirectoryPath + '/' + filename,
      );
      var existing = await RNFS.exists(
        RNFS.DocumentDirectoryPath + '/' + filename,
      );
      console.log(RNFS.DocumentDirectoryPath + '/' + filename);
      console.log(existing);
      if (existing) {
        this.store.chatUploadFile(
          3,
          RNFS.DocumentDirectoryPath + '/' + filename,
          filename,
          this,
        );
      }
    }

    // var message = this.getNormalMessage();
    // message.messageType = 'file';
    // message.extras = {fileType: 'video'};
    // message.path = video.mediaPath;

    // JMessage.createSendMessage(message, msg => {
    //   var auroraMsg = this.convertJMessageToAuroraMsg(msg);
    //   auroraMsg.status = 'send_going';
    //   AuroraIController.appendMessages([auroraMsg]);
    //   AuroraIController.scrollToBottom(true);
    //   this.setMessageTarget(msg);
    //   console.log(msg);
    //   JMessage.sendMessage(
    //     msg,
    //     jmessage => {
    //       var auroraMsg = this.convertJMessageToAuroraMsg(jmessage);
    //       AuroraIController.updateMessage(auroraMsg);
    //     },
    //     error => {
    //       Alert.alert(`send image fail ${JSON.stringify(error)}`);
    //     },
    //   );
    // });
  };

  onSendGalleryFiles = mediaFiles => {
    for (var index in mediaFiles) {
      Alert.alert(
        'onSendGalleryFiles',
        JSON.stringify(mediaFiles[index]['mediaPath']),
      );
      var message = this.getNormalMessage();
      message.messageType = 'image';
      message.path = mediaFiles[index].mediaPath;

      JMessage.createSendMessage(message, msg => {
        var auroraMsg = this.convertJMessageToAuroraMsg(msg);
        auroraMsg.status = 'send_going';
        AuroraIController.appendMessages([auroraMsg]);
        AuroraIController.scrollToBottom(true);
        this.setMessageTarget(msg);
        msg.messageSendingOptions = {
          needReadReceipt: true,
          isShowNotification: true,
          isRetainOffline: true,
          isCustomNotificationEnabled: true,
          notificationTitle: msg.from.nickname,
          notificationText: '發來圖片',
        };
        JMessage.sendMessage(
          msg,
          jmessage => {
            var auroraMsg = this.convertJMessageToAuroraMsg(jmessage);
            AuroraIController.updateMessage(auroraMsg);
          },
          error => {
            Alert.alert(`send image fail ${JSON.stringify(error)}`);
          },
        );
      });
    }
  };

  onSwitchToMicrophoneMode = () => {
    AuroraIController.scrollToBottom(true);
  };

  async selectPhoto() {
    this.selectPhotoOrVideo = false;
    ImagePicker.openPicker({
      includeBase64: false,
      writeTempFile: true,
      multiple: false,
      mediaType: 'photo',
      cropping: false,
    }).then(image => {
      console.log(image);
      var response = image;
      if (Platform.OS === 'ios') {
        // const uri = this.store.convertLocalIdentifierToAssetLibrary(
        //   response.localIdentifier,
        //   'JPG',
        // );
        // response.path = uri;
        console.log(response);

        this.store.chatUploadFile(1, response.path, response.filename, this);
      } else {
        // this.store.apartmentDataDoc.push(
        //   this.saveAndroidImageHandler(response),
        // );
      }
    });
  }

  async onSendCustomImageMessage(uri) {
    console.log(uri);
    var message = this.getNormalMessage();
    message.messageType = 'custom';
    // message.path = response.path;
    message.customObject = {
      image: uri,
    };
    JMessage.createSendMessage(message, msg => {
      var auroraMsg = this.convertJMessageToAuroraMsg(msg);
      auroraMsg.status = 'send_going';
      AuroraIController.appendMessages([auroraMsg]);
      AuroraIController.scrollToBottom(true);
      this.setMessageTarget(msg);
      msg.messageSendingOptions = {
        needReadReceipt: true,
        isShowNotification: true,
        isRetainOffline: true,
        isCustomNotificationEnabled: true,
        notificationTitle: msg.from.nickname,
        notificationText: '發來圖片',
      };
      JMessage.sendMessage(
        msg,
        jmessage => {
          var auroraMsg = this.convertJMessageToAuroraMsg(jmessage);
          AuroraIController.updateMessage(auroraMsg);
        },
        error => {
          Alert.alert(`send image fail ${JSON.stringify(error)}`);
        },
      );
    });
  }

  async selectVideo() {
    this.selectPhotoOrVideo = false;
    ImagePicker.openPicker({
      includeBase64: false,
      writeTempFile: true,
      multiple: false,
      mediaType: 'video',
      cropping: false,
    }).then(async video => {
      if (Platform.OS === 'ios') {
        console.log(video);

        const fileName = video.path.slice(
          video.path.indexOf('react-native-image-crop-picker/') + 31,
        );
        console.log(fileName);
        await RNFS.moveFile(
          video.path.slice(7),
          RNFS.DocumentDirectoryPath + '/' + fileName,
        );
        var existing = await RNFS.exists(
          RNFS.DocumentDirectoryPath + '/' + fileName,
        );
        console.log(RNFS.DocumentDirectoryPath + '/' + fileName);
        console.log(existing);
        if (existing) {
          this.store.chatUploadFile(
            3,
            RNFS.DocumentDirectoryPath + '/' + fileName,
            fileName,
            this,
          );
        }

        // message.path = response.path.slice(7);
        // this.store.chatUploadFile(3, video.path.slice(7), video.filename, this);
      } else {
        // this.store.apartmentDataDoc.push(
        //   this.saveAndroidImageHandler(response),
        // );
      }
    });
  }

  takePhoto() {
    this.takePhotoOrVideo = false;
    ImagePicker.openCamera({
      includeBase64: false,
      writeTempFile: true,
      multiple: false,
      mediaType: 'photo',
      cropping: false,
    }).then(image => {
      console.log(image);
      var response = image;
      if (Platform.OS === 'ios') {
        this.store.chatUploadFile(1, response.path, response.filename, this);
      } else {
        // this.store.apartmentDataDoc.push(
        //   this.saveAndroidImageHandler(response),
        // );
      }
    });
  }

  takeVideo() {
    this.takePhotoOrVideo = false;
    ImagePicker.openCamera({
      includeBase64: false,
      writeTempFile: true,
      multiple: false,
      mediaType: 'video',
      cropping: false,
    }).then(image => {
      console.log(image);
      var response = image;
      if (Platform.OS === 'ios') {
        // Alert.alert('messages', JSON.stringify(response));
        var message = this.getNormalMessage();
        message.messageType = 'file';
        message.extras = {fileType: 'video'};
        message.path = response.path.slice(7);

        JMessage.createSendMessage(message, msg => {
          var auroraMsg = this.convertJMessageToAuroraMsg(msg);
          auroraMsg.status = 'send_going';
          AuroraIController.appendMessages([auroraMsg]);
          AuroraIController.scrollToBottom(true);
          this.setMessageTarget(msg);
          console.log(msg);
          JMessage.sendMessage(
            msg,
            jmessage => {
              var auroraMsg = this.convertJMessageToAuroraMsg(jmessage);
              AuroraIController.updateMessage(auroraMsg);
            },
            error => {
              Alert.alert(`send image fail ${JSON.stringify(error)}`);
            },
          );
        });
      } else {
        // this.store.apartmentDataDoc.push(
        //   this.saveAndroidImageHandler(response),
        // );
      }
    });
  }

  onSwitchToGalleryMode = () => {
    AuroraIController.scrollToBottom(true);
    AuroraIController.hidenFeatureView(true);
    this.selectPhotoOrVideo = true;
    // ImagePicker.openPicker({
    //   includeBase64: false,
    //   writeTempFile: true,
    //   multiple: false,
    //   mediaType: 'photo',
    //   cropping: false,
    // }).then(image => {
    //   console.log(image);
    //   var response = image;
    //   if (Platform.OS === 'ios') {
    //     // const uri = this.store.convertLocalIdentifierToAssetLibrary(
    //     //   response.localIdentifier,
    //     //   'JPG',
    //     // );
    //     // response.path = uri;
    //     console.log(response.path);
    //     var message = this.getNormalMessage();
    //     message.messageType = 'image';
    //     message.path = response.path;

    //     JMessage.createSendMessage(message, msg => {
    //       var auroraMsg = this.convertJMessageToAuroraMsg(msg);
    //       auroraMsg.status = 'send_going';
    //       AuroraIController.appendMessages([auroraMsg]);
    //       AuroraIController.scrollToBottom(true);
    //       this.setMessageTarget(msg);
    //       msg.messageSendingOptions = {
    //         needReadReceipt: true,
    //         isShowNotification: true,
    //         isRetainOffline: true,
    //         isCustomNotificationEnabled: true,
    //         notificationTitle: msg.from.nickname,
    //         notificationText: '發來圖片',
    //       };
    //       JMessage.sendMessage(
    //         msg,
    //         jmessage => {
    //           var auroraMsg = this.convertJMessageToAuroraMsg(jmessage);
    //           AuroraIController.updateMessage(auroraMsg);
    //         },
    //         error => {
    //           Alert.alert(`send image fail ${JSON.stringify(error)}`);
    //         },
    //       );
    //     });
    //   } else {
    //     // this.store.apartmentDataDoc.push(
    //     //   this.saveAndroidImageHandler(response),
    //     // );
    //   }
    // });
  };

  onSwitchToCameraMode = () => {
    AuroraIController.scrollToBottom(true);
    //AuroraIController.hidenFeatureView(true);
    //this.takePhotoOrVideo = true;

    // Alert.alert(
    //   'Take Video or Photo',
    //   'Take Video or Photo',
    //   [
    //     {text: 'Take Photo', onPress: () => this.takePhoto()},
    //     {text: 'Take Video', onPress: () => this.takeVideo()},
    //     {text: 'Cancel', onPress: () => console.log('cencel')},
    //   ],
    //   {cancelable: false},
    // );
    //return;
    // ImagePicker.openPicker({
    //   includeBase64: false,
    //   writeTempFile: true,
    //   multiple: false,
    //   mediaType: 'video',
    //   cropping: false,
    // }).then(image => {
    //   console.log(image);
    //   var response = image;
    //   if (Platform.OS === 'ios') {
    //     Alert.alert('messages', JSON.stringify(response));
    //     var message = this.getNormalMessage();
    //     message.messageType = 'file';
    //     message.extras = {fileType: 'video'};
    //     message.path = response.path.slice(7);

    //     JMessage.createSendMessage(message, msg => {
    //       var auroraMsg = this.convertJMessageToAuroraMsg(msg);
    //       auroraMsg.status = 'send_going';
    //       AuroraIController.appendMessages([auroraMsg]);
    //       AuroraIController.scrollToBottom(true);
    //       this.setMessageTarget(msg);
    //       console.log(msg);
    //       JMessage.sendMessage(
    //         msg,
    //         jmessage => {
    //           var auroraMsg = this.convertJMessageToAuroraMsg(jmessage);
    //           AuroraIController.updateMessage(auroraMsg);
    //         },
    //         error => {
    //           Alert.alert(`send image fail ${JSON.stringify(error)}`);
    //         },
    //       );
    //     });
    //   } else {
    //     // this.store.apartmentDataDoc.push(
    //     //   this.saveAndroidImageHandler(response),
    //     // );
    //   }
    // });
  };

  onShowKeyboard = keyboard_height => {
    var inputViewHeight = keyboard_height + 86;
    this.updateLayout({width: window.width, height: inputViewHeight});
  };

  onSwitchToEmojiMode = () => {
    AuroraIController.scrollToBottom(true);
  };

  onInitPress() {
    console.log('on click init push');
    this.updateAction();
  }

  render() {
    return (
      <View style={styles.container}>
        {Platform.OS == 'ios' ? (
          <View>
            <View>
              <BackHeader
                instance={this}
                back={true}
                title={this.conversation.nickname}
              />
            </View>
            <MessageListView
              style={this.state.messageListLayout}
              ref="MessageList"
              onAvatarClick={this.onAvatarClick}
              isShowDisplayName={true}
              isAllowPullToRefresh={true}
              onMsgClick={this.onMsgClick}
              dateTextSize={10}
              dateTextColor={colors.mainColor}
              onMsgLongClick={this.onMsgLongClick}
              onStatusViewClick={this.onStatusViewClick}
              onTouchMsgList={this.onTouchMsgList}
              onTapMessageCell={this.onTapMessageCell}
              onBeginDragMessageList={this.onBeginDragMessageList}
              onPullToRefresh={this.onPullToRefresh}
              avatarSize={{width: 0, height: 0}}
              sendBubbleTextSize={18}
              sendBubbleTextColor={'#000000'}
              sendBubblePadding={{left: 10, top: 10, right: 15, bottom: 10}}
            />
            <InputView
              style={this.state.inputViewLayout}
              ref="ChatInput"
              menuContainerHeight={this.state.menuContainerHeight}
              isDismissMenuContainer={this.state.isDismissMenuContainer}
              onSendText={text => {
                this.onSendCustomMessage(text, text, 0);
              }}
              onTakePicture={this.onTakePicture}
              onStartRecordVoice={this.onStartRecordVoice}
              onFinishRecordVoice={this.onFinishRecordVoice}
              onCancelRecordVoice={this.onCancelRecordVoice}
              onStartRecordVideo={this.onStartRecordVideo}
              onFinishRecordVideo={this.onFinishRecordVideo}
              onSendGalleryFiles={this.onSendGalleryFiles}
              onSwitchToEmojiMode={this.onSwitchToEmojiMode}
              onSwitchToMicrophoneMode={this.onSwitchToMicrophoneMode}
              onSwitchToGalleryMode={this.onSwitchToGalleryMode}
              onSwitchToCameraMode={this.onSwitchToCameraMode}
              onShowKeyboard={this.onShowKeyboard}
              onTouchEditText={this.onTouchEditText}
              onFullScreen={this.onFullScreen}
              onRecoverScreen={this.onRecoverScreen}
              onSizeChange={this.onInputViewSizeChange}
            />
          </View>
        ) : (
          <View>
            <MessageListView
              style={{flex: 1, margin: 0, width: window.width, marginTop: 70}}
              ref="MessageList"
              onAvatarClick={this.onAvatarClick}
              isShowDisplayName={true}
              isAllowPullToRefresh={true}
              onMsgClick={this.onMsgClick}
              dateTextSize={10}
              dateTextColor={colors.mainColor}
              onMsgLongClick={this.onMsgLongClick}
              onStatusViewClick={this.onStatusViewClick}
              onTouchMsgList={this.onTouchMsgList}
              onTapMessageCell={this.onTapMessageCell}
              onBeginDragMessageList={this.onBeginDragMessageList}
              onPullToRefresh={this.onPullToRefresh}
              avatarSize={{width: 0, height: 0}}
              sendBubbleTextSize={18}
              sendBubbleTextColor={'#000000'}
              sendBubblePadding={{left: 10, top: 10, right: 15, bottom: 10}}
            />
            <View style={{position: 'absolute', top: 0}}>
              <BackHeader
                instance={this}
                back={true}
                title={this.conversation.nickname}
              />
            </View>
            <InputView
              style={this.state.inputViewLayout}
              ref="ChatInput"
              menuContainerHeight={this.state.menuContainerHeight}
              isDismissMenuContainer={this.state.isDismissMenuContainer}
              onSendText={text => {
                this.onSendCustomMessage(text, text, 0);
              }}
              onTakePicture={this.onTakePicture}
              onStartRecordVoice={this.onStartRecordVoice}
              onFinishRecordVoice={this.onFinishRecordVoice}
              onCancelRecordVoice={this.onCancelRecordVoice}
              onStartRecordVideo={this.onStartRecordVideo}
              onFinishRecordVideo={this.onFinishRecordVideo}
              onSendGalleryFiles={this.onSendGalleryFiles}
              onSwitchToEmojiMode={this.onSwitchToEmojiMode}
              onSwitchToMicrophoneMode={this.onSwitchToMicrophoneMode}
              onSwitchToGalleryMode={this.onSwitchToGalleryMode}
              onSwitchToCameraMode={this.onSwitchToCameraMode}
              onShowKeyboard={this.onShowKeyboard}
              onTouchEditText={this.onTouchEditText}
              onFullScreen={this.onFullScreen}
              onRecoverScreen={this.onRecoverScreen}
              onSizeChange={this.onInputViewSizeChange}
            />
          </View>
        )}

        <Modal
          visible={this.selectPhotoOrVideo}
          width={0.7}
          height={0.2}
          onTouchOutside={() => {
            this.selectPhotoOrVideo = false;
          }}
          swipeDirection={['up', 'down']} // can be string or an array
          swipeThreshold={200} // default 100
          onSwipeOut={event => {
            this.selectPhotoOrVideo = false;
          }}>
          <ModalContent>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              <TouchableOpacity
                style={{
                  alignItems: 'center',
                  justifyContent: 'center',
                  flex: 1,
                }}
                onPress={() => this.selectPhoto()}>
                <Icon
                  name="file-image"
                  sholid
                  color={colors.mainColor}
                  size={70}
                />
                <Text
                  style={{
                    fontFamily: Fonts.ubuntu,
                    color: colors.mainColor,
                    fontSize: 18,
                  }}>
                  {'傳送相片'}
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={{
                  alignItems: 'center',
                  justifyContent: 'center',
                  flex: 1,
                }}
                onPress={() => this.selectVideo()}>
                <Icon
                  name="file-video"
                  sholid
                  color={colors.mainColor}
                  size={70}
                />
                <Text
                  style={{
                    fontFamily: Fonts.ubuntu,
                    color: colors.mainColor,
                    fontSize: 18,
                  }}>
                  {'傳送影片'}
                </Text>
              </TouchableOpacity>
            </View>
          </ModalContent>
        </Modal>
        <Modal
          visible={this.takePhotoOrVideo}
          width={0.7}
          height={0.2}
          onTouchOutside={() => {
            this.takePhotoOrVideo = false;
          }}
          // swipeDirection={['up', 'down']} // can be string or an array
          // swipeThreshold={200} // default 100
          onSwipeOut={event => {
            this.takePhotoOrVideo = false;
          }}>
          <ModalContent>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              <TouchableOpacity
                style={{
                  alignItems: 'center',
                  justifyContent: 'center',
                  flex: 1,
                }}
                onPress={() => this.takePhoto()}>
                <Icon name="camera" sholid color={colors.mainColor} size={70} />
                <Text
                  style={{
                    fontFamily: Fonts.ubuntu,
                    color: colors.mainColor,
                    fontSize: 18,
                  }}>
                  {'拍攝相片'}
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={{
                  alignItems: 'center',
                  justifyContent: 'center',
                  flex: 1,
                }}
                onPress={() => this.takeVideo()}>
                <Icon name="video" sholid color={colors.mainColor} size={70} />
                <Text
                  style={{
                    fontFamily: Fonts.ubuntu,
                    color: colors.mainColor,
                    fontSize: 18,
                  }}>
                  {'拍攝影片'}
                </Text>
              </TouchableOpacity>
            </View>
          </ModalContent>
        </Modal>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  inputView: {
    backgroundColor: 'green',
    width: window.width,
    height: 100,
  },
  btnStyle: {
    marginTop: 10,
    borderWidth: 1,
    borderColor: '#3e83d7',
    borderRadius: 8,
    backgroundColor: '#3e83d7',
  },
});
