<template>
  <LayoutVue>
    <div class="flex flex-col w-full h-full">
      <div class="flex items-center flex-shrink-0">
        <Search
          :model-value="currentSearchStr"
          @update:model-value="handleCurrentSearchStrChange"
          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">
        <CopyrightTable
          ref="copyrightTableRef"
          v-show="activedMenu === eCollectionType.copyright"
          :debounced-search-str="debouncedSearchStrOfCopyright"
          :table-data="tableDataOfPicture"
          :loading="loadingOfPicture"
          @scroll-to-end="fetchNextPageOfPicture"
          @transferExecuted="handleTransferExecuted"
        ></CopyrightTable>
        <AlbumTable
          ref="derivativesTableRef"
          v-show="activedMenu === eCollectionType.derivatives"
          :debounced-search-str="debouncedSearchStrOfDerivatives"
          :table-data="tableDataOfDerivatives"
          :loading="loadingOfDerivatives"
          @go-to-detail="
            $router.push({
              name: 'issuedDerivativesDetail',
              query: $event,
            })
          "
          @update="refetchDerivatives"
          @scroll-to-end="fetchNextPageOfDerivatives"
        ></AlbumTable>
        <AlbumTable
          ref="albumTableRef"
          v-show="activedMenu === eCollectionType.album"
          :debounced-search-str="debouncedSearchStrOfAlbum"
          :table-data="tableDataOfAlbum"
          :loading="loadingOfAlbum"
          @go-to-detail="
            $router.push({
              name: 'issuedAlbumDetail',
              query: $event,
            })
          "
          @update="refetchAlbum"
          @scroll-to-end="fetchNextPageOfAlbum"
        ></AlbumTable>
      </div>
    </div>
  </LayoutVue>
</template>
<script lang="ts" setup>
import { computed, onBeforeMount, ref, watch } from "vue";

import { GO_URLS, syButton } from "cqk-sy-ui";
import syMenu from "@/components/Menu/syMenu.vue";
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 CopyrightTable from "./components/CopyrightTable/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 searchStrOfCopyright = ref("");
const searchStrOfDerivatives = ref("");
const searchStrOfAlbum = ref("");

const debouncedSearchStrOfCopyright = ref("");
const debouncedSearchStrOfDerivatives = ref("");
const debouncedSearchStrOfAlbum = ref("");

const copyrightTableRef = ref<InstanceType<typeof CopyrightTable>>();
const derivativesTableRef = ref<InstanceType<typeof AlbumTable>>();
const albumTableRef = ref<InstanceType<typeof AlbumTable>>();
const activedMenu = ref(eCollectionType.copyright);
const menuList = [
  { label: "版权", value: eCollectionType.copyright },
  { label: "衍生品", value: eCollectionType.derivatives },
  { label: "专辑", value: eCollectionType.album },
];
const currentSearchStr = computed(() => {
  if (activedMenu.value === eCollectionType.copyright) {
    return searchStrOfCopyright.value;
  } else if (activedMenu.value === eCollectionType.derivatives) {
    return searchStrOfDerivatives.value;
  } else if (activedMenu.value === eCollectionType.album) {
    return searchStrOfAlbum.value;
  }
  return "";
});

function handleCurrentSearchStrChange(str: string) {
  if (activedMenu.value === eCollectionType.copyright) {
    searchStrOfCopyright.value = str;
  } else if (activedMenu.value === eCollectionType.derivatives) {
    searchStrOfDerivatives.value = str;
  } else if (activedMenu.value === eCollectionType.album) {
    searchStrOfAlbum.value = str;
  }
}

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

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

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

const {
  fetchNextPage: fetchNextPageOfDerivatives,
  tableData: tableDataOfDerivatives,
  loading: loadingOfDerivatives,
  refetch: __refetchOfDerivatives,
} = useTableData({
  fetchData: fetchDerivativesData,
});

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

async function fetchDerivativesData({
  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: searchStrOfDerivatives.value,
      batch_type: 2,
    },
  });
  return {
    total: res!.data.total,
    data: res!.data.results || [],
  };
}

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,
      batch_type: 1,
    },
  });
  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: searchStrOfCopyright.value,
    },
  });
  return {
    total: res!.data.total,
    data: res!.data.results || [],
  };
}

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

watchDebounced(
  searchStrOfDerivatives,
  () => {
    refetchDerivatives().then(() => {
      debouncedSearchStrOfDerivatives.value = searchStrOfDerivatives.value;
    });
  },
  {
    debounce: watchStrChangeDebounceTime,
  }
);

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

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

function refetchAlbum() {
  return __refetchOfAlbum();
}

function refetchDerivatives() {
  return __refetchOfDerivatives();
}

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>
