<template>
  <ele-modal
    width="75%"
    :visible="visible"
    :maskClosable="false"
    :maxable="true"
    :title="`${data?.userInfo?.nickname}(当前用户) 与 ${data?.friendInfo?.nickname} 的聊天记录`"
    :body-style="{ paddingBottom: '28px' }"
    :footer="false"
    @update:visible="updateVisible"
    @ok="save"
  >
    <div style="height: 700px; overflow-y: auto; overflow-x: hidden">
      <a-list
        class="demo-loadmore-list"
        item-layout="horizontal"
        :data-source="list"
        :loading="loading"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <a-skeleton avatar :title="false" :loading="!!item.loading" active>
              <a-list-item-meta>
                <template #avatar>
                  <a-avatar :src="item.formUserInfo?.avatar" />
                </template>
                <template #title>
                  {{ item.formUserInfo.nickname }}
                  <span style="color: #666666">
                    ID: {{ item.formUserInfo.userId }}</span
                  >
                </template>
                <template #description>
                  <template v-if="item.type === 'text'"
                    >{{ item.content }}
                  </template>
                  <template v-else-if="item.type === 'image'">
                    <img
                      style="width: 200px; height: 200px; object-fit: contain"
                      :src="item.content"
                    />
                  </template>
                  <template v-else-if="item.type === 'card'">
                    <ChatCard :content="item.content" />
                  </template>
                </template>
              </a-list-item-meta>
            </a-skeleton>
          </a-list-item>
        </template>
      </a-list>
    </div>

    <ChatInputBar @send="sendMessag" />
  </ele-modal>
</template>
<script lang="ts" setup>
  import { onUnmounted, ref, watch } from 'vue';
  import { ChatConversation, ChatMessage } from '@/api/love/chat/model';
  import { addChatMessage, pageChatMessage } from '@/api/love/chat';
  import ChatCard from '@/views/love/chat/components/chat-card.vue';
  import ChatInputBar from '@/views/love/chat/components/chat-input-bar.vue';
  import { emitter } from '@/utils/common';
  import { useChatStore } from '@/store/modules/chat';
  const chatStore = useChatStore();
  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data: ChatConversation;
  }>();
  const loading = ref<boolean>(false);
  const list = ref<ChatMessage[]>([]);
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();
  // const loading = ref(false);

  const save = () => {
    updateVisible(false);
    emit('done');
  };
  /**
   * 加载消息
   */
  const loadMessage = () => {
    loading.value = true;
    pageChatMessage({
      formUserId: props.data.userId,
      toUserId: props.data.friendId,
      keywords: '',
      limit: 50,
      page: 1
    })
      .then((res) => {
        if (res?.list) {
          list.value = res.list;
          if (res.list.length == 0) {
            console.log(JSON.parse(JSON.stringify(props.data.userInfo)));
            let images: any[] = [];
            if (props.data.userInfo?.userProfile?.images) {
              images = JSON.parse(props.data.userInfo?.userProfile?.images);
            }

            if (images.length > 3) {
              images.splice(3, images.length - 3);
            }
            const content: string = JSON.stringify({
              age: props.data.userInfo?.userProfile?.age,
              city: props.data.userInfo?.userProfile?.city,
              height: props.data.userInfo?.userProfile?.height,
              yearlyPay: props.data.userInfo?.userProfile?.yearlyPay,
              position: props.data.userInfo?.userProfile?.position,
              files: images.map((d) => {
                return {
                  thumb: d.url,
                  url: d.url
                };
              })
            });
            sendMessag({
              content: content,
              type: 'card'
            });
          }
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  emitter.on('message', (message) => {
    console.log('message', message, props.data);

    if (
      props.data &&
      message.toUserId === props.data.userId &&
      message.formUserId === props.data.friendId
    ) {
      list.value.push(message);
    }
  });
  /**
   * 发送消息
   */
  const sendMessag = ({ content, type }) => {
    addChatMessage({
      content,
      type,
      formUserId: props.data.userId,
      toUserId: props.data.friendId
    }).then((res) => {
      if (res.code == 0) {
        list.value.push({
          content,
          type,
          formUserId: props.data.userId,
          toUserId: props.data.friendId,
          formUserInfo: props.data.userInfo
        });
      }
    });
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        list.value = [];
        if (props.data?.id) {
          chatStore.readConversation(props.data.id);
        }
        loadMessage();
      }
    }
  );

  onUnmounted(() => {
    emitter.off('message');
  });
</script>
