<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-group">
      <main class="TUI-conversation-list">
        <aside class="TUI-contact-left">
          <ul class="TUI-contact-list">
            <li class="TUI-contact-list-item" v-for="(item, index) in groupList" :key="index" @click="handleListItem(item)">
              <aside class="left">
                <img class="avatar" :src="item.img || 'https://oss.dayaedu.com/news-info/07/1690775328089.png'" onerror="this.src='https://oss.dayaedu.com/news-info/07/1690775328089.png'" />
              </aside>
              <div class="content-header">
                <label>
                  <p class="name">{{ item.name }}</p>
                </label>
                <div class="middle-box">
                  <p>共{{ item.memberNum || 0 }}人</p>
                </div>
              </div>
              <div class="content-footer">
                <span class="time"></span>
                <img v-if="item.selfInfo?.messageRemindType === 'AcceptNotNotify'" class="mute-icon" src="../../assets/icon/mute.svg" />
                <i></i>
              </div>
            </li>
          </ul>
        </aside>
      </main>
      <div class="theEmtpy" v-if="!loading && groupList.length <= 0" style="height: 90%">
        <img class="emptyImg" src="../../assets/nomore.png" />
        <p>暂无数据</p>
      </div>
      <DialogTUI :show="dialogShow" :isHeaderShow="true" title="提示" :is-footer-show="true" @submit="handleManage()" @update:show="(e) => (dialogShow = e)">
        <p>该群已解散，是否删除？</p>
      </DialogTUI>
    </div>
  </div>
</template>
<script lang="ts">
import { computed, defineComponent, onMounted, onUnmounted, reactive, toRefs } from "vue";
import { caculateTimeago } from "../utils";
import { handleAvatar, handleName, handleAt } from "../TUIChat/utils/utils";
import { imGroupPage, imGroupDetail } from "../../../api";
import { useThrottleFn } from "@vueuse/core";
import DialogTUI from "../../components/dialogTUi/index.vue";
import { eventGlobal } from "@/helpers";
const TUIGroup = defineComponent({
  name: "TUIGroup",
  components: { DialogTUI },
  props: {
    displayOnlineStatus: {
      type: Boolean,
      default: false,
    },
  },
  setup(props) {
    const TUIServer: any = TUIGroup.TUIServer;
    const data = reactive({
      loading: true,
      page: 1,
      rows: 100,
      keyword: "",
      finshed: false, // 是否加载完
      groupList: [] as any,
      searchGroup: [] as any,
      searchID: "",
      currentGroup: null,
      netWork: "",
      userStatusList: new Map(),
      dialogShow: false,
      dialogItem: {} as any,
    });

    const handleItemTime = (time: number) => {
      if (time > 0) {
        return caculateTimeago(time * 1000);
      }
      return "";
    };

    const handleListItem = async (item: any) => {
      try {
        // 判断群是否存在
        console.log(item, "item");
        // const res = await imGroupDetail({ id: item.id });
        // 判断是否有群
        if (item.id) {
          const name = `GROUP${item.id}`;
          TUIServer.TUICore.TUIServer.TUIConversation.getConversationProfile(name).then((imResponse: any) => {
            console.log(imResponse, "item");
            // 通知 TUIConversation 添加当前会话
            TUIServer.TUICore.TUIServer.TUIConversation.handleCurrentConversation(imResponse.data.conversation);

            (data.currentGroup as any) = {};
          });
        } else {
          data.dialogShow = true;
          data.dialogItem = item;
        }
      } catch (e) {
        //
      }
    };
    const handleManage = () => {
      const index = data.groupList.findIndex((item: any) => item.groupId == data.dialogItem.groupId);
      data.groupList.splice(index, 1);
    };
    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;
      return true;
    });

    // 获取列表
    const getList = async () => {
      data.loading = true;
      try {
        const res = await imGroupPage({
          search: data.keyword,
          page: data.page,
          rows: data.rows,
        });

        data.groupList.push(...(res.data || []));

        // 是否加载完成
        data.finshed = true; //res.data.pages <= res.data.current ? true : false;
      } catch {
        //
      }
      data.loading = false;
    };

    /** 删除移除的组和退出的群 */
    const onRemoveGroup = (groupId: any) => {
      const index = data.groupList.findIndex((group: any) => group.groupId == groupId);

      data.groupList.splice(index, 1);
    };

    onMounted(() => {
      getList();

      eventGlobal.on("removeGroup", (groupId: any) => {
        onRemoveGroup(groupId);
      });
    });

    onUnmounted(() => {
      eventGlobal.off("removeGroup", onRemoveGroup);
    });

    const noSearch = (val: string) => {
      console.log(val, "val");
      data.page = 1;
      data.keyword = val;
      data.groupList = [];
      getList();
    };

    const debouncedRequest = useThrottleFn((val: string) => {
      noSearch(val);
    }, 500);

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

    return {
      ...toRefs(data),
      handleListItem,
      handleManage,
      isNetwork,
      handleAvatar,
      handleName,
      handleAt,
      handleItemTime,
      noSearch,
      onKeyup,
      debouncedRequest,
    };
  },
});
export default TUIGroup;
</script>

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