<template>
  <LayoutVue>
    <div class="flex flex-col w-full h-full">
      <div class="flex items-center flex-shrink-0">
        <Search
          :model-value="
            activedMenu === eCollectionType.picture
              ? searchStrOfPicture
              : searchStrOfAlbum
          "
          @update:model-value="
            (v) => {
              if (activedMenu === eCollectionType.picture) {
                searchStrOfPicture = v;
              } else {
                searchStrOfAlbum = v;
              }
            }
          "
          placeholder="搜索"
        ></Search>
        <Avatar class="ml-7"></Avatar>
      </div>
      <div
        class="flex items-center justify-between flex-shrink-0"
        style="margin-top: 26px"
      >
        <Title>藏品管理</Title>
        <div class="flex items-center">
          <syButton
            style="width: 113px"
            mode="elementBtn"
            size="large"
            @click="
              () => {
                $router.push({
                  name: 'albumManagement',
                });
              }
            "
            type="default"
          >
            <Icon
              icon-name="iconzhuanjiguanli"
              style="margin-right: 3px"
            ></Icon>
            专辑管理</syButton
          >
          <syButton
            style="width: 113px"
            mode="elementBtn"
            size="large"
            @click="
              () => {
                $router.push({
                  name: 'transferRecords',
                  query: {
                    type: activedMenu,
                  },
                });
              }
            "
            type="default"
          >
            <Icon icon-name="iconhuazhuanjilu" style="margin-right: 3px"></Icon>
            划转记录</syButton
          >
          <syButton
            style="width: 113px"
            mode="elementBtn"
            size="large"
            @click="$router.push('/passMaker')"
            type="primary"
            >发行藏品</syButton
          >
        </div>
      </div>
      <syMenu
        class="flex-shrink-0"
        v-model="activedMenu"
        :menu-list="menuList"
        style="margin-bottom: 15px"
      ></syMenu>

      <div class="flex-grow overflow-hidden relative">
        <PictureTable
          v-if="tableDataOfPicture.length !== 0"
          ref="pictureTableRef"
          v-show="activedMenu === eCollectionType.picture"
          :active="activedMenu === eCollectionType.picture"
          :table-data="tableDataOfPicture"
          :loading="loadingOfPicture"
          @scroll-to-end="fetchNextPageOfPicture"
          @transferExecuted="handleTransferExecuted"
        ></PictureTable>
        <Empty
          v-if="
            activedMenu === eCollectionType.picture &&
            !loadingOfPicture &&
            tableDataOfPicture.length === 0
          "
          class="absolute top-1/3 left-1/2 transform -translate-x-1/2 -translate-y-1/2"
        >
          {{
            searchingStrOfPicture === ""
              ? "暂无数据"
              : "没有找到匹配结果，尝试其他关键词搜索"
          }}
        </Empty>
        <AlbumTable
          v-if="tableDataOfAlbum.length !== 0"
          v-show="activedMenu === eCollectionType.album"
          :active="activedMenu === eCollectionType.album"
          :table-data="tableDataOfAlbum"
          :loading="loadingOfAlbum"
          @update="refetchAlbum"
          @scroll-to-end="fetchNextPageOfAlbum"
        ></AlbumTable>
        <Empty
          v-if="
            activedMenu === eCollectionType.album &&
            !loadingOfAlbum &&
            tableDataOfAlbum.length === 0
          "
          class="absolute top-1/3 left-1/2 transform -translate-x-1/2 -translate-y-1/2"
        >
          {{
            searchingStrOfAlbum === ""
              ? "暂无数据"
              : "没有找到匹配结果，尝试其他关键词搜索"
          }}
        </Empty>
      </div>
    </div>
  </LayoutVue>
</template>
<script lang="ts" setup>
import { onBeforeMount, ref, watch } from "vue";

import { GO_URLS, syButton, syMenu } from "cqk-sy-ui";
import LayoutVue from "@/components/Layout.vue";
import Search from "@/components/Search/index.vue";
import Avatar from "@/components/Avatar/index.vue";
import Title from "@/components/Title.vue";
import Icon from "@/components/Icon/index.vue";
import PictureTable from "./components/PictureTable/index.vue";
import AlbumTable from "./components/AlbumTable/index.vue";

import { eCollectionType } from "../PassMaker/types";
import { useTableData } from "@/components/Table/hooks";
import { watchDebounced } from "@vueuse/core";
import { watchStrChangeDebounceTime } from "@/config/time";
import { $ajax } from "@/service";
import { sleep } from "@/utils/promise";
import { URLS } from "@/service/URL";
import Empty from "@/components/Empty/index.vue";
import { useRoute } from "vue-router";
import { router } from "@/router";

const searchStrOfPicture = ref("");
const searchStrOfAlbum = ref("");

const searchingStrOfPicture = ref("");
const searchingStrOfAlbum = ref("");

const pictureTableRef = ref<InstanceType<typeof PictureTable>>();
const activedMenu = ref(eCollectionType.picture);
const menuList = [
  { label: "藏品列表", value: eCollectionType.picture },
  { label: "专辑列表", value: eCollectionType.album },
];

const route = useRoute();
onBeforeMount(() => {
  activedMenu.value =
    (route.query.type as eCollectionType) || eCollectionType.picture;
});

watch(activedMenu, (menu) => {
  router.push({
    query: {
      type: menu,
    },
  });
});

const {
  fetchNextPage: fetchNextPageOfPicture,
  tableData: tableDataOfPicture,
  loading: loadingOfPicture,
  refetch: __refetchOfPicture,
} = useTableData({
  fetchData: fetchPictureData,
});

const {
  fetchNextPage: fetchNextPageOfAlbum,
  tableData: tableDataOfAlbum,
  loading: loadingOfAlbum,
  refetch: __refetchOfAlbum,
} = useTableData({
  fetchData: fetchAlbumData,
});

async function fetchAlbumData({
  page,
  page_size,
}: {
  page: number;
  page_size: number;
}): Promise<{
  total: number;
  data: any[];
}> {
  const res = await $ajax({
    type: "get",
    url: URLS.batches,
    params: {
      page: page,
      page_size: page_size,
      name: searchStrOfAlbum.value,
    },
  });
  return {
    total: res!.data.total,
    data: res!.data.results || [],
  };
}
async function fetchPictureData({
  page,
  page_size,
}: {
  page: number;
  page_size: number;
}): Promise<{
  total: number;
  data: any[];
}> {
  const res = await $ajax({
    type: "get",
    url: GO_URLS.passList,
    params: {
      page: page,
      page_size: page_size,
      name: searchStrOfPicture.value,
    },
  });
  return {
    total: res!.data.total,
    data: res!.data.results || [],
  };
}

watchDebounced(
  searchStrOfPicture,
  () => {
    refetchPicture().then(() => {
      searchingStrOfPicture.value = searchStrOfPicture.value;
    });
  },
  { debounce: watchStrChangeDebounceTime }
);

watchDebounced(
  searchStrOfAlbum,
  () => {
    refetchAlbum().then(() => {
      searchingStrOfAlbum.value = searchStrOfAlbum.value;
    });
  },
  { debounce: watchStrChangeDebounceTime }
);

function refetchPicture() {
  pictureTableRef.value?.scrollTo(0, 0);
  return __refetchOfPicture();
}

function refetchAlbum() {
  pictureTableRef.value?.scrollTo(0, 0);
  return __refetchOfAlbum();
}

const handleTransferExecuted = async (id: number, balance: number) => {
  try {
    await keepQueryingUntilTheTransferIsSuccessful(id, balance);
    refetchPicture();
  } catch (err) {}
};

const keepQueryingUntilTheTransferIsSuccessful = async (
  id: number,
  balance: number,
  count = 5
): Promise<boolean> => {
  if (count === 0) {
    throw new Error("超过查询次数");
  }
  const res = await $ajax({
    type: "get",
    url: GO_URLS.pass,
    params: {
      id,
    },
  });
  count--;
  if (res?.data.balance !== balance) {
    return true;
  } else {
    await sleep(4000);
    return keepQueryingUntilTheTransferIsSuccessful(id, balance, count);
  }
};
</script>
<style lang="scss" scoped></style>
