<template>
  <div style="height: 100%">
    <div class="sectionSearch">
      <n-input
        class="TheSearch"
        style="--n-font-size: 12px; --n-height: 32px; --n-caret-color: #198cfe; --n-border-hover: 1px solid #198cfe; --n-border-focus: 1px solid #198cfe; --n-loading-color: #198cfe; --n-box-shadow-focus: 0 0 0 2px rgba(25 140 254, 0.2)"
        round
        clearable
        placeholder="请输入名称"
        v-model:value="keyword"
        @clear="
          () => {
            debouncedRequest('');
          }
        "
        @keyup="onKeyup"
      >
        <template #prefix> <span class="icon-search-input"></span></template>
      </n-input>
    </div>
    <div class="TUI-conversation">
      <div class="network" v-if="isNetwork">
        <i class="icon icon-error">!</i>
        <p>️{{ $t("TUIConversation.网络异常，请您检查网络设置") }}</p>
      </div>
      <main class="TUI-conversation-list">
        <TUIConversationList :currentID="currentConversationID" :data="conversationData" @handleItem="handleCurrentConversation" :isH5="env.isH5" :displayOnlineStatus="displayOnlineStatus" :userStatusList="userStatusList" />
      </main>

      <!-- <the-empty v-if="!isNetwork && !loading && conversationData.list.length <= 0" style="height: 90%" /> -->
      <div class="theEmtpy" v-if="!loading && conversationData.list.length <= 0" style="height: 90%">
        <img class="emptyImg" src="../../assets/nomore.png" />
        <p>暂无数据</p>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, computed, watch, onMounted, onBeforeMount } from "vue";
import TUIConversationList from "./components/list";
import { caculateTimeago } from "../utils";
import { useThrottleFn } from "@vueuse/core";
import { handleAvatar, handleName, handleShowLastMessage, handleAt } from "../TUIChat/utils/utils";

const TUIConversation = defineComponent({
  name: "TUIConversation",

  components: {
    TUIConversationList,
    // TheSearch,
    // TheEmpty,
  },
  props: {
    displayOnlineStatus: {
      type: Boolean,
      default: false,
    },
  },
  setup(props: any, ctx: any) {
    const TUIServer: any = TUIConversation?.TUIServer;
    const data = reactive({
      currentConversationID: "",
      keyword: "",
      loading: false,
      conversationData: {
        list: [] as any,
        handleItemAvator: (item: any) => handleAvatar(item),
        handleItemName: (item: any) => handleName(item),
        handleShowAt: (item: any) => handleAt(item),
        handleShowMessage: (item: any) => handleShowLastMessage(item),
        handleItemTime: (time: number) => {
          if (time > 0) {
            return caculateTimeago(time * 1000);
          }
          return "";
        },
      },
      userIDList: [],
      netWork: "",
      env: TUIServer.TUICore.TUIEnv,
      displayOnlineStatus: false,
      userStatusList: new Map(),
    });

    try {
      data.loading = true;
      TUIServer.bind(data, () => {
        setTimeout(() => {
          data.loading = false;
        }, 500);
      });
    } catch {
      data.loading = false;
    }

    TUIConversationList.TUIServer = TUIServer;

    const onUpdateCount = (val: any) => {
      if (window.parent) {
        window.parent?.postMessage({
          api: "getNoReadMessageCount",
          count: val,
        });
      }
    };

    onMounted(() => {
      window.addEventListener("message", (params?: any) => {
        console.log(params, "message");
        if (!params.data?.imUserId) return;

        TUIServer.getConversationProfile(`C2C${params?.data.imUserId}`)
          .then((imResponse: any) => {
            // 通知 TUIConversation 添加当前会话
            TUIServer.handleCurrentConversation(imResponse.data.conversation);
          })
          .catch((error: any) => {
            console.log(error, "error");
          });
      });
      TUIServer.TUICore.tim.on(TUIServer.TUICore.TIM.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, onUpdateCount);
    });
    onBeforeMount(() => {
      TUIServer.TUICore.tim.off(TUIServer.TUICore.TIM.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, onUpdateCount);
    });
    watch(
      () => data.currentConversationID,
      (newVal: any) => {
        ctx.emit("current", newVal);
      },
      {
        deep: true,
      }
    );

    const isNetwork = computed(() => {
      const disconnected = data.netWork === TUIServer.TUICore.TIM.TYPES.NET_STATE_DISCONNECTED;
      const connecting = data.netWork === TUIServer.TUICore.TIM.TYPES.NET_STATE_CONNECTING;
      return disconnected || connecting;
    });

    const handleCurrentConversation = (value: any) => {
      TUIServer.handleCurrentConversation(value);
    };

    //
    const noSearch = async (val: string) => {
      data.loading = true;
      try {
        data.conversationData.list = [];
        await TUIServer.getConversationListForName(val);
      } catch {
        //
      }
      data.loading = false;
    };

    const debouncedRequest = useThrottleFn((val: string) => {
      if (props.loading) return;
      noSearch(val);
    }, 500);

    const onKeyup = (e: any) => {
      e.stopPropagation();
      if (e.code === "Enter") {
        debouncedRequest(data.keyword);
      }
    };

    return {
      ...toRefs(data),
      handleCurrentConversation,
      isNetwork,
      noSearch,
      onKeyup,
      debouncedRequest,
    };
  },
});
export default TUIConversation;
</script>

<style scoped lang="scss" src="./style/index.scss"></style>
