var lastscrollvalue;
var beforeHeight = window.innerHeight;
var beforeWidth = window.innerWidth;
var beforeScroll;

window.onscroll = function () {
  if (beforeScroll == window.scrollY) {
    return;
  }
  beforeScroll = window.scrollY;
  const beforeHeight = $(".room_container").height();
  messageCount = $(".chat_message").length;
  if ($(this).scrollTop() === 0 && messageCount >= PagingSize.MESSAGE) {
    if (!$("#chatLoader").is(":visible")) {
      let loader = $(
        '<div id="chatLoader" class="text-center"><div class="spinner-grow spinner-grow-sm" role="status" /></div>'
      );
      $("#messages").prepend(loader);
      const messageId = $($(".chat_message").get(0)).data("messageid");
      NativeBridgeDelegate.updatePreMessage(messageId);
      let messages = NativeBridgeDataSource.getMessagesWithMessageId(messageId);
      CHAT_UI.prependMessage(messages);
      loader.remove();
      var afterHeight = $(".room_container").height();
      window.scroll(0, afterHeight - beforeHeight);
    }
  }
};

document.addEventListener("DOMContentLoaded", function () {
  // 検索アイコン押下イベント
  $(".nav_item_wrap .search_menu").click(function () {
    $(".nav_item_wrap").addClass("none");
    $(".footer-wrap").addClass("none");
    $(".chat_room_src_form").removeClass("none");
    $(".room_container").addClass("none");
    $(".overlay_src_msg").removeClass("none");
    // フィルタ表示
    $("#filter").removeClass("none");
    $("#user_list").addClass("none");

    $('.chat_room_src_form input[type="search"]').focus();
    $("#searchMessage").addClass("onfocus");
    $(".chat_list").removeClass("none");
  });

  $(".chat_room_src_form .cancel").click(function () {
    $(".nav_item_wrap").removeClass("none");
    $(".footer-wrap").removeClass("none");
    $(".chat_room_src_form").addClass("none");
    $(".chat_room_src_form input").val("");
    $(".room_container").removeClass("none");
    $(".overlay_src_msg").empty();
    // ユーザーリスト表示
    $("#filter").addClass("none");
    $("#user_list").removeClass("none");

    $('.chat_room_src_form input[type="search"]').blur();
    $("#searchMessage").removeClass("onfocus");
    $(".chat_list").addClass("none");
    CHAT_UI.scrollToBottom();
  });

  $('.chat_room_src_form input[type="search"]').click(function () {
    if ($("#searchMessage").hasClass("onfocus")) {
      $("#searchMessage").removeClass("onfocus");
      $("#searchMessage").blur();
    } else {
      $("#searchMessage").addClass("onfocus");
      $("#searchMessage").focus();
    }
  });

  $("#searchMessage").blur(function () {
    $("#searchMessage").removeClass("onfocus");
  });

  // フィルタ選択イベント
  $(document).on("click", "#filter .img_wrap", function (event) {
    // チェックアイコン追加
    $(this).toggleClass("filter");
  });

  var footerHeight = $(".footer-wrap").height();
  window.addEventListener("resize", function () {
    var afterHeight = window.innerHeight;
    var afterWidth = window.innerWidth;
    var moreScroll = beforeHeight - afterHeight;
    if (beforeHeight > afterHeight && beforeHeight - afterHeight > 50) {
      if (deviceInfo.isiOS()) {
        window.scrollTo(0, beforeScroll + moreScroll);
      } else if (beforeWidth == afterWidth) {
        //キーボード表示時
        $(".room_container").css("margin-bottom", 0);
        window.scrollTo(
          0,
          beforeScroll + moreScroll - $(".footer_content_b").height()
        );
      } else {
        //画面回転時
        window.scrollTo(
          0,
          beforeScroll + moreScroll * 2 - $(".footer_content_b").height()
        );
      }
    } else if (beforeHeight < afterHeight) {
      $(".room_container").css("margin-bottom", footerHeight);
      if (deviceInfo.isIOS()) {
        window.scrollTo(0, beforeScroll + moreScroll);
      } else if (beforeWidth == afterWidth) {
        //キーボード非表示
        window.scrollTo(
          0,
          beforeScroll + moreScroll + $(".footer_content_b").height()
        );
      } else {
        //画面回転時
        window.scrollTo(
          0,
          beforeScroll + moreScroll * 2 + $(".footer_content_b").height()
        );
      }
    }
    beforeHeight = window.innerHeight;
    beforeWidth = window.innerWidth;
  });

  $("#messageInput").focusin(function (e) {
    beforeHeight = window.innerHeight;
    beforeWidth = window.innerWidth;
    beforeScroll = window.scrollY;
  });

  // チャットルーム
  // メッセージ検索イベント
  $('.chat_room_src_form input[type="search"]').keyup(function (e) {
    let workVal = "";
    var keyword = $('.chat_room_src_form input[type="search"]').val();
    if (e.key == "Enter" || e.KeyCode == 13) {
      if (keyword != "" && keyword.length != 0) {
        $('.chat_room_src_form input[type="search"]').blur();
        return;
      }
    } else if (keyword == "" || keyword.length < 2) {
      $(".overlay_src_msg").empty();
      return;
    }
    CHAT.searchMessage(keyword, workVal);
    if (e.key == "Enter" || e.KeyCode == 13) {
      $("#searchMessage").removeClass("onfocus");
      $('.chat_room_src_form input[type="search"]').blur();
      return;
    }
  });
  // iOSキーボード変換検知用
  $('.chat_room_src_form input[type="search"]').on(
    "compositionend",
    function () {
      if (deviceInfo.isIOS()) {
        let workVal = "";
        var keyword = $('.chat_room_src_form input[type="search"]').val();
        CHAT.searchMessage(keyword, workVal);
      }
    }
  );

  $(document).on("click", ".filter_img", function (event) {
    let workVal = "";
    var keyword = $('.chat_room_src_form input[type="search"]').val();
    $(".overlay_src_msg").empty();
    let checkedUserList = getCheckedUserList();
    if (keyword.length == 1) {
      return;
    }
    const messages = NativeBridgeDataSource.searchMessages(
      keyword,
      checkedUserList.join(",")
    );
    var userMessageTemplate = getTemplate(TemplateURL.USER_MESSAGE);
    var myMessageTemplate = getTemplate(TemplateURL.MY_MESSAGE);

    let jQueryMessages = $(".overlay_src_msg");
    messages.forEach(function (message) {
      let template = userMessageTemplate;
      if (message.shopMemberId == currentUserInfo.shopMemberId) {
        template = myMessageTemplate;
      }
      if (message.messageType == MessageType.SYSTEM) {
        template = systemMessageTemplate;
      }
      let messageTime = CHAT_UTIL.formatDate(message.insertDate);

      // ユーザの様式を読み込む
      if (message.profileUrl) {
        message.profileUrl = Common.getProfileImgUrl(message.profileUrl);
      } else {
        message.profileUrl = Common.getProfileImgUrl("");
      }
      message.message = message.message.toString();
      var replacePath = message.message;
      replacePath = replacePath.replaceAll(
        "?fileName=",
        "?sid=" + currentUserInfo.sid + "&fileName="
      );
      message.message = replacePath;

      let html = Mustache.render(template, {
        text: message.message,
        from: message.loginId,
        shopMemberId: message.shopMemberId,
        profileImage: message.profileUrl,
        createdAtDay: messageTime.createdAtDay,
        createdAtTime: messageTime.createdAtTime,
      });
      html =
        message.message.includes("attachedImages") ||
        message.message.includes("attachedVideos")
          ? CHAT_UTIL.htmlDecode(html)
          : html;
      workVal = html + workVal;
    });
    jQueryMessages.prepend(workVal);
  });

  $(".message_input_form").on("focus", function (e) {
    setTimeout(function () {
      $(".message_input_send").removeClass("none");
      $(".attach_file").addClass("none");
      $(".footer_content_b").addClass("none");
    }, 10);
  });

  $(".message_input_form").on("focusout", function (e) {
    setTimeout(function () {
      if ($(e.relatedTarget).hasClass("message_input_send")) {
        CHAT_UI.sendMessage();
      } else {
        $(".message_input_send").addClass("none");
        $(".attach_file").removeClass("none");
        $(".footer_content_b").removeClass("none");
      }
    }, 10);
  });
});

var getCheckedUserList = function () {
  let checkedUserList = [];
  $(".img_wrap.filter").each(function (user) {
    const selectedUser = $(".img_wrap.filter")[user];
    checkedUserList.push($(selectedUser).data("user-id"));
  });
  return checkedUserList;
};

//　メッセージ検索
CHAT.searchMessage = function (keyword, workVal) {
  $(".overlay_src_msg").empty();
  var checkedUserList = [];
  $(".img_wrap.filter").each(function (user) {
    const selectedUser = $(".img_wrap.filter")[user];
    checkedUserList.push($(selectedUser).data("user-id"));
  });
  var messages = NativeBridgeDataSource.searchMessages(
    keyword,
    checkedUserList.join(",")
  );
  var userMessageTemplate = getTemplate(TemplateURL.USER_MESSAGE);
  var myMessageTemplate = getTemplate(TemplateURL.MY_MESSAGE);

  let jQueryMessages = $(".overlay_src_msg");
  messages.forEach(function (message) {
    let template = userMessageTemplate;
    if (message.shopMemberId == currentUserInfo.shopMemberId) {
      template = myMessageTemplate;
    }
    if (message.messageType == MessageType.SYSTEM) {
      template = systemMessageTemplate;
    }
    let messageTime = CHAT_UTIL.formatDate(message.insertDate);
    let messageTime = CHAT_UTIL.formatDate(message.insertDate);
    if (message.profileUrl) {
      message.profileUrl = Common.getProfileImgUrl(message.profileUrl);
    } else {
      message.profileUrl = Common.getProfileImgUrl("");
    }
    message.message = message.message.toString();
    var replacePath = message.message;
    replacePath = replacePath.replaceAll(
      "?fileName=",
      "?sid=" + currentUserInfo.sid + "&fileName="
    );
    message.message = replacePath;
    let html = Mustache.render(template, {
      text: message.message,
      from: message.loginId,
      shopMemberId: message.shopMemberId,
      profileImage: message.profileUrl,
      createdAtDay: messageTime.createdAtDay,
      createdAtTime: messageTime.createdAtTime,
    });
    html =
      message.message.includes("attachedImages") ||
      message.message.includes("attachedVideos")
        ? CHAT_UTIL.htmlDecode(html)
        : html;
    workVal = html + workVal;
  });
  jQueryMessages.prepend(workVal);
  if (messages.length == 0) {
    const noResultMsg = getNoResultMessage();
    jQueryMessages.append(noResultMsg);
  }
};

// 下スクロールでユーザーリストを非表示
var startPos = 0;
var winScrollTop = 0;
$(window).on("scroll", function () {
  winScrollTop = $(this).scrollTop();
  if (winScrollTop >= startPos) {
    if (winScrollTop >= 200) {
      $("#chat_room .user_list").addClass("hide");
    }
  } else {
    $("#chat_room .user_list").removeClass("hide");
  }
  startPos = winScrollTop;
});

//メッセージ送信
$("#messageInput").on("keypress", function (event) {
  if (event.which == 13) {
    // Enterキーの処理
    $("#messageSend").click();
  }
});

//上にスクロールすると新しいメッセージを呼ぶ処理。
$("#messages").scroll(function () {
  if ($(this).scrollTop() === 0) {
    if (!$("#chatLoader").is(":visible")) {
      // 現在、メッセージの個数以前をメッセージを読み込む
      // ローディングアイコンを追加する
      let loader = $(
        '<div id="chatLoader" class="text-center"><div class="spinner-grow spinner-grow-sm" role="status" /></div>'
      );
      $("#messages").prepend(loader);
      loader.remove();
    }
  }
});

CHAT_UI.startCollaboration = function (collaborationType) {
  if (deviceInfo.isAndroid()) {
    if (
      collaborationType == COLLABORATION_TYPE.DOCUMENT &&
      androidVersion < ANDROID_SDK_VERSION.O
    ) {
      alert(getLocalizedString("not_support_version"));
      return;
    }
  }

  if ($(".collabo_area.start").length != 0) {
    if (!confirm(getLocalizedString("already_exist_collaboration"))) {
      Common.dismissLoadingIndicator();
      return;
    }
    const sendData = DATA_MESSAGE_SCHEME + FINISH_ALL_COLLABORATION_SIGNAL;
    CHAT_SOCKET.emitCreateMessage(sendData, 0);
    NativeBridgeDelegate.finishAllCollaboration();
  }
  NativeBridgeDelegate.startCollaboration(collaborationType);
};

CHAT_UI.sendMessage = function (e) {
  const messageTextBox = $("#messageInput");
  const message =
    messageTextBox.val().length > 0
      ? encodeURIComponent(messageTextBox.val())
      : "";
  messageTextBox.val("");

  if (message.length > 0) {
    const sendData = message + messageSeperator + MessageType.TEXT;
    CHAT_SOCKET.emitCreateMessage(sendData, 0);
  }
  $(".message_input_form").focus();
};

CHAT_UI.loadMessages = function (roomId, joinRoomName) {
  roomName = joinRoomName;
  if (serverInfo.isOnline == "true") {
    Common.refreshForOnline();
    NativeBridgeDelegate.updateMessages(roomId);
  } else {
    Common.refreshForOffline();
  }
  const roomType = NativeBridgeDataSource.getRoomType();
  if (roomType == ChatRoomType.DM) {
    $("#roomMenu").removeClass("none");
  }
  var messages = NativeBridgeDataSource.getMessages(roomId);
  var usersInRoom = NativeBridgeDataSource.getUsersInRoom(roomId);

  $("#roomTitle").text(roomName).data("roomName", roomName);
  let jQueryMessages = $("#messages");
  // スクロールの変化を防ぐため以前画面の高さを保存する
  let beforeHeight = jQueryMessages.prop("scrollHeight");

  var userTemplate = getTemplate(TemplateURL.USER_LIST);

  var topUserListTemplate = getTemplate(TemplateURL.CHATROOM_USER_LIST);

  var filterUserListTemplate = getTemplate(
    TemplateURL.CHATROOM_USER_FILTER_LIST
  );

  usersInRoom.forEach(function (user) {
    user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
  });
  let html = Mustache.render(topUserListTemplate, {
    userList: usersInRoom,
  });
  let obj = jQuery.parseHTML(html);
  $("#user_list").append(obj);

  let filterHtml = Mustache.render(filterUserListTemplate, {
    userList: usersInRoom,
  });
  let filterObj = jQuery.parseHTML(filterHtml);
  $("#filter").append(filterObj);

  CHAT_UI.prependMessage(messages);

  CHAT_UI.waitForLoadingImage(jQueryMessages, CHAT_UI.scrollToBottom);
  CHAT_UI.waitForLoadingVideo(jQueryMessages, CHAT_UI.scrollToBottom);

  if (deviceInfo.isiOS()) {
    $(window).on("load", function () {
      CHAT_UI.scrollToBottom();
    });
  }
};


CHAT_UI.prependMessage = function (messages) {
  var now = new Date();
  let jQueryMessages = $("#messages");
  // スクロールの変化を防ぐため以前画面の高さを保存する
  let beforeHeight = jQueryMessages.prop("scrollHeight");
  // メッセージ文字列の生成
  let workVal = "";
  var userTemplate = getTemplate(TemplateURL.USER_LIST);

  var userMessageTemplate = getTemplate(TemplateURL.USER_MESSAGE);

  var myMessageTemplate = getTemplate(TemplateURL.MY_MESSAGE);

  var systemMessageTemplate = getTemplate(TemplateURL.SYSTEM_MESSAGE);

  var openCollaborationMessageTemplate = getTemplate(
    TemplateURL.OPEN_COLLABORATION_MESSAGE
  );
  var checkBeforeDate = "";
  var beforeDate = "";
  messages.forEach(function (message) {
    let template = userMessageTemplate;
    if (message.shopMemberId == currentUserInfo.shopMemberId) {
      template = myMessageTemplate;
    }
    if (message.messageType == MessageType.SYSTEM) {
      template = systemMessageTemplate;
    }
    if (
      message.messageType == MessageType.COMMUNICATIONSTART ||
      message.messageType == MessageType.COMMUNICATIONEND
    ) {
      template = openCollaborationMessageTemplate;
    }
    let messageTime = CHAT_UTIL.formatDate(message.insertDate);
    // ユーザの様式を読み込む

    if (message.profileUrl) {
      message.profileUrl = Common.getProfileImgUrl(message.profileUrl);
    } else {
      message.profileUrl = Common.getProfileImgUrl("");
    }

    // #36147
    message.message = message.message.toString();
    var replacePath = message.message;
    replacePath = replacePath.replaceAll(
      "?fileName=",
      "?sid=" + currentUserInfo.sid + "&fileName="
    );
    message.message = replacePath;
    /* if (message.message contain) {
         }*/
    var isOtherYear = false;
    var isToday = false;
    if (messageTime.createdAt.includes(":")) {
      isToday = true;
    }
    if (now.getFullYear() != message.insertDate.substring(0, 4)) {
      isOtherYear = true;
    }
    if (messageTime.createdAtDay != checkBeforeDate && checkBeforeDate != "") {
      let messageDay = CHAT_UTIL.systemDay(beforeDate);
      let html = Mustache.render(systemMessageTemplate, {
        year: messageDay.year + getLocalizedString("year"),
        month: messageDay.month + getLocalizedString("month"),
        day: messageDay.day + getLocalizedString("day"),
        dow: CHAT_UTIL.findDow(messageDay.dow),
      });
      workVal = html + workVal;
    }
    checkBeforeDate = messageTime.createdAtDay;
    beforeDate = message.insertDate;

    if (
      message.messageType == MessageType.COMMUNICATIONSTART ||
      message.messageType == MessageType.COMMUNICATIONEND
    ) {
      const collaborationInfo = JSON.parse(message.message);
      const userInCollaboration = JSON.parse(
        NativeBridgeDataSource.getUserInfoList(collaborationInfo.userList)
      );

      var meetingId = 0;
      if (typeof collaborationInfo.meetingId != "undefined") {
        meetingId = collaborationInfo.meetingId;
      }
      userInCollaboration.forEach(function (user) {
        user.profileUrl = Common.getProfileImgUrl(user.profileUrl);
      });
      let html = Mustache.render(template, {
        messageId: message.messageId,
        roomName: roomName,
        userCount: userInCollaboration.length,
        userList:
          userInCollaboration.length > 3
            ? userInCollaboration.slice(0, 3)
            : userInCollaboration,
        insertDate: message.insertDate,
        collaborationType: collaborationInfo.collaborationType,
        meetingId: meetingId,
        isToday: isToday,
        createdAtDay: messageTime.createdAtDay,
        createdAtTime: messageTime.createdAtTime,
        createdAtYear:
          message.insertDate.substring(0, 4) + getLocalizedString("year") + " ",
        isOtherYear: isOtherYear,
        isEnded:
          message.messageType == MessageType.COMMUNICATIONEND ? true : false,
      });
      html =
        message.message.includes("attachedImages") ||
        message.message.includes("attachedVideos")
          ? CHAT_UTIL.htmlDecode(html)
          : html;
      workVal = html + workVal;
    } else {
      let html = Mustache.render(template, {
        text: message.message,
        from: message.loginId,
        messageId: message.messageId,
        shopMemberId: message.shopMemberId,
        profileImage: message.profileUrl,
        createdAtDay: messageTime.createdAtDay,
        createdAtTime: messageTime.createdAtTime,
        createdAtYear:
          message.insertDate.substring(0, 4) + getLocalizedString("year") + " ",
        unreadCount: message.unreadCount,
        isOtherYear: isOtherYear,
        isToday: isToday,
      });
      html =
        message.message.includes("attachedImages") ||
        message.message.includes("attachedVideos")
          ? CHAT_UTIL.htmlDecode(html)
          : html;
      workVal = html + workVal;
    }
  });
  // メッセージの画面描画
  jQueryMessages.prepend(workVal);
};

// 画像の読み込みが全て終わったタイミングでコールバック実行
// FIXME 追加読み込みの場合は差分の画像のみ監視すべきだが、現状新規入室時にしか対応出来ていない。
CHAT_UI.waitForLoadingVideo = function (div, callback) {
  Common.showLoadingIndicator();
  //    var imgs = document.getElementsByTagName("video");
  var video = div.find("video");
  var count = video.length;
  if (count == 0) callback();
  var loaded = 0;
  video.each(function () {
    this.addEventListener("loadeddata", function (e) {
      loaded++;
      if (loaded === count) {
        callback();
        Common.dismissLoadingIndicator();
      }
    });
  });
};

CHAT_UI.waitForLoadingImage = function (div, callback) {
  var imgs = div.find("img");
  var count = imgs.length;
  if (count == 0) callback();
  var loaded = 0;
  imgs
    .one("load", function (e) {
      // イメージが読み込まれた
      loaded++;
      if (loaded === count) {
        callback();
      }
    })
    .each(function () {
      if (this.complete || this.readyState === readyState.COMPLETED) {
        $(this).trigger("load");
      }
    });
};

CHAT_UI.scrollToBottom = function () {
  const messages = $(".room_contents");
  const scrollHeight = messages.prop("scrollHeight");
  //messages.scrollTop(scrollHeight);
  $("html, body").animate(
    {
      scrollTop: scrollHeight,
    },
    100
  );
};

CHAT_UI.refreshForOnline = function () {
  serverInfo.isOnline = "true";
  $("#videoUploadButton").removeClass("ui-state-disabled");
  $("#imageInputButton").removeClass("ui-state-disabled");
  $("#messageSend").prop("disabled", false);
  $("#messageInput").prop("disabled", false);
  $("#messageInput").prop("placeholder", "メッセージを入力してください");
  $("#room_name_change_button").removeClass("ui-state-disabled");
  $("#add_user_button").removeClass("ui-state-disabled");
  $(".fa-download").show();

  if (typeof $("#roomTitle").val() != "undefined") {
    CHAT_SOCKET.initialJoin();
  }
};

CHAT_UI.refreshForOffline = function () {
  serverInfo.isOnline = "false";
  $("#videoUploadButton").addClass("ui-state-disabled");
  $("#imageInputButton").addClass("ui-state-disabled");
  $("#messageSend").prop("disabled", true);
  $("#messageInput").prop("disabled", true);
  $("#messageInput").prop("placeholder", "");
  $("#room_name_change_button").addClass("ui-state-disabled");
  $("#add_user_button").addClass("ui-state-disabled");
  $(".fa-download").hide();
};