<template>
  <List @load="onLoad" v-model:loading="loading" :finished="finished">
    <AddressBookItem
      v-for="target in list"
      :key="target.address"
      :display-name="target.displayName"
      :is-user="isUser"
      @chat="
        $router.push({
          name: 'Chat',
          query: {
            targetId: target.address,
          },
        })
      "
    ></AddressBookItem>
  </List>
  <div v-if="state.isEmpty" class="text-center text-sm mt-20 text-app-txt">
    无联系人
  </div>
</template>
<script setup lang="ts">
import { staffGetUsers } from "@/service/StaffService";
import UserService from "@/service/UserService";
import { eRole } from "@/types/roleType";
import { getUserMsg } from "@/utils/userMsg";
import { computed, reactive, ref } from "@vue/reactivity";
import { List } from "vant";
import { iContactPerson } from "@/types/chat/index";
import { getDisplayNamesFromAddress } from "@/utils/displayName";
import AddressBookItem from "./AddressBookItem.vue";

const list = ref<(iContactPerson & { displayName: string })[]>([]);
const loading = ref(false);
const finished = ref(false);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

const state = reactive({
  isEmpty: false,
});

const isUser = computed(() => {
  return getUserMsg()?.role2 === eRole.user;
});

async function staffLoadCustoms() {
  const ret = await staffGetUsers({
    is_desc: true,
    order_by: "phone",
    page: page.value,
    page_size: pageSize.value,
  });
  if (ret.code === 200) {
    const displayNames = ret.data.item.map((i) => i.phone);
    list.value.push(
      ...ret.data.item.map((item, index) => {
        return {
          ...item,
          displayName: displayNames[index],
        };
      })
    );
    total.value = ret.data.total;
    page.value++;
    if (list.value.length === total.value) {
      finished.value = true;
    }
  } else {
    finished.value = true;
  }
}

async function userLoadAccountManager() {
  const ret = await UserService.getInstance().userGetAccountManager();
  if (ret.code === 200) {
    if (!ret.data) {
      finished.value = true;
      return;
    }
    const displayNames = await getDisplayNamesFromAddress([ret.data.address]);
    list.value.push({ ...ret.data, displayName: displayNames[0] });
    finished.value = true;
  }
}

async function onLoad() {
  const userMsg = getUserMsg();

  if (userMsg?.role2 === eRole.manager || userMsg?.role2 === eRole.staff) {
    await staffLoadCustoms();
  } else {
    await userLoadAccountManager();
  }
  loading.value = false;

  state.isEmpty = list.value.length === 0;
}
</script>
