import chatApi from "~/apis/chatApi";
import repoApi from "~/apis/repoApi";

export default {
  methods: {
    // #region replays methods
    closeReplays() {
      this.showReplays = false;
      this.resetReplayPagination();
      this.replays = [];
      this.replayFinishedTop = false;
      this.replayFinishedBottom = false;
      this.replayOverflow = false;
    },
    allReplayers(comment, replayUsers) {
      let newUsers = [];

      if (comment.replys)
        comment.replys.users.forEach((user) => {
          replayUsers.forEach((item) => {
            if (user == item.user_id) newUsers.push(item);
          });
        });
      return newUsers;
    },
    async getReplays(
      fill_limit = false,
      by_first_message = false,
      seen_date = undefined,
      page = undefined,
      message_id = undefined
    ) {
      // if (this.fetchinReplaygData) return;
      // this.fetchinReplaygData = true;

      let group_id = this.listGetter.id;
      // groups,lobbies
      let payload = {
        group_id: group_id,
        contact_id: undefined,
        replyto: this.replayTo.id,
      };

      if (this.listGetter && this.listGetter?.is_group == 0) {
        payload.group_id = undefined;
        payload.contact_id = this.listGetter?.user;
      }

      if (seen_date == undefined) seen_date = this.replayPagination.seen_date;

      //پیام منطبق با تاریخ درخواستی نیاید
      if (!by_first_message && seen_date > 0) seen_date++;
      if (page == undefined) page = this.replayPagination.page;

      payload = {
        ...payload,
        offset: 0,
        limit: this.replayLimit,
        seen_date: seen_date,
        page: page,
        message_id: message_id,
      };

      return await this.httpService
        .postRequest("message/" + chatApi.messages.virtualList, payload)
        .then((response) => {
          // set replays for render on the left side.
          let replays = undefined;

          if (response.data && response.data.length) {
            replays = structuredClone(response);

            this.setUsers(replays.data, response.users);
          }

          // this.localComments = response.data;
          // this.replays.forEach((item) => {
          //   item.user = response.users.find(
          //     (user) => user.user_id == item.user
          //   );
          //   if (item.replys)
          //     item.replys.users = this.allReplayers(item, response.users);
          // });

          this.replayPagination.total = response.pagination.total;

          // this.replayPagination = {
          //   ...this.replayPagination,
          //   ...response.pagination,
          // };

          return replays;
        })
        .finally(() => {
          // this.fetchinReplaygData = false;
        });
    },
    saveReplay() {
      if (this.savingReplay) return;
      this.savingReplay = true;

      let payload = {
        text: this.replayText,
        group_id: this.listGetter.id,
        id: this.replayCommentor?.id ?? undefined,
        contact_id: undefined,
        replyto: this.replayTo?.id ?? undefined,
      };

      if (this.$route.name == "privates") {
        payload = {
          text: this.replayText,
          id: this.replayCommentor?.id ?? undefined,
          group_id: undefined,
          contact_id: this.listGetter.user,
          replyto: this.replayTo?.id ?? undefined,
        };
      }

      let url = "message/" + chatApi.messages.create;
      payload.text = this.replaceTextWithLink(payload.text);

      this.httpService
        .formDataRequest(url, payload)
        .then((res) => {
          // this.mySwalToast({
          //   html: res?.message ?? "",
          // });

          if (this.isReplayEditMode) {
            this.replayCommentor = {};
          }

          this.replayText = null;
          this.toReplayLastItem();
          this.updateMessageCount(res);

          // this.getReplays(

          // ).then(() => {
          //   this.updateMessageCount();
          // });
        })

        .finally(() => {
          this.savingReplay = false;
          this.isReplayEditMode = false;
          this.replyComment = false;
        });
    },
    // #endregion

    async replaySaveFiles() {
      let payload = {
        text: this.uploadDescription,
        group_id: this.listGetter.id,
        id: this.mainCommentor?.id ?? undefined,
        contact_id: undefined,
        replyto: this.replayTo?.id ?? undefined,
      };

      if (this.$route.name == "privates") {
        payload = {
          text: this.uploadDescription,
          id: this.replayTo?.id ?? undefined,
          contact_id: this.listGetter.user,
        };
      }

      let url = chatApi.messages.create;
      // when screen shot paste, decide where to save it.(replay or message)

      // if (
      //   payload.file.type == "" &&
      //   payload.file.name == "mp3" &&
      //   payload.file.size <= 20000
      // ) {
      //   // 20KB
      //   this.mySwalToast({
      //     icon: "warn",
      //     text: "حداقل صوت قابل آپلود 20 کیلو بایت می باشد.",
      //   });
      // } else
      // 'Content-Type': 'application/x-www-form-urlencoded'

      if (this.files.length > 1) {
        this.files.forEach((fileItem) => {
          payload.file = fileItem;
          payload.length = fileItem.size;

          this.httpService
            .formDataRequest(messageUrl() + url, payload)
            .then((res) => {
              this.replayText = null;
              this.uploadDescription = null;
              this.toReplayLastItem();
              this.updateMessageCount(res);
            })
            .catch(() => {
              this.mySwalToast({
                html: "خطایی رخ داد.لطفا دوباره امتحان کنید.",
              });
            });
        });
      } else {
        //  0: files, 1: image, 2:audio  3:video
        // payload.file_type = this.getFileType(this.files[0].name);
        payload.file = this.files[0];
        payload.length = this.files[0].size;

        return await this.httpService
          .formDataRequest(messageUrl() + url, payload)
          .then((res) => {
            this.closeDroppedList();
            this.replayText = null;
            this.uploadDescription = null;
            this.toReplayLastItem();
            this.updateMessageCount(res);
          })
          .catch(() => {
            this.mySwalToast({
              html: "خطایی رخ داد.لطفا دوباره امتحان کنید.",
            });
          });
      }
    },
    replayToTop() {
      if (this.replayFinishedTop) return;

      --this.replayPagination.pageTop;
      this.replayPagination.page = this.replayPagination.pageTop;
      const vm = this;

      this.getReplays().then((response) => {
        if (!response?.data?.length) {
          vm.replayFinishedTop = true;
          vm.replayPagination.pageTop++;
          vm.replayPagination.page = vm.replayPagination.pageTop;
          return;
        }

        const vsl = vm.$refs.replayVsl;
        let prev_size = vsl.getScrollSize();
        vm.replays = response.data.concat(vm.replays);

        vm.$nextTick(() => {
          const offset = vsl.getScrollSize() - prev_size;
          vm.replaySetVirtualListToOffset(offset);
        });
      });
    },
    replayToBottom() {
      if (this.replayFirstLoad) {
        this.replayFirstLoad = false;
        return;
      }

      if (this.replayFinishedBottom) return;

      ++this.replayPagination.pageBottom;
      this.replayPagination.page = this.replayPagination.pageBottom;

      this.getReplays().then((response) => {
        if (!response?.data?.length) {
          this.replayFinishedBottom = true;
          this.replayPagination.pageBottom--;
          this.replayPagination.page = this.replayPagination.pageBottom;
          return;
        }

        this.replays = [...this.replays, ...response.data];

        this.$nextTick(() => {
          const vsl = this.$refs.replayVsl;
          const offset = vsl.getScrollSize();
          this.replaySetVirtualListToOffset(offset);
          this.fetchingData = false;
        });
      });
    },
    toReplayFirstItem() {
      this.replayPagination.pageBottom = 1;
      this.replayPagination.pageTop = 0;
      this.replayPagination.page = 1;
      this.replayPagination.seen_date = 0;
      this.getReplays().then((response) => {
        if (!response.data.length) {
          return;
        }

        this.replays = response.data;

        // const mids = this.getMids(response.data)
        this.$nextTick(() => {
          this.replayOffset = 0;
          this.replaySetVirtualListToOffset(this.replayOffset);
          this.fetchingData = false;
        });
      });
    },
    toReplayLastItem() {
      this.replayPagination.pageBottom = 0;
      this.replayPagination.pageTop = -1;
      this.replayPagination.page = -1;
      this.replayPagination.seen_date = -1;

      this.getReplays().then((response) => {
        if (!response.data.length) {
          return;
        }

        this.replays = response.data;

        // const mids = this.getMids(response.data)
        this.$nextTick(() => {
          const vsl = this.$refs.replayVsl;
          this.offset = vsl.getScrollSize();
          this.replaySetVirtualListToOffset(this.replayOffset);
          this.fetchingData = false;
        });
      });
    },
    async replayOnResult(data) {
      this.files = [];
      this.files.push(new File([data], "mp3"));

      // if (this.replayAbortRecord) return;
      // this.replayAbortRecord = true;

      this.replaySaveFiles().then(() => {
        // this.replayRecording = false;
        // this.replayAbortRecord = false;
      });
    },
    showReplyComment() {
      const myReply = document.getElementById("show_reply");
      myReply.style.display = "none";
    },
    closeReplyComment(isEditModeName) {
      this.replyComment = false;
      this[isEditModeName] = false;
      this.replayText = null;
      // try {
      //   this.$refs.replays.style.removeProperty("height");
      //   this.$refs.replayTextRef.style.removeProperty("height");
      // } catch (err) {
      //   this.$refs.replays.style.height = null;
      //   this.$refs.replayTextRef.style.height = null;
      // }
    },
    resetReplayPagination() {
      this.replayPagination = {
        page: 0,
        total: 0,
        pageTop: 0,
        pageBottom: 1,
        seenDate: null,
      };
    },
  },
};