"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ChatScreen = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _Styles = _interopRequireDefault(require("../../Styles"));
var _bottomSheet = require("../../components/bottomSheet/bottom-sheet");
var _components = require("../../components");
var _ChatStore = _interopRequireDefault(require("./ChatStore"));
var _utils = require("../../utils");
var _AppStore = _interopRequireDefault(require("../AppStore"));
var _mobxReactLite = require("mobx-react-lite");
var _reactNativeNavigation = require("react-native-navigation");
var _Item = require("./Item");
var _reactNativeUuid = _interopRequireDefault(require("react-native-uuid"));
var _Attach = require("./Attach");
var _flatlist = require("../../components/flatlist");
var _reactNativePopupMenu = require("react-native-popup-menu");
var _RecordButton = require("./RecordButton");
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
var _CameraRoll = _interopRequireDefault(require("../../components/cameraRollPicker/CameraRoll"));
var _reactNativeFastImage = _interopRequireDefault(require("react-native-fast-image"));
var _reactNativeToastMessage = _interopRequireWildcard(require("react-native-toast-message"));
var _reactNativeEmojiPickerStaltz = _interopRequireDefault(require("react-native-emoji-picker-staltz"));
var _InputStore = _interopRequireDefault(require("./InputStore"));
var _emoji = _interopRequireDefault(require("../../components/emoji"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
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); }
const ChatScreen = (0, _mobxReactLite.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] = (0, _react.useState)({});
  const inputRef = (0, _react.useRef)(null);
  const isOrderSuccess = () => {
    return (order === null || order === void 0 ? void 0 : order.order_status) === 501;
  };
  (0, _react.useEffect)(() => {
    _ChatStore.default.quote = props.order ? {
      _id: _reactNativeUuid.default.v4(),
      conversation_id: conversation._id,
      text: 'QUOTE_ORDER',
      type: 'QUOTE_ORDER',
      order_number: props.order.ORDER_NUMBER ? props.order.ORDER_NUMBER : props.order.ma_phieugui,
      has_attachment: false,
      order_info: {
        vtp_order: props.order
      }
    } : undefined;
    const showSubscription = _reactNative.Keyboard.addListener('keyboardDidShow', () => {
      if (_ChatStore.default.keyboardEmoji) {
        var _InputStore$inputRef, _InputStore$inputRef$;
        _ChatStore.default.keyboardEmoji = false;
        (_InputStore$inputRef = _InputStore.default.inputRef) === null || _InputStore$inputRef === void 0 ? void 0 : (_InputStore$inputRef$ = _InputStore$inputRef.current) === null || _InputStore$inputRef$ === void 0 ? void 0 : _InputStore$inputRef$.focus();
      }
    });
    _ChatStore.default.resetData();
    let receiver = {};
    try {
      receiver = conversation.detail_participants.find(i => i.user_id !== _AppStore.default.user.user_id);
      setReceiver(receiver ? receiver : {});
    } catch (e) {}
    _ChatStore.default.page = 0;
    _ChatStore.default.getData({
      conversation_id: conversation === null || conversation === void 0 ? void 0 : conversation._id
    });
    return () => {
      _ChatStore.default.data = [];
      _ChatStore.default.showAttachModal = false;
      _ChatStore.default.keyboardEmoji = false;
      _ChatStore.default.images = [];
      _InputStore.default.input = '';
      showSubscription.remove();
    };
  }, []);
  const navigateAttachs = () => {
    if (conversation.type === 'PAIR') {
      _reactNativeNavigation.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.default.getData({
      conversation_id: conversation._id
    });
  };
  const sendImages = async () => {
    try {
      var _props$data$order_inf;
      _ChatStore.default.showAttachModal = false;
      try {
        if (_reactNative.Platform.OS === 'ios') {
          for (let i = 0; i < _ChatStore.default.images.length; i++) {
            const regex = /:\/\/(.{36})\//i;
            const result = _ChatStore.default.images[i].uri.match(regex);
            const photoDetail = await _CameraRoll.default.getPhotoByInternalID(result[1], {});
            _ChatStore.default.images[i].uri = photoDetail.node.image.filepath;
          }
        }
      } catch (e) {
        alert(e);
      }
      const message = {
        id: _reactNativeUuid.default.v4(),
        type: 'MESSAGE',
        attachmentLocal: _ChatStore.default.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.default.user.type + '_' + _AppStore.default.user.user_id,
        conversation_id: props.data._id
      };
      _ChatStore.default.images = [];
      _ChatStore.default.data.unshift(message);
      _ChatStore.default.sendMessage(message);
    } catch (e) {}
  };
  return /*#__PURE__*/_react.default.createElement(_reactNativeSafeAreaContext.SafeAreaView, {
    style: {
      flex: 1
    }
  }, /*#__PURE__*/_react.default.createElement(_bottomSheet.BottomSheetModalProvider, {
    style: {
      flex: 1
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNative.KeyboardAvoidingView, {
    style: {
      flex: 1
    },
    behavior: _reactNative.Platform.OS === 'ios' ? 'padding' : ''
  }, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: {
      flexDirection: 'row',
      alignItems: 'center',
      height: 64,
      backgroundColor: _Styles.default.primary
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, {
    onPress: () => _reactNativeNavigation.Navigation.pop(props.componentId),
    style: {
      width: 50,
      height: 50,
      justifyContent: 'center',
      alignItems: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNativeFastImage.default, {
    style: {
      height: 36,
      width: 36,
      resizeMode: 'contain'
    },
    source: require('../../assets/ic_back.png')
  })), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: {
      flex: 1,
      alignItems: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: {
      flexDirection: 'row',
      alignItems: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, {
    onPress: navigateAttachs,
    style: {
      flexDirection: 'row',
      alignItems: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(_components.MText, {
    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 && receiver.first_name ? receiver === null || receiver === void 0 ? void 0 : receiver.first_name : '') + ' ' + (receiver !== null && receiver !== void 0 && receiver.last_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.default.createElement(_reactNativeFastImage.default, {
    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.default.createElement(_reactNative.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.default.createElement(_reactNative.View, {
    style: {
      flexDirection: 'row',
      alignItems: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: {
      height: 8,
      width: 8,
      marginRight: 8,
      borderRadius: 4,
      backgroundColor: '#30F03B'
    }
  }), /*#__PURE__*/_react.default.createElement(_components.MText, {
    style: {
      fontSize: 13,
      color: "white"
    }
  }, receiver.type === 'VTMAN' ? '' : 'Đang hoạt động')), /*#__PURE__*/_react.default.createElement(_components.MText, {
    style: {
      fontWeight: '500',
      fontSize: 13,
      color: 'white',
      textAlign: 'center'
    }
  }, conversation.type === 'PAIR' && receiver.type === 'VTMAN' && _AppStore.default.lang.common.postman))), /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, {
    onPress: () => {
      try {
        _reactNative.Linking.openURL(`tel:${receiver === null || receiver === void 0 ? void 0 : receiver.phone}`);
      } catch (e) {
        console.log(e);
      }
    },
    style: {
      width: 50,
      height: 50,
      justifyContent: 'center',
      alignItems: 'flex-end'
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNativeFastImage.default, {
    style: {
      height: 18,
      width: 18,
      resizeMode: 'contain',
      marginRight: 16
    },
    source: require('../../assets/ic_call_out_white.png')
  }))), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: {
      flex: 1,
      backgroundColor: 'white'
    }
  }, /*#__PURE__*/_react.default.createElement(_flatlist.FlatList, {
    keyboardShouldPersistTaps: 'always',
    estimatedItemSize: 100,
    viewabilityConfig: {
      waitForInteraction: true,
      itemVisiblePercentThreshold: 50,
      minimumViewTime: 1000
    },
    overrideItemLayout: (layout, item) => {
      layout.size = 200;
    }
    // forceNonDeterministicRendering={true}
    ,
    style: {
      flex: 1,
      backgroundColor: 'white',
      transform: [{
        scaleY: -1
      }]
    },
    data: _ChatStore.default.data,
    extraData: _ChatStore.default.data
    // inverted
    ,
    renderItem: _ref => {
      let {
        item,
        index
      } = _ref;
      return /*#__PURE__*/_react.default.createElement(_reactNative.View, {
        style: {
          transform: [{
            scaleY: -1
          }]
        }
      }, /*#__PURE__*/_react.default.createElement(_Item.ChatItem, {
        item: item,
        index: index,
        conversation: conversation,
        componentId: props.componentId
      }));
    },
    getItemType: (item, index) => {
      return item === null || item === void 0 ? void 0 : item.type;
    },
    onEndReached: () => handleLoadMore(),
    onEndReachedThreshold: 10,
    ListHeaderComponent: () => /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: {
        height: 8
      }
    }),
    removeClippedSubviews: true,
    keyExtractor: item => item._id !== undefined ? item._id : item.id,
    refreshing: _ChatStore.default.isLoading,
    onRefresh: () => {
      _ChatStore.default.page = 0;
      _ChatStore.default.getData({
        conversation_id: conversation._id
      });
    }
  })), /*#__PURE__*/_react.default.createElement(BottomChat, props)), /*#__PURE__*/_react.default.createElement(_Attach.AttachScreen, props), _ChatStore.default.images.length > 0 && _ChatStore.default.showAttachModal && /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, {
    onPress: sendImages,
    style: {
      position: 'absolute',
      zIndex: 99999,
      bottom: 92 + (0, _reactNativeSafeAreaContext.useSafeAreaInsets)().bottom,
      left: 16,
      right: 16,
      alignItems: 'center',
      justifyContent: 'center',
      padding: 16,
      margin: 16,
      backgroundColor: _Styles.default.primary,
      borderRadius: 10
    }
  }, /*#__PURE__*/_react.default.createElement(_components.MText, {
    style: {
      color: 'white',
      fontWeight: '600',
      fontSize: 15
    }
  }, _AppStore.default.lang.chat.send))), /*#__PURE__*/_react.default.createElement(_reactNativeToastMessage.default, {
    bottomOffset: 90,
    config: {
      info: props => /*#__PURE__*/_react.default.createElement(_reactNativeToastMessage.BaseToast, _extends({}, props, {
        style: {
          borderLeftColor: 'transparent',
          borderRadius: 8,
          backgroundColor: _Styles.default.primaryText,
          flexWrap: 'wrap'
        }
        // contentContainerStyle={{
        //   backgroundColor: colors.primaryText,
        //   borderRadius: 8,
        //   marginHorizontal: 16,
        // }}
        ,
        text1Style: {
          flexWrap: 'wrap',
          color: 'white',
          fontSize: 13,
          fontWeight: '500',
          fontFamily: 'SVN-GilroyMedium'
        }
      }))
    }
  }));
});
exports.ChatScreen = ChatScreen;
const BottomChat = (0, _mobxReactLite.observer)(function BottomChat(props) {
  (0, _react.useEffect)(() => {
    return () => {
      _InputStore.default.input = '';
    };
  }, []);
  const conversation = props.data;
  const sendMessage = async () => {
    var _conversation$order_i;
    const message = {
      id: _reactNativeUuid.default.v4(),
      type: 'MESSAGE',
      text: _InputStore.default.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.default.user.type + '_' + _AppStore.default.user.user_id,
      conversation_id: conversation._id
    };
    _InputStore.default.input = '';
    _ChatStore.default.data.unshift(message);
    _ChatStore.default.sendMessage(message);
  };
  const handlePresentModalPress = () => {
    _reactNative.Keyboard.dismiss();
    _ChatStore.default.showAttachModal = true;
  };
  const isOrderSuccess = () => {
    return false;
  };
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, {
    disabled: !isOrderSuccess(),
    onPress: () => {
      _reactNativeToastMessage.default.show({
        type: 'info',
        position: 'bottom',
        text1: 'Chat với bưu tá lấy không khả dụng do\ntrạng thái đơn không cho phép. '
      });
    },
    style: {
      minHeight: 56,
      backgroundColor: '#F8F8FA',
      flexDirection: 'row',
      alignItems: 'flex-end',
      borderTopWidth: 1,
      borderColor: '#DCE6F0'
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, {
    disabled: isOrderSuccess(),
    onPress: handlePresentModalPress,
    style: {
      width: 56,
      height: 56,
      alignItems: 'center',
      justifyContent: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNativeFastImage.default, {
    source: require('../../assets/ic_attach.png'),
    tintColor: isOrderSuccess() ? '#B5B4B8' : _Styles.default.primary,
    style: {
      height: 24,
      width: 24,
      resizeMode: 'contain',
      tintColor: isOrderSuccess() ? '#B5B4B8' : _Styles.default.primary
    }
  })), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: {
      width: 1,
      height: '100%'
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: {
      width: 1,
      backgroundColor: '#DCE6F0',
      marginVertical: 14,
      flex: 1
    }
  })), /*#__PURE__*/_react.default.createElement(_Attach.Input, null), /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, {
    disabled: isOrderSuccess(),
    onPress: () => {
      if (_ChatStore.default.keyboardEmoji) {
        _ChatStore.default.keyboardEmoji = false;
      } else {
        _ChatStore.default.keyboardEmoji = true;
        _reactNative.Keyboard.dismiss();
      }
    },
    style: {
      width: 40,
      height: 56,
      alignItems: 'center',
      justifyContent: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNativeFastImage.default, {
    source: isOrderSuccess() ? require('../../assets/ic_emoji_disabled.png') : require('../../assets/ic_emoj.png'),
    style: {
      height: 24,
      width: 24,
      resizeMode: 'contain'
    }
  })), _InputStore.default.input.trim() !== '' && !isOrderSuccess() && /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, {
    onPress: sendMessage,
    style: {
      width: 40,
      height: 56,
      alignItems: 'center',
      justifyContent: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(_reactNativeFastImage.default, {
    source: require('../../assets/ic_send.png'),
    style: {
      height: 24,
      width: 24,
      resizeMode: 'contain'
    }
  })), _InputStore.default.input.trim() === '' && /*#__PURE__*/_react.default.createElement(_RecordButton.RecordButton, _extends({
    disabled: isOrderSuccess()
  }, props, {
    style: {
      width: 40,
      height: 56,
      alignItems: 'center',
      justifyContent: 'center'
    }
  }), /*#__PURE__*/_react.default.createElement(_reactNativeFastImage.default, {
    source: require('../../assets/ic_microphone.png'),
    style: {
      height: 24,
      width: 24,
      resizeMode: 'contain',
      tintColor: isOrderSuccess() ? '#B5B4B8' : _Styles.default.primary
    },
    tintColor: isOrderSuccess() ? '#B5B4B8' : _Styles.default.primary
  }))), _ChatStore.default.keyboardEmoji &&
  /*#__PURE__*/
  // <EmojiKeyboard
  //   styles={{
  //     container: { borderRadius: 0, backgroundColor: 'white' },
  //   }}
  //   onEmojiSelected={(emoji) => {
  //     chatStore.input += emoji.emoji;
  //   }}
  // />
  _react.default.createElement(_reactNativeEmojiPickerStaltz.default, {
    emojiStyle: {
      color: 'black'
    },
    hideClearButton: true,
    onEmojiSelected: emoji => {
      if (emoji !== null) {
        _InputStore.default.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