function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { TouchableOpacity, View, Platform, KeyboardAvoidingView, Keyboard, StatusBar, TextInput, TouchableOpacityBase, Dimensions } from 'react-native';
import colors from '../../Styles';
import { BottomSheetModalProvider } from '../../components/bottomSheet/bottom-sheet';
import { MText as Text } from '../../components';
import chatStore from './ChatStore';
import { Log, orderStatus } from '../../utils';
import appStore from '../AppStore';
import { observer } from 'mobx-react-lite';
import { Navigation } from 'react-native-navigation';
import { ChatItem } from './Item';
import uuid from 'react-native-uuid';
import { AttachScreen, Input } from './Attach';
import { FlatList, ScrollView } from '../../components/flatlist';
import { MenuProvider } from 'react-native-popup-menu';
import { RecordButton } from './RecordButton';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import CameraRoll from '../../components/cameraRollPicker/CameraRoll';
import { SafeAreaView } from 'react-native-safe-area-context';
import { EmojiKeyboard } from '../../components/emojiKeyBoard';
// import { MTextInput as TextInput } from '../../components';
import Image from 'react-native-fast-image';
import Toast, { BaseToast } from 'react-native-toast-message';
import EmojiPicker from 'react-native-emoji-picker-staltz';
import inputStore from './InputStore';
import InputStore from './InputStore';
let {
  height,
  width
} = Dimensions.get('window');
import { FlashList } from "../../components/flashlist";
export const ChatScreen = observer(function ChatScreen(props) {
  var _props$data, _props$data$orders, _props$data2, _receiver$state;
  const conversation = props.data;
  const order = ((_props$data = props.data) === null || _props$data === void 0 ? void 0 : (_props$data$orders = _props$data.orders) === null || _props$data$orders === void 0 ? void 0 : _props$data$orders.length) > 0 ? (_props$data2 = props.data) === null || _props$data2 === void 0 ? void 0 : _props$data2.orders[0] : {};
  const [receiver, setReceiver] = useState({});
  const inputRef = useRef(null);
  const isOrderSuccess = () => {
    return (order === null || order === void 0 ? void 0 : order.order_status) === 501;
  };
  useEffect(() => {
    chatStore.quote = props.order ? {
      _id: uuid.v4(),
      conversation_id: conversation._id,
      text: 'QUOTE_ORDER',
      type: 'QUOTE_ORDER',
      order_number: props.order.ORDER_NUMBER,
      has_attachment: false,
      order_info: {
        vtp_order: props.order
      }
    } : undefined;
    const showSubscription = Keyboard.addListener('keyboardDidShow', () => {
      if (chatStore.keyboardEmoji) {
        var _InputStore$inputRef, _InputStore$inputRef$;
        chatStore.keyboardEmoji = false;
        (_InputStore$inputRef = InputStore.inputRef) === null || _InputStore$inputRef === void 0 ? void 0 : (_InputStore$inputRef$ = _InputStore$inputRef.current) === null || _InputStore$inputRef$ === void 0 ? void 0 : _InputStore$inputRef$.focus();
      }
    });
    chatStore.resetData();
    const listener = Navigation.events().registerNavigationButtonPressedListener(() => {
      chatStore.images = [];
    });
    let receiver = {};
    try {
      receiver = conversation.detail_participants.find(i => i.user_id !== appStore.user.user_id);
      setReceiver(receiver ? receiver : {});
    } catch (e) {}
    setTimeout(() => {
      chatStore.page = 0;
      chatStore.getData({
        conversation_id: conversation === null || conversation === void 0 ? void 0 : conversation._id
      });
    }, 250);
    return () => {
      showSubscription.remove();
      listener.remove();
      chatStore.showAttachModal = false;
      chatStore.keyboardEmoji = false;
    };
  }, []);
  const navigateAttachs = () => {
    if (conversation.type === 'PAIR') {
      Navigation.push(props.componentId, {
        component: {
          name: 'AttachsScreen',
          options: {
            popGesture: false,
            bottomTabs: {
              visible: false
            },
            topBar: {
              visible: false,
              height: 0
            }
          },
          passProps: {
            data: conversation,
            receiver
          }
        }
      });
    }
  };
  const handleLoadMore = () => {
    chatStore.getData({
      conversation_id: conversation._id
    });
  };
  const sendImages = async () => {
    try {
      var _props$data$order_inf;
      chatStore.showAttachModal = false;
      try {
        if (Platform.OS === 'ios') {
          for (let i = 0; i < chatStore.images.length; i++) {
            const regex = /:\/\/(.{36})\//i;
            const result = chatStore.images[i].uri.match(regex);
            const photoDetail = await CameraRoll.getPhotoByInternalID(result[1], {});
            chatStore.images[i].uri = photoDetail.node.image.filepath;
          }
        }
      } catch (e) {
        alert(e);
      }
      const message = {
        id: uuid.v4(),
        type: 'MESSAGE',
        attachmentLocal: chatStore.images,
        has_attachment: true,
        attachment_ids: [],
        text: '',
        status: 'sending',
        order_number: (_props$data$order_inf = props.data.order_info) === null || _props$data$order_inf === void 0 ? void 0 : _props$data$order_inf.order_number,
        sender: appStore.user.type + '_' + appStore.user.user_id,
        conversation_id: props.data._id
      };
      chatStore.images = [];
      chatStore.data.unshift(message);
      chatStore.sendMessage(message);
    } catch (e) {}
  };
  return /*#__PURE__*/React.createElement(MenuProvider, {
    style: {
      flex: 1,
      backgroundColor: colors.primary
    }
  }, /*#__PURE__*/React.createElement(SafeAreaView, {
    style: {
      flex: 1
    }
  }, /*#__PURE__*/React.createElement(BottomSheetModalProvider, {
    style: {
      flex: 1
    }
  }, /*#__PURE__*/React.createElement(KeyboardAvoidingView, {
    style: {
      flex: 1
    },
    behavior: Platform.OS === 'ios' ? 'padding' : ''
  }, /*#__PURE__*/React.createElement(View, {
    style: {
      flexDirection: 'row',
      alignItems: 'center',
      height: 64,
      backgroundColor: colors.primary
    }
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: () => Navigation.pop(props.componentId),
    style: {
      width: 50,
      height: 50,
      justifyContent: 'center',
      alignItems: 'center'
    }
  }, /*#__PURE__*/React.createElement(Image, {
    style: {
      height: 36,
      width: 36,
      resizeMode: 'contain'
    },
    source: require('../../assets/ic_back.png')
  })), /*#__PURE__*/React.createElement(View, {
    style: {
      flex: 1,
      alignItems: 'center'
    }
  }, /*#__PURE__*/React.createElement(View, {
    style: {
      flexDirection: 'row',
      alignItems: 'center'
    }
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: navigateAttachs,
    style: {
      flexDirection: 'row',
      alignItems: 'center'
    }
  }, /*#__PURE__*/React.createElement(Text, {
    style: {
      fontWeight: '600',
      fontSize: 17,
      color: 'white'
    }
  }, (conversation === null || conversation === void 0 ? void 0 : conversation.type) === 'GROUP' ? 'Đơn ' + (conversation === null || conversation === void 0 ? void 0 : conversation.order_numbers[0]) : (conversation === null || conversation === void 0 ? void 0 : conversation.type) === 'PAIR' ? (receiver === null || receiver === void 0 ? void 0 : receiver.first_name) + ' ' + (receiver === null || receiver === void 0 ? void 0 : receiver.last_name) : (conversation === null || conversation === void 0 ? void 0 : conversation.type) === 'PAIR_SUPPORT' ? 'Chăm sóc khách hàng' : 'Không tên'), (conversation === null || conversation === void 0 ? void 0 : conversation.type) === 'PAIR' && /*#__PURE__*/React.createElement(Image, {
    style: {
      height: 14,
      width: 14,
      marginLeft: 4,
      resizeMode: 'contain'
    },
    source: require('../../assets/ic_arrow_down.png')
  }))), (conversation === null || conversation === void 0 ? void 0 : conversation.type) === 'PAIR' && /*#__PURE__*/React.createElement(View, {
    style: {
      flexDirection: 'row',
      alignItems: 'center',
      marginTop: 2
    }
  }, ((_receiver$state = receiver.state) === null || _receiver$state === void 0 ? void 0 : _receiver$state.includes('ONLINE')) && /*#__PURE__*/React.createElement(View, {
    style: {
      flexDirection: 'row',
      alignItems: 'center'
    }
  }, /*#__PURE__*/React.createElement(View, {
    style: {
      height: 8,
      width: 8,
      marginRight: 8,
      borderRadius: 4,
      backgroundColor: '#30F03B'
    }
  })), /*#__PURE__*/React.createElement(Text, {
    style: {
      fontWeight: '500',
      fontSize: 13,
      color: 'white',
      textAlign: 'center'
    }
  }, conversation.type === 'PAIR' && receiver.type === 'VTMAN' && appStore.lang.common.postman))), /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: () => alert('Tính năng đang phát triển!'),
    style: {
      width: 50,
      height: 50,
      justifyContent: 'center',
      alignItems: 'flex-end'
    }
  }, /*#__PURE__*/React.createElement(Image, {
    style: {
      height: 18,
      width: 18,
      resizeMode: 'contain',
      marginRight: 16
    },
    source: require('../../assets/ic_call_out_white.png')
  }))), /*#__PURE__*/React.createElement(View, {
    style: {
      flex: 1,
      backgroundColor: 'white'
    }
  }, /*#__PURE__*/React.createElement(FlashList, {
    estimatedItemSize: 200,
    forceNonDeterministicRendering: true,
    maintainVisibleContentPosition: {
      autoscrollToTopThreshold: 10,
      minIndexForVisible: 1
    },
    style: {
      flex: 1,
      backgroundColor: 'white'
    },
    data: chatStore.data,
    extraData: chatStore.data,
    inverted: true,
    renderItem: _ref => {
      let {
        item,
        index
      } = _ref;
      return /*#__PURE__*/React.createElement(ChatItem, {
        item: item,
        index: index,
        conversation: conversation
      });
    },
    getItemType: (item, index) => {
      if (index === 0) {
        return 0;
      }
      return item === null || item === void 0 ? void 0 : item.type;
    },
    onEndReached: () => handleLoadMore(),
    onEndReachedThreshold: 0.5,
    ListHeaderComponent: () => /*#__PURE__*/React.createElement(View, {
      style: {
        height: 8
      }
    }),
    removeClippedSubviews: true,
    keyExtractor: item => item._id !== undefined ? item._id : item.id,
    refreshing: chatStore.isLoading,
    onRefresh: () => {
      chatStore.page = 0;
      chatStore.getData({
        conversation_id: conversation._id
      });
    }
  })), /*#__PURE__*/React.createElement(BottomChat, props)), /*#__PURE__*/React.createElement(AttachScreen, props), chatStore.images.length > 0 && chatStore.showAttachModal && /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: sendImages,
    style: {
      position: 'absolute',
      zIndex: 99999,
      bottom: 92 + useSafeAreaInsets().bottom,
      left: 16,
      right: 16,
      alignItems: 'center',
      justifyContent: 'center',
      padding: 16,
      margin: 16,
      backgroundColor: colors.primary,
      borderRadius: 10
    }
  }, /*#__PURE__*/React.createElement(Text, {
    style: {
      color: 'white',
      fontWeight: '600',
      fontSize: 15
    }
  }, appStore.lang.chat.send))), /*#__PURE__*/React.createElement(Toast, {
    bottomOffset: 90,
    config: {
      info: props => /*#__PURE__*/React.createElement(BaseToast, _extends({}, props, {
        style: {
          borderLeftColor: 'transparent',
          borderRadius: 8,
          backgroundColor: colors.primaryText,
          flexWrap: 'wrap'
        }
        // contentContainerStyle={{
        //   backgroundColor: colors.primaryText,
        //   borderRadius: 8,
        //   marginHorizontal: 16,
        // }}
        ,
        text1Style: {
          flexWrap: 'wrap',
          color: 'white',
          fontSize: 13,
          fontWeight: '500',
          fontFamily: 'SVN-GilroyMedium'
        }
      }))
    }
  })));
});
const BottomChat = observer(function BottomChat(props) {
  const conversation = props.data;
  const sendMessage = async () => {
    var _conversation$order_i;
    const message = {
      id: uuid.v4(),
      type: 'MESSAGE',
      text: InputStore.input,
      status: 'sending',
      order_number: props.order ? props.order.ORDER_NUMBER : (_conversation$order_i = conversation.order_info) === null || _conversation$order_i === void 0 ? void 0 : _conversation$order_i.order_number,
      sender: appStore.user.type + '_' + appStore.user.user_id,
      conversation_id: conversation._id
    };
    InputStore.input = '';
    chatStore.data.unshift(message);
    chatStore.sendMessage(message);
  };
  const handlePresentModalPress = () => {
    Keyboard.dismiss();
    chatStore.showAttachModal = true;
  };
  const isOrderSuccess = () => {
    return false;
  };
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(TouchableOpacity, {
    disabled: !isOrderSuccess(),
    onPress: () => {
      Toast.show({
        type: 'info',
        position: 'bottom',
        text1: 'Chat với bưu tá lấy không khả dụng do đơn đã'
      });
    },
    style: {
      minHeight: 56,
      backgroundColor: '#F8F8FA',
      flexDirection: 'row',
      alignItems: 'flex-end',
      borderTopWidth: 1,
      borderColor: '#DCE6F0'
    }
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    disabled: isOrderSuccess(),
    onPress: handlePresentModalPress,
    style: {
      width: 56,
      height: 56,
      alignItems: 'center',
      justifyContent: 'center'
    }
  }, /*#__PURE__*/React.createElement(Image, {
    source: require('../../assets/ic_attach.png'),
    tintColor: isOrderSuccess() ? '#B5B4B8' : colors.primary,
    style: {
      height: 24,
      width: 24,
      resizeMode: 'contain',
      tintColor: isOrderSuccess() ? '#B5B4B8' : colors.primary
    }
  })), /*#__PURE__*/React.createElement(View, {
    style: {
      width: 1,
      height: '100%'
    }
  }, /*#__PURE__*/React.createElement(View, {
    style: {
      width: 1,
      backgroundColor: '#DCE6F0',
      marginVertical: 14,
      flex: 1
    }
  })), /*#__PURE__*/React.createElement(Input, null), /*#__PURE__*/React.createElement(TouchableOpacity, {
    disabled: isOrderSuccess(),
    onPress: () => {
      if (chatStore.keyboardEmoji) {
        chatStore.keyboardEmoji = false;
      } else {
        chatStore.keyboardEmoji = true;
        Keyboard.dismiss();
      }
    },
    style: {
      width: 40,
      height: 56,
      alignItems: 'center',
      justifyContent: 'center'
    }
  }, /*#__PURE__*/React.createElement(Image, {
    source: isOrderSuccess() ? require('../../assets/ic_emoji_disabled.png') : require('../../assets/ic_emoj.png'),
    style: {
      height: 24,
      width: 24,
      resizeMode: 'contain'
    }
  })), inputStore.input.trim() !== '' && !isOrderSuccess() && /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: sendMessage,
    style: {
      width: 40,
      height: 56,
      alignItems: 'center',
      justifyContent: 'center'
    }
  }, /*#__PURE__*/React.createElement(Image, {
    source: require('../../assets/ic_send.png'),
    style: {
      height: 24,
      width: 24,
      resizeMode: 'contain'
    }
  })), inputStore.input.trim() === '' && /*#__PURE__*/React.createElement(RecordButton, _extends({
    disabled: isOrderSuccess()
  }, props, {
    style: {
      width: 40,
      height: 56,
      alignItems: 'center',
      justifyContent: 'center'
    }
  }), /*#__PURE__*/React.createElement(Image, {
    source: require('../../assets/ic_microphone.png'),
    style: {
      height: 24,
      width: 24,
      resizeMode: 'contain',
      tintColor: isOrderSuccess() ? '#B5B4B8' : colors.primary
    },
    tintColor: isOrderSuccess() ? '#B5B4B8' : colors.primary
  }))), chatStore.keyboardEmoji &&
  /*#__PURE__*/
  // <EmojiKeyboard
  //   styles={{
  //     container: { borderRadius: 0, backgroundColor: 'white' },
  //   }}
  //   onEmojiSelected={(emoji) => {
  //     chatStore.input += emoji.emoji;
  //   }}
  // />
  React.createElement(EmojiPicker, {
    hideClearButton: true,
    onEmojiSelected: emoji => {
      if (emoji !== null) {
        inputStore.input += emoji;
      }
    },
    rows: 7,
    localizedCategories: [
    // Always in this order:
    'Smileys and emotion', 'People and body', 'Animals and nature', 'Food and drink', 'Activities', 'Travel and places', 'Objects', 'Symbols']
  }));
});
//# sourceMappingURL=index.js.map