"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _mobx = require("mobx");
var _services = _interopRequireWildcard(require("../../services"));
var _utils = require("../../utils");
var _reactNativeUuid = _interopRequireDefault(require("react-native-uuid"));
var _resizeImage = _interopRequireDefault(require("../../components/resizeImage"));
var _uploadProgress = _interopRequireDefault(require("./uploadProgress"));
var _InputStore = _interopRequireDefault(require("./InputStore"));
var _waveView = _interopRequireDefault(require("../../components/waveView"));
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 _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var _ = require('lodash');
class ChatStore {
  constructor() {
    _defineProperty(this, "isLoading", false);
    _defineProperty(this, "isLoadingMore", false);
    _defineProperty(this, "canLoadMore", true);
    _defineProperty(this, "isError", false);
    _defineProperty(this, "error", 0);
    _defineProperty(this, "page", 0);
    _defineProperty(this, "tab", 1);
    _defineProperty(this, "conversation_id", '');
    _defineProperty(this, "input", '');
    _defineProperty(this, "keyboardEmoji", false);
    _defineProperty(this, "data", []);
    _defineProperty(this, "images", []);
    _defineProperty(this, "queue", []);
    _defineProperty(this, "showAttachModal", false);
    _defineProperty(this, "location", {
      latitude: 0,
      longitude: 0
    });
    _defineProperty(this, "tabImage", void 0);
    _defineProperty(this, "tabQuickMessage", void 0);
    _defineProperty(this, "tabLocationMessage", void 0);
    _defineProperty(this, "quote", void 0);
    _defineProperty(this, "intervalSound", void 0);
    _defineProperty(this, "pauseSound", void 0);
    _defineProperty(this, "soundBarsRefs", {});
    _defineProperty(this, "delay", delayInms => {
      return new Promise(resolve => setTimeout(resolve, delayInms));
    });
    (0, _mobx.makeAutoObservable)(this);
  }
  onChangeTextChat(emoji) {
    this.input += emoji;
  }
  resetData() {
    this.isLoading = false;
    this.isLoadingMore = false;
    this.canLoadMore = true;
    this.isError = false;
    this.error = 0;
    this.page = 0;
    this.tab = 1;
    this.conversation_id = '';
    this.input = '';
    this.data = [];
    this.images = [];
    this.showAttachModal = false;
  }
  async getData(params, onSuccess, onError) {
    this.conversation_id = params.conversation_id;
    try {
      if (this.page !== 0 && (this.isLoading || this.isLoadingMore || !this.canLoadMore)) {
        return;
      }
      this.page += 1;
      if (this.page === 1) {
        this.isLoading = true;
        this.canLoadMore = false;
      } else {
        this.isLoadingMore = true;
      }
      const response = await _services.default.create().conversationMessages({
        ...params,
        ...{
          page: this.page
        }
      });
      this.isLoading = false;
      this.isLoadingMore = false;
      (0, _utils.Log)(response);
      if (response.status === 200) {
        if (response.data.status === 200) {
          if (response.data.data) {
            if (this.page === 1) {
              this.data = response.data.data;
              if (this.quote !== undefined) {
                this.data = [chatStore.quote, ...this.data];
              }
            } else {
              this.data = [...this.data, ...response.data.data];
            }
            this.canLoadMore = response.data.data.length > 0;
            this.isError = false;
            if (onSuccess) {
              onSuccess(this.data);
            }
          }
        } else {
          // alert(response.data.message)
        }
      } else {
        this.isLoading = false;
        this.isLoadingMore = false;
        this.isError = true;
        // if (onError) {
        //   onError('');
        // }
      }
    } catch (error) {
      this.isLoading = false;
      this.isLoadingMore = false;
      this.isError = true;
      // if (onError) {
      //   onError(JSON.stringify(error));
      // }
      (0, _utils.Log)(error);
    }
  }
  async getDataBackground() {
    try {
      _services.default.create().conversationMessages({
        conversation_id: this.conversation_id,
        page: 1
      }).then(response => {
        if (response.status === 200) {
          if (response.data.status === 200) {
            if (response.data.data) {
              this.data = _.unionBy(response.data.data, (0, _mobx.toJS)(this.data), "_id");
            }
          }
        }
      });
    } catch (error) {
      (0, _utils.Log)(error);
    }
  }
  async getOrderInfoVTM(order_number) {
    try {
      const response = await _services.default.create().getOrderInfoVTM({
        order_number: order_number
      });
      if (response.status === 200) {
        if (response.data.status === 200 && response.data.data) {
          var _response$data$data;
          if (this.quote && ((_response$data$data = response.data.data) === null || _response$data$data === void 0 ? void 0 : _response$data$data.order_number) === this.quote.order_number) {
            var _response$data$data2, _response$data$data3;
            this.quote.order_info.vtp_order = {
              ...this.quote.order_info.vtp_order,
              ...{
                product_name: (_response$data$data2 = response.data.data) === null || _response$data$data2 === void 0 ? void 0 : _response$data$data2.product_name,
                status_name: (_response$data$data3 = response.data.data) === null || _response$data$data3 === void 0 ? void 0 : _response$data$data3.status_name
              }
            };
            this.quote = {
              ...this.quote
            };
          }
          // if (response.data.data) {
          //   this.data = _.unionBy(response.data.data, toJS(this.data), "_id");
          // }
        }
      }
    } catch (error) {
      (0, _utils.Log)(error);
    }
  }
  async sendMessage(params) {
    try {
      var _InputStore$inputRef, _InputStore$inputRef$;
      (_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();
    } catch (e) {}
    const quoteCopy = {
      ...this.quote
    };
    if (this.quote) {
      this.quote = undefined;
      await this.sendMessage(quoteCopy);
    }
    console.log('sendMessage', params);
    let attachment_ids = [];
    if (params.attachmentLocal) {
      const formData = new FormData();
      for (let i = 0; i < params.attachmentLocal.length; i++) {
        var _extension;
        let extension = params.attachmentLocal[i].extension;
        if (params.attachmentLocal[i].name == null) {
          extension = params.attachmentLocal[i].uri.split(".").pop().toLowerCase();
        } else {
          extension = params.attachmentLocal[i].name.split(".").pop().toLowerCase();
        }
        extension = (_extension = extension) === null || _extension === void 0 ? void 0 : _extension.toLowerCase();
        let fileUri = '';
        if (extension === 'mov' || extension === 'mp4') {
          fileUri = params.attachmentLocal[i].uri;
          formData.append("files", {
            name: _reactNativeUuid.default.v4() + '.' + extension,
            uri: fileUri,
            type: 'video/' + extension
          });
        } else if (extension === 'doc' || extension === 'pdf' || extension === 'xls') {
          try {
            fileUri = params.attachmentLocal[i].uri;
            formData.append("files", {
              name: _reactNativeUuid.default.v4() + '.' + extension,
              uri: fileUri,
              type: params.attachmentLocal[i].type
            });
          } catch (e) {}
        } else if (extension === 'jpg' || extension === 'png' || extension === 'jpeg' || extension === 'heic') {
          let absolutePath = params.attachmentLocal[i].uri;
          // if (Platform.OS === 'android'){

          if (params.attachmentLocal[i].width >= 900 || params.attachmentLocal[i].height >= 900) {
            try {
              const result = await _resizeImage.default.createResizedImage(absolutePath, 900, 900, 'JPEG', 80, 0);
              fileUri = result.uri;
            } catch (e) {
              fileUri = absolutePath;
              console.log(e);
            }
          } else {
            fileUri = absolutePath;
          }
          try {
            formData.append("files", {
              name: _reactNativeUuid.default.v4() + '.' + extension,
              uri: fileUri,
              type: 'image/' + extension
            });
          } catch (e) {}
        } else {
          try {
            formData.append("files", {
              name: params.attachmentLocal[i].name,
              uri: params.attachmentLocal[i].uri,
              type: 'image/' + extension
            });
          } catch (e) {}
        }
      }
      const response = await _services.default.create().uploadFile(formData, progress => {
        _uploadProgress.default.progress[params.id] = Math.round(progress.loaded / progress.total * 100);
      });
      try {
        if (response.data.data) {
          attachment_ids = response.data.data.map(a => a._id);
        }
      } catch (e) {
        if (response.status === 201) {
          return;
        }
        this.data = this.data.map(item => {
          if (item.id === params.id && item.id) {
            item.status = 'error';
          }
          return item;
        });
        return;
      }
    }
    const response = await _services.default.create().sendMessage({
      ...params,
      ...{
        attachment_ids: attachment_ids
      }
    });
    (0, _utils.Log)(response);
    if (response.status === 201 && response.data.status === 200) {
      this.data = [...this.data.map(item => {
        if (item.id === params.id && item.id) {
          var _response$data$data4, _response$data$data4$, _response$data$data5, _response$data$data5$, _response$data$data6, _response$data$data6$;
          item.status = 'sent';
          item.attachmentLocal = [];
          item.attachments = (_response$data$data4 = response.data.data) !== null && _response$data$data4 !== void 0 && (_response$data$data4$ = _response$data$data4.message) !== null && _response$data$data4$ !== void 0 && _response$data$data4$.attachments ? (_response$data$data5 = response.data.data) === null || _response$data$data5 === void 0 ? void 0 : (_response$data$data5$ = _response$data$data5.message) === null || _response$data$data5$ === void 0 ? void 0 : _response$data$data5$.attachments : [];
          // item.id = undefined
          item._id = (_response$data$data6 = response.data.data) === null || _response$data$data6 === void 0 ? void 0 : (_response$data$data6$ = _response$data$data6.message) === null || _response$data$data6$ === void 0 ? void 0 : _response$data$data6$._id;
        }
        return item;
      })];
    } else {
      this.data = this.data.map(item => {
        if (item.id === params.id && item.id) {
          item.status = 'error';
        }
        return item;
      });
    }
  }
}
const chatStore = new ChatStore();
var _default = chatStore;
exports.default = _default;
//# sourceMappingURL=ChatStore.js.map