<template>
  <view class="page_container">
    <z-paging
      ref="paging"
      :fixed="false"
      default-page-size="20"
      loading-full-fixed
      refresher-background="#05263c"
      v-model="momentsList"
      :show-loading-more-no-more-view="false"
      @query="queryList"
      @scroll="onScroll"
    >
      <moments-header
        :needTransparent="needTransparent"
        :baseUserInfo="baseUserInfo"
        showBack
      />
      <!-- <moments-item v-for="item in momentsList" :key="item.workMomentID" :moments="item" inSingle @startComent="startComent" /> -->
      <view v-for="group in groups">
        <view class="moments" v-for="(item, i) in group.objects">
          <view class="moments_day">
            <text v-if="i === 0">{{ group.date }}</text>
          </view>
          <view
            class="moments_content"
            v-if="item.content.metas.length > 0"
            @click="toDetails(item.workMomentID)"
          >
            <image :src="item.content.metas[0].thumb"></image>
            <view class="moments_content_text">
              <text class="main-text">{{ item.content.text }}</text>
              <text class="tip-text">共{{ item.content.metas.length }}张</text>
            </view>
          </view>
          <view
            class="moments_content"
            @click="toDetails(item.workMomentID)"
            v-else
          >
            <view class="moments_only_text">
              <text class="only-text">{{ item.content.text }}</text>
            </view>
          </view>
        </view>
      </view>
      <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 dayjs from "dayjs";
import CustomNavBar from "../../../components/CustomNavBar/index.vue";
import { commentMoments, getUserMomentsSplit } from "../../../api/moments";
import MomentsHeader from "../index/components/MomentsHeader.vue";
import MomentsItem from "../index/components/MomentsItem.vue";
import CommentInput from "../index/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,
      baseUserInfo: {},
    };
  },
  computed: {
    placeholder() {
      if (this.commentState.comment.userID) {
        return `回复${this.commentState.comment.nickname}`;
      }
      return "评论";
    },
    groups() {
      const groupsMap = new Map();
      const currentDate = dayjs().format("YYYY-MM-DD");
      this.momentsList.forEach((obj) => {
        const objDate = dayjs.unix(obj.createTime / 1000);

        if (objDate.format("YYYY-MM-DD") === currentDate) {
          const todayKey = "今日";
          if (!groupsMap.has(todayKey)) {
            groupsMap.set(todayKey, []);
          }
          groupsMap.get(todayKey).push(obj);
        } else if (objDate.add(1, "day").format("YYYY-MM-DD") === currentDate) {
          const yesterdayKey = "昨日";
          if (!groupsMap.has(yesterdayKey)) {
            groupsMap.set(yesterdayKey, []);
          }
          groupsMap.get(yesterdayKey).push(obj);
        } else {
          const otherKey = objDate.format("MM-DD");
          if (!groupsMap.has(otherKey)) {
            groupsMap.set(otherKey, []);
          }
          groupsMap.get(otherKey).push(obj);
        }
      });
      return Array.from(groupsMap, ([date, objects]) => ({
        date,
        objects,
      }));
    },
  },
  onLoad(options) {
    this.baseUserInfo = JSON.parse(options.baseUserInfo);
    this.setPageListener();
    uni.addInterceptor("navigateTo", {
      success: () => {
        if (this.commenting) {
          this.commentState.workMomentID = "";
          this.commentState.comment = {};
          this.commenting = false;
        }
      },
    });
    this.$nextTick(() => this.$refs.commentInputRef.setKeyboardListener());
  },
  onUnload() {
    this.$refs.commentInputRef.disposeKeyboardListener();
  },
  methods: {
    toDetails(workMomentID) {
      uni.$u.route("/pages/moments/momentsDetails/index", {
        workMomentID,
      });
    },
    queryList(pageNo, pageSize) {
      console.log(pageNo, pageSize);
      getUserMomentsSplit(this.baseUserInfo.userID, pageNo)
        .then((res) => {
          console.log("getUserMomentsSplit", 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)
          uni.$emit(
            PageEvents.PushNewComment,
            newComment,
            this.commentState.workMomentID,
          );
        })
        .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;
    },
    deleteMomentsHandler(workMomentID, isDetails) {
      if (!isDetails) {
        return;
      }
      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, isDetails) {
      if (!isDetails) {
        return;
      }
      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, isDetails) {
      if (!isDetails) {
        return;
      }
      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,
      };
      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);

  .moments {
    @include centerBox();
    align-items: flex-start;
    margin-bottom: 24rpx;

    &_day {
      @include centerBox();
      justify-content: center;
      font-weight: 600;
      font-size: 30rpx;
      flex-shrink: 0;
      width: 140rpx;
    }

    &_content {
      @include btwBox();
      flex: 1;
      flex-direction: row;

      .moments_only_text {
        width: 100%;
        background: #e8eaef;
        padding: 24rpx;
        margin-right: 24rpx;

        .only-text {
          @include ellipsisWithLine(2);
        }
      }

      image {
        flex-shrink: 0;
        width: 160rpx;
        height: 160rpx;
      }

      &_text {
        height: 160rpx;
        display: flex;
        flex: 1;
        flex-direction: column;
        justify-content: space-between;
        align-items: flex-start;
        margin: 0 24rpx;

        .main-text {
          @include ellipsisWithLine(3);
        }

        .tip-text {
          color: #8e9ab0;
          font-size: 26rpx;
        }
      }
    }
  }

  .loading_wrap {
    @include centerBox();
    height: 100%;
  }
}
</style>
