<template>
  <view class="page_container" :class="{ ios_page: isIos }">
    <z-paging
      ref="paging"
      :fixed="false"
      loading-full-fixed
      default-page-size="20"
      refresher-background="#05263c"
      v-model="momentsList"
      :show-loading-more-no-more-view="false"
      @query="queryList"
      @scroll="onScroll">
      <moments-header
        :needTransparent="needTransparent"
        @topbarClick="topbarClick"
      />
      <moments-item
        v-for="item in momentsList"
        :key="item.workMomentID"
        :moments="item"
        @startComent="startComent"
      />
      <view slot="loading" class="loading_wrap">
        <u-loading-icon text="加载中"></u-loading-icon>
      </view>
      <comment-input
        slot="bottom"
        ref="commentInputRef"
        v-show="commenting"
        :loading="commentLoading"
        :commenting="commenting"
        :placeholder="placeholder"
        @completeInput="sendComment"
        @hiddenInput="commenting = false"
      />
    </z-paging>
  </view>
</template>

<script>
import { v4 as uuidv4 } from "uuid";
import IMSDK from "openim-uniapp-polyfill";
import CustomNavBar from "../../../components/CustomNavBar/index.vue";
import { commentMoments, getSelfMomentsSplit } from "../../../api/moments";
import MomentsHeader from "./components/MomentsHeader.vue";
import MomentsItem from "./components/MomentsItem.vue";
import CommentInput from "./components/CommentInput.vue";
import { PageEvents } from "../../../constant";
export default {
  components: {
    MomentsHeader,
    MomentsItem,
    CustomNavBar,
    CommentInput,
  },
  data() {
    return {
      commenting: false,
      isFocus: false,
      needTransparent: true,
      momentsList: [],
      commentState: {
        workMomentID: "",
        comment: {},
      },
      commentLoading: false,
      isIos: uni.$u.os() === "ios",
    };
  },
  computed: {
    placeholder() {
      if (this.commentState.comment.userID) {
        return `回复${this.commentState.comment.nickname}`;
      }
      return "评论";
    },
  },
  onLoad() {
    this.setPageListener();
    uni.addInterceptor("navigateTo", {
      success: () => {
        if (this.commenting) {
          this.commentState.workMomentID = "";
          this.commentState.comment = {};
          this.commenting = false;
        }
      },
    });
    IMSDK.subscribe(
      IMSDK.IMEvents.OnRecvCustomBusinessMessage,
      this.customMessageHandler,
    );
  },
  onUnload() {
    this.disposePageListener();
    IMSDK.unsubscribe(
      IMSDK.IMEvents.OnRecvCustomBusinessMessage,
      this.customMessageHandler,
    );
  },
  onShow() {
    this.$nextTick(() => this.$refs.commentInputRef.setKeyboardListener());
  },
  onHide() {
    this.$refs.commentInputRef.disposeKeyboardListener();
    uni.showTabBar();
  },
  methods: {
    customMessageHandler({ data }) {
      uni.$emit(PageEvents.RefreshMomentsUnreadCount);
      console.log("customMessageHandler", data);
      if (data.key.includes("wm_")) {
        const moments = JSON.parse(data.data).body;
        const tempArr = this.momentsList.map((item) => {
          if (item.workMomentID === moments.workMomentID) {
            item = { ...item, ...moments };
          }
          if (!item.content.metas) {
            item.content.metas = [];
          }
          if (!item.likeUsers) {
            item.likeUsers = [];
          }
          if (!item.comments) {
            item.comments = [];
          }
          if (!item.permissionUsers) {
            item.permissionUsers = [];
          }
          if (!item.atUsers) {
            item.atUsers = [];
          }
          return item;
        });
        console.log(tempArr);
        this.momentsList = tempArr;
      }
    },
    queryList(pageNo, pageSize) {
      console.log(pageNo, pageSize);
      getSelfMomentsSplit(pageNo)
        .then((res) => {
          console.log(res);
          this.$refs.paging.complete(res.workMoments);
        })
        .catch((err) => uni.$u.toast("获取工作圈数据失败！"));
    },
    startComent(workMomentID, comment) {
      this.commentState.workMomentID = workMomentID;
      this.commentState.comment = comment || {};
      this.commenting = true;
      this.$nextTick(() => (this.isFocus = true));
    },
    sendComment(content) {
      this.commentLoading = true;
      commentMoments(
        this.commentState.workMomentID,
        content,
        this.commentState.comment.userID,
      )
        .then(() => {
          const newComment = {
            userID: this.$store.getters.storeCurrentUserID,
            nickname: this.$store.getters.storeSelfInfo.nickname,
            replyUserID: this.commentState.comment.userID,
            replyNickname: this.commentState.comment.nickname,
            commentID: uuidv4(),
            content,
          };
          this.pushNewComment(newComment);
        })
        .catch((err) => uni.$u.toast("评论失败！"))
        .finally(() => {
          this.commentLoading = false;
          this.commentState.workMomentID = "";
          this.commentState.comment = {};
          this.commenting = false;
        });
    },
    pushNewComment(newComment, workMomentID) {
      const idx = this.momentsList.findIndex(
        (moments) =>
          moments.workMomentID ===
          (workMomentID || this.commentState.workMomentID),
      );
      if (idx > -1) {
        const tmpObj = {
          ...this.momentsList[idx],
        };
        tmpObj.comments = [...tmpObj.comments, newComment];
        this.momentsList[idx] = {
          ...tmpObj,
        };
        console.log(this.momentsList[idx]);
        this.$refs.paging.updateCache();
      }
    },
    onScroll(e) {
      this.needTransparent = e.detail.scrollTop < 200;
    },
    topbarClick() {
      uni.$u.route("/pages/moments/designatedMoments/index", {
        baseUserInfo: JSON.stringify({
          userID: this.$store.getters.storeSelfInfo.userID,
          nickname: this.$store.getters.storeSelfInfo.nickname,
          faceURL: this.$store.getters.storeSelfInfo.faceURL,
        }),
      });
    },
    deleteMomentsHandler(workMomentID) {
      const tmpList = [...this.momentsList];
      const idx = tmpList.findIndex(
        (moments) => moments.workMomentID === workMomentID,
      );
      if (idx > -1) {
        tmpList.splice(idx, 1);
        this.momentsList = [...tmpList];
        this.$refs.paging.updateCache();
      }
    },
    deleteCommentHandler(workMomentID, commentID) {
      const idx = this.momentsList.findIndex(
        (moments) => moments.workMomentID === workMomentID,
      );
      if (idx > -1) {
        const tmpObj = {
          ...this.momentsList[idx],
        };
        const commentIdx = tmpObj.comments.findIndex(
          (comment) => comment.commentID === commentID,
        );
        tmpObj.comments.splice(commentIdx, 1);
        this.momentsList[idx] = {
          ...tmpObj,
        };
        this.$refs.paging.updateCache();
      }
    },
    operateLikeHandler(workMomentID, isLiked) {
      console.log(workMomentID, isLiked);
      const idx = this.momentsList.findIndex(
        (moments) => moments.workMomentID === workMomentID,
      );
      if (idx === -1) return;
      const tmpObj = {
        ...this.momentsList[idx],
      };
      if (isLiked) {
        const likedIdx = tmpObj.likeUsers.findIndex(
          (user) => user.userID === this.$store.getters.storeCurrentUserID,
        );
        if (likedIdx > -1) {
          tmpObj.likeUsers.splice(likedIdx, 1);
        }
      } else {
        tmpObj.likeUsers.push({
          userID: this.$store.getters.storeCurrentUserID,
          nickname: this.$store.getters.storeSelfInfo.nickname,
        });
      }
      this.momentsList[idx] = {
        ...tmpObj,
      };
      console.log(this.momentsList[idx]);
      this.$refs.paging.updateCache();
    },
    refershHandler() {
      this.$refs.paging.reload();
    },
    setPageListener() {
      uni.$on(PageEvents.PushNewComment, this.pushNewComment);
      uni.$on(PageEvents.DeleteComment, this.deleteCommentHandler);
      uni.$on(PageEvents.DeleteMoments, this.deleteMomentsHandler);
      uni.$on(PageEvents.OperateLike, this.operateLikeHandler);
      uni.$on(PageEvents.RefreshMoments, this.refershHandler);
    },
    disposePageListener() {
      uni.$off(PageEvents.PushNewComment, this.pushNewComment);
      uni.$off(PageEvents.DeleteComment, this.deleteCommentHandler);
      uni.$off(PageEvents.DeleteMoments, this.deleteMomentsHandler);
      uni.$off(PageEvents.OperateLike, this.operateLikeHandler);
      uni.$off(PageEvents.RefreshMoments, this.refershHandler);
    },
  },
  onBackPress() {
    if (this.commenting) {
      this.commenting = false;
      return true;
    }
    return false;
  },
};
</script>

<style lang="scss" scoped>
.page_container {
  background-color: #f8f8f8;
  position: relative;
  // height: calc(100vh - 55px);

  .loading_wrap {
    @include centerBox();
    height: 100%;
  }
}

.ios_page {
  .input_bar {
    position: absolute;
    left: 0;
    right: 0;
  }
}
</style>
