<template>
  <view>
    <text v-if="isNeedShowMessageTime" class="message_time">{{
      messageTime(msgBody.time)
    }}</text>
    <view
      :class="[
        'message_list_item',
        !isSelf(msgBody) || 'message_list_item_mine',
        msgBody.id == quoteMsgId && 'quote_msg_avtive',
      ]"
    >
      <!--user avatar -->
      <view class="message_list_item_avatar">
        <u-avatar
          :src="messageItemAvatar"
          shape="square"
          :size="28"
          @click="entryContactsDetailPage"
        />
      </view>
      <view class="message_list_item_content" @longpress="callMessagePopup">
        <text
          :class="[
            'message_list_item_content_nickname',
            isSelf(msgBody) && 'message_list_item_content_nickname_mine',
          ]"
          >{{ messageItemNickName }}</text
        >

        <!-- 文本消息 -->
        <template v-if="msgBody.type === MESSAGE_TYPE.TEXT">
          <text-msg-item :msgBody="msgBody" />
        </template>
        <!-- 图片消息 -->
        <template v-if="msgBody.type === MESSAGE_TYPE.IMAGE">
          <image-msg-item :msgBody="msgBody" />
        </template>
        <!-- 语音消息 -->
        <template v-if="msgBody.type === MESSAGE_TYPE.AUDIO">
          <audio-msg-item
            :msgBody="msgBody"
            :playAudioMid="playAudioMid"
            @onClickPlayAudio="onClickPlayAudio"
          />
        </template>
        <!-- 附件消息 -->

        <template v-if="msgBody.type === MESSAGE_TYPE.FILE">
          <file-msg-item :msgBody="msgBody" />
        </template>

        <!-- 个人名片 -->
        <template
          v-if="
            msgBody.type === MESSAGE_TYPE.CUSTOM &&
            msgBody.customEvent === CUSTOM_EVENT_NAME.USER_CARD
          "
        >
          <user-card-msg-item
            @click.native="entryContactsDetailPage(CUSTOM_EVENT_NAME.USER_CARD)"
            :msgBody="msgBody"
          />
        </template>
		
		<!-- 商品链接 -->
		<template
		  v-if="
		    msgBody.type === MESSAGE_TYPE.CUSTOM &&
		    msgBody.customEvent === CUSTOM_EVENT_NAME.PRODUCTLINK
		  "
		>
		  <product-card-item
			 @click.native="entryProductDetailPage(CUSTOM_EVENT_NAME.PRODUCTLINK)"
		    :msgBody="msgBody"
		  />
		  
		</template>
		
		
        <msg-quote-container
          v-if="msgBody.ext && msgBody.ext.msgQuote"
          :msgQuoteContent="msgBody.ext.msgQuote"
          @click.native="callScrollToQuoteMsg(msgBody.ext.msgQuote)"
        />
      </view>
    </view>
  </view>
</template>

<script>
import { MESSAGE_TYPE, CUSTOM_EVENT_NAME, CHAT_TYPE } from "@/EaseIM/constant";
import TextMsgItem from "./messagesItem/textMsgItem";
import ImageMsgItem from "./messagesItem/imageMsgItem";
import AudioMsgItem from "./messagesItem/audioMsgItem";
import FileMsgItem from "./messagesItem/fileMsgItem";
import UserCardMsgItem from "./messagesItem/userCardItem";
import ProductCardItem from "./messagesItem/productCardItem";
import MsgQuoteContainer from "./msgQuoteContainer";
import { EMClient } from "@/EaseIM";
export default {
  components: {
    TextMsgItem,
    ImageMsgItem,
    AudioMsgItem,
    FileMsgItem,
    UserCardMsgItem,
	ProductCardItem,
    MsgQuoteContainer,
  },
  props: {
    msgBody: {
      type: Object,
      default: () => ({}),
      required: true,
    },
    isNeedShowMessageTime: {
      type: Boolean,
      default: false,
    },
    quoteMsgId: {
      type: String,
      default: "",
    },
  },

  data() {
    return {
      MESSAGE_TYPE,
      CUSTOM_EVENT_NAME,
      playAudioMid: "",
	
      // defaultAvatar: "/static/images/new_ui/defaultAvatar.png",
	  defaultAvatar:uni.getStorageSync('nowConversationIntem').avatarurl,
      defaultAvatarMe: uni.getStorageSync('selectmerchant').merchantIntention.logo,
      defaultNicknameMe: uni.getStorageSync('selectmerchant').merchantIntention.mer_name,
    };
  },
  computed: {
    isSelf() {
      return (item) => {
        return (
          item.from ===
          this.$store.state.LoginStore.loginUserBaseInfos.loginUserId
        );
      };
    },
    loginUserProfiles() {
      return this.$store.state.LoginStore.loginUserProfiles;
    },
    messageTime() {
      return (time) => {
        return this.$u.timeFrom(time);
      };
    },

    friendUserInfoCollection() {
      return this.$store.getters.friendUserInfoCollection;
    },
    groupMembersProfileData() {
      return this.$store.getters.groupMembersProfile;
    },
    messageItemAvatar() {
      if (this.isSelf(this.msgBody)) {
        return this.loginUserProfiles?.avatarurl || this.defaultAvatarMe;
      }
      if (this.msgBody.chatType === CHAT_TYPE.SINGLE_CHAT) {
        const userId = this.msgBody.from;
        if (
          this.friendUserInfoCollection[userId] &&
          this.friendUserInfoCollection[userId]?.avatarurl
        ) {
          return (
            this.friendUserInfoCollection[userId].avatarurl ||
            this.defaultAvatar
          );
        } else {
          return this.defaultAvatar;
        }
      }
      if (this.msgBody.chatType === CHAT_TYPE.GROUP_CHAT) {
        const groupId = this.msgBody.to;
        const userId = this.msgBody.from;
        const groupMemberData = this.groupMembersProfileData[groupId];
        if (groupMemberData) {
          return groupMemberData[userId]?.avatarurl || this.defaultAvatar;
        } else {
          return this.defaultAvatar;
        }
      }
    },
    messageItemNickName() {
      if (this.isSelf(this.msgBody)) {
		// console.log('this.loginUserProfiles>>>>>>>>>>>>',this.loginUserProfiles)
		// console.log('EMClient.user>>>>>>>>>>>>',EMClient.user)
        return this.loginUserProfiles?.nickname || this.defaultNicknameMe;
      }
      if (this.msgBody.chatType === CHAT_TYPE.SINGLE_CHAT) {
        // const userId = this.msgBody.from;
		const userId=uni.getStorageSync('nowConversationIntem').nickname
		
        if (
          this.friendUserInfoCollection[userId] &&
          this.friendUserInfoCollection[userId]?.nickname
        ) {
          // return this.friendUserInfoCollection[userId].nickname;
          return uni.getStorageSync('nowConversationIntem').nickname;
        } else {
          return userId;
        }
      }
      if (this.msgBody.chatType === CHAT_TYPE.GROUP_CHAT) {
        const groupId = this.msgBody.to;
        const userId = this.msgBody.from;
        const groupMemberData = this.groupMembersProfileData[groupId];
        if (groupMemberData) {
          return (
            groupMemberData[userId]?.nickName ||
            groupMemberData[userId]?.nickname ||
            userId
          );
        } else {
          return userId;
        }
      }
    },
  },
  methods: {
    onClickPlayAudio(mid) {
      this.playAudioMid = mid;
      console.log("mid", mid);
      console.log("++++++++");
    },
    callMessagePopup() {
      this.$emit("alertMessagePopup", this.msgBody);
    },
    callScrollToQuoteMsg(msgQuote) {
      this.$emit("scrollToQuoteMessge", msgQuote);
    },
    //前往联系人详情页面
    entryContactsDetailPage(type) {
      if (type === CUSTOM_EVENT_NAME.USER_CARD) {
        const {
          customExts: { uid: userId },
        } = this.msgBody;
        uni.navigateTo({
          url: `../contactsDetail/index?userId=${userId}`,
        });
      } else {
        if (this.msgBody.from === EMClient.user) return;
        const userId = this.msgBody.from;
        uni.navigateTo({
          url: `../contactsDetail/index?userId=${userId}`,
        });
      }
    },
	//跳转商品详情
	entryProductDetailPage(){
		const {
		  customExts: { uid: uid,productId:productId },
		} = this.msgBody;
		uni.navigateToMiniProgram({
			      appId: 'wx9082e5ac2fdb513f',
			      path: `pages/store/product/detail?id=${productId}`,
			  	  envVersion: 'trial', // develop（开发版），trial（体验版），release（正式版）
			      success(res) {
			        // 打开成功
			        console.log(res);
			      },
			      fail: (error) => {
			        console.log(error);
			      }
		})
	}
  },
};
</script>

<style scoped>
@import "./index.css";
</style>
