<template>
  <view class="moments_item">
    <my-avatar
      size="48"
      :src="moments.faceURL"
      :desc="moments.nickname"
      @click="toPublisher"
    />
    <view class="main_content">
      <view class="pusher">
        {{ moments.nickname }}
      </view>

      <view class="moments_text" @click="toDetails">
        {{ moments.content.text }}
      </view>

      <!-- 	<view class="moments_media" :class="{'grid_media':moments.content.metas.length>1}"
				:style="{'grid-template-rows':getGridRows}">
				<media-item v-for="item in moments.content.metas" :key="item.original" :item="item" />
			</view> -->
      <u-album
        v-if="moments.content.metas.length > 0"
        multipleSize="70"
        keyName="thumb"
        previewKeyName="original"
        :isVideo="moments.content.type === 1"
        :previewFullImage="moments.content.type === 0"
        :urls="moments.content.metas || []"
        @clickItem="clickMediaItem"
      ></u-album>

      <view class="at_list" v-if="moments.atUsers.length > 0">
        <text>{{ atStr }}</text>
      </view>

      <view class="time_line">
        <text>{{ publishTimeStr }}</text>
        <image
          v-if="moments.permission === 1"
          class="lock_icon"
          src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/moments_lock.png"
        />
        <image
          v-if="moments.permission === 2 || moments.permission === 3"
          class="limit_icon"
          src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/moments_limit.png"
        />
        <text
          v-if="moments.userID === $store.getters.storeCurrentUserID"
          @click="delteMoments"
          >删除</text
        >
        <image
          class="action_icon"
          src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/moments_more.png"
          @click.stop="showAction"
        />
        <u-overlay
          :show="moreMenuVisible"
          @click="moreMenuVisible = false"
          opacity="0"
        >
          <view
            :style="{ top: popMenuPosition.top, right: popMenuPosition.right }"
            class="more_menu">
            <view class="menu_item" @click="likeOrNot">
              <image :src="likeIcon" mode="" />
              <view>赞</view>
            </view>
            <view
              class="menu_item"
              @click="$emit('startComent', moments.workMomentID)"
            >
              <image src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/moments_coment.png" mode="" />
              <view>评论</view>
            </view>
          </view>
        </u-overlay>
      </view>

      <view class="like_list" v-if="likeStr">
        <image :src="moments_liked" />
        <text>{{ likeStr }}</text>
      </view>

      <view class="coment_list">
        <coment-item
          v-for="comment in moments.comments"
          :key="comment.commentID"
          :momentsUserID="moments.userID"
          :comment="comment"
          @startComent="$emit('startComent', moments.workMomentID, comment)"
          @deleteComent="deleteComent"
        />
      </view>
    </view>
  </view>
</template>

<script>
import IMSDK from "openim-uniapp-polyfill";
import MyAvatar from "../../../../components/MyAvatar/index.vue";
import MediaItem from "./MediaItem.vue";
import ComentItem from "./ComentItem.vue";
import { formatConversionTime } from "../../../../util/imCommon";
import { deleteComment, deleteMoments, likeMoments } from "../../../../api/moments";
import { PageEvents } from "../../../../constant";
import { toastWithCallback } from "../../../../util/common";

const moments_like = "https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/moments_like.png";
const moments_liked = "https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/moments_liked.png";
export default {
  components: {
    MyAvatar,
    MediaItem,
    ComentItem,
  },
  props: {
    moments: Object,
    showDetails: Boolean,
    inSingle: Boolean,
  },
  data() {
    return {
      moreMenuVisible: false,
      popMenuPosition: {
        top: 0,
        right: 0,
      },
      moments_liked,
    };
  },
  computed: {
    publishTimeStr() {
      return formatConversionTime(this.moments.createTime);
    },
    getGridRows() {
      if (this.moments.content.metas.length < 3) {
        return "100px";
      }
      if (this.moments.content.metas.length < 6) {
        return "100px 100px";
      }
      return "100px 100px 100px";
    },
    likeStr() {
      let str = "";
      const likeNum = this.moments.likeUsers.length;
      const tmpList = this.showDetails
        ? this.moments.likeUsers
        : this.moments.likeUsers.slice(0, 5);
      tmpList.map((user) => (str += `${user.nickname}、`));
      return (
        str.slice(0, str.length - 1) +
        (likeNum > 5 && this.showDetails ? `等${likeNum}人点赞` : "")
      );
    },
    atStr() {
      let str = "提到了：";
      const atNum = this.moments.atUsers.length;
      const tmpList = this.showDetails
        ? this.moments.atUsers
        : this.moments.atUsers.slice(0, 5);
      tmpList.map((user) => (str += `${user.nickname}、`));
      return (
        str.slice(0, str.length - 1) +
        (atNum > 5 && this.showDetails ? `等${atNum}人` : "")
      );
    },
    isLiked() {
      return (
        this.moments.likeUsers.findIndex(
          (user) => user.userID === this.$store.getters.storeCurrentUserID,
        ) > -1
      );
    },
    likeIcon() {
      return this.isLiked ? moments_liked : moments_like;
    },
  },
  methods: {
    async showAction() {
      const { left, top } = await this.getEl(".action_icon");
      this.popMenuPosition.right = `${
        uni.getWindowInfo().windowWidth - left + 12
      }px`;
      this.popMenuPosition.top = `${top}px`;
      this.moreMenuVisible = true;
    },
    getEl(el) {
      return new Promise((resolve) => {
        const query = uni.createSelectorQuery().in(this);
        query
          .select(el)
          .boundingClientRect((data) => {
            resolve(data);
          })
          .exec();
      });
    },
    likeOrNot() {
      likeMoments(this.moments.workMomentID, !this.isLiked)
        .then((res) => {
          if (this.isLiked) {
            const tmpArr = [...this.moments.likeUsers];
            const idx = tmpArr.findIndex(
              (user) =>
                user.userID === this.$store.getters.storeSelfInfo.userID,
            );
            if (idx > -1) {
              tmpArr.splice(idx, 1);
            }
            this.moments.likeUsers = [...tmpArr];
          } else {
            this.moments.likeUsers = [
              ...this.moments.likeUsers,
              {
                userID: this.$store.getters.storeSelfInfo.userID,
                nickname: this.$store.getters.storeSelfInfo.nickname,
              },
            ];
          }
          if (this.showDetails || this.inSingle) {
            uni.$emit(
              PageEvents.OperateLike,
              this.moments.workMomentID,
              !this.isLiked,
              this.showDetails,
            );
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    toDetails() {
      if (!this.showDetails) {
        uni.$u.route("/pages_im/pages/moments/momentsDetails/index", {
          workMomentID: this.moments.workMomentID,
        });
      }
    },
    clickMediaItem(item) {
      uni.$u.route("/pages_im/pages/conversation/previewVideo/index", {
        previewVideoUrl: item.original,
      });
    },
    delteMoments() {
      uni.showModal({
        title: "提示",
        content: "确定要删除此条内容吗？",
        showCancel: true,
        confirmText: "确认",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            deleteMoments(this.moments.workMomentID)
              .then(() => {
                uni.$emit(
                  PageEvents.DeleteMoments,
                  this.moments.workMomentID,
                  this.showDetails,
                );
                toastWithCallback("删除成功！", uni.navigateBack);
              })
              .catch((err) => {
                uni.$u.toast("删除失败！");
                console.log(err);
              });
          }
        },
      });
    },
    deleteComent(commentID) {
      uni.showModal({
        title: "提示",
        content: "确定要删除此条评论吗？",
        showCancel: true,
        confirmText: "确认",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            deleteComment(this.moments.workMomentID, commentID)
              .then(() => {
                const tmpArr = [...this.moments.comments];
                const idx = tmpArr.findIndex(
                  (comment) => comment.commentID === commentID,
                );
                if (idx > -1) {
                  tmpArr.splice(idx, 1);
                }
                this.moments.comments = [...tmpArr];
                if (this.showDetails || this.inSingle) {
                  uni.$emit(
                    PageEvents.DeleteComment,
                    this.moments.workMomentID,
                    commentID,
                    this.showDetails,
                  );
                }
              })
              .catch((err) => uni.$u.toast("删除失败！"));
          }
        },
      });
    },
    toPublisher() {
      if (!this.inSingle) {
        uni.$u.route("/pages_im/pages/common/userCard/index", {
          sourceID: this.moments.userID,
        });
        // uni.$u.route("/pages/moments/designatedMoments/index", {
        //   baseUserInfo: JSON.stringify({
        //     userID: this.moments.userID,
        //     nickname: this.moments.nickname,
        //     faceURL: this.moments.faceURL,
        //   }),
        // });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.moments_item {
  display: flex;
  padding: 32rpx;
  background-color: #fff;
  border-bottom: 1px solid rgba(126, 134, 142, 0.16);

  .main_content {
    width: 100%;
    margin-left: 24rpx;

    .pusher {
      @include nomalEllipsis;
      max-width: 360rpx;
      font-size: 32rpx;
      font-weight: 500;
      color: #6085b1;
      margin-bottom: 8rpx;
    }

    .moments_text {
      @include ellipsisWithLine(5);
      color: #333;
      margin-bottom: 12rpx;
    }

    .moments_media {
      margin: 24rpx 0;
    }

    .grid_media {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      grid-gap: 10px;
    }

    .u-album {
      margin-bottom: 12rpx;

      /deep/.u-album__row__wrapper {
        border-radius: 8rpx;
        overflow: hidden;
      }
    }

    .time_line {
      position: relative;
      font-size: 24rpx;
      color: #a2a3a5;
      margin-bottom: 12rpx;

      text:nth-child(2) {
        color: #5a7b98;
        margin-left: 24rpx;
      }

      .limit_icon {
        width: 15px;
        height: 10px;
        padding: 0 12rpx;
      }

      .lock_icon {
        width: 9px;
        height: 11px;
        padding: 0 12rpx;
      }

      .action_icon {
        width: 18px;
        height: 12px;
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .at_list {
      font-size: 24rpx;
      color: #a2a3a4;
      margin-bottom: 12rpx;
    }

    .like_list {
      font-size: 24rpx;
      color: #5a7b98;
      margin-bottom: 12rpx;

      image {
        width: 12px;
        height: 12px;
        margin-right: 12rpx;
      }
    }
  }

  &:nth-child(2) {
    padding-top: 64rpx;
  }
  &:last-child {
    border: none;
  }
}

.more_menu {
  display: flex;
  position: absolute;
  z-index: 999;
  transform: translateY(-25%);
  width: max-content;
  border-radius: 6rpx;
  background-color: #5d5e61;
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.3);
  padding: 12rpx;

  .menu_item {
    display: flex;
    align-items: center;
    color: #fff;
    padding: 0 24rpx;

    image {
      width: 12px;
      height: 12px;
      margin-right: 12rpx;
    }

    &:first-child {
      border-right: 1px solid #575151;
    }
  }
}
</style>
