<script setup lang="ts">
import { ref, onMounted, reactive, onUnmounted, watchEffect } from "vue";
import { useDebounceFn } from "@vueuse/core";
import { useRouter, useRoute } from "vue-router";
import { httpCompany } from "/@/api/user";
import { useResponseHandle } from "/@/hooks/core/useAsync";
import { useCompany } from "/@/hooks/core/useCompany";
import { initRouter } from "/@/router/utils";
import { setRelaComName, setRelaComNo } from "/@/utils/auth";

const props = defineProps<{
  noSet?: boolean;
}>();

const { setCurrentCompany, currentCompany, setCompanyList, companyList } =
  useCompany();

const route = useRoute();
const router = useRouter();

const selectRef = ref(null);
const list = ref<any[]>(companyList.value);
const responseHandle = useResponseHandle();

const state = reactive({
  loading: false,
  noMore: false,
  name: "",
  count: 0,
  page: 1
});

let scrollWrapper: HTMLDivElement | null = null;

const debouceScroll = useDebounceFn(handleScroll, 500);

async function requesetSupplierAll(name: string) {
  state.name = name;
  state.page = 1;
  state.noMore = false;

  const { data, message, code } = await httpCompany({
    companyName: state.name,
    page: state.page,
    noRela: true
  });

  responseHandle({
    code,
    message,
    handler: () => {
      list.value = data.list;
      state.count = data.count;
      state.loading = false;
      const maxPage = Math.ceil(state.count / 10);
      state.noMore = maxPage <= 1;
    }
  });
}

onMounted(() => {
  setTimeout(() => {
    const superItem = document.querySelector(".super-item");
    if (!superItem) return;
    scrollWrapper = superItem.parentElement?.parentElement as HTMLDivElement;
    if (!scrollWrapper) return;
    scrollWrapper.addEventListener("scroll", debouceScroll, false);
  }, 1000);
});

async function handleScroll() {
  const height = scrollWrapper.clientHeight;
  const scrollTop = scrollWrapper.scrollTop;
  const scrollHeight = scrollWrapper.scrollHeight;

  if (height + scrollTop >= scrollHeight && !state.noMore) {
    state.page++;
    state.loading = true;

    const { data, message, code } = await httpCompany({
      companyName: state.name,
      page: state.page,
      noRela: true
    });

    const pushCompany = (_list: any[]) => {
      list.value = [...list.value, ..._list];
    };

    responseHandle({
      code,
      message,
      handler: () => {
        state.count = data.count;
        const maxPage = Math.ceil(state.count / 10);

        if (state.page > maxPage) {
          state.noMore = true;
          state.loading = false;
          return;
        }

        pushCompany(data.list);
      }
    });
  }
}

onUnmounted(() => {
  state.loading = false;
  state.noMore = false;
  state.name = "";
  state.page = 1;

  if (scrollWrapper) {
    scrollWrapper.removeEventListener("scroll", debouceScroll);
  }
});

async function handleChange(value) {
  if (props.noSet) return;

  try {
    const { companyName } = setCurrentCompany(value, list.value);

    setRelaComNo(value);
    setRelaComName(companyName);
    await initRouter();

    const { path } = route;
    if (path.indexOf("Detail") >= 0) {
      const listPath = path.split("Detail");
      router.replace(listPath[0]);
      return;
    }

    router.replace(route.path + "?reload=" + value);
  } catch (err) {
    router.replace("/welcome" + "?reload=" + value + "&" + "error=" + "1");
  }
}

const getLabel = company => {
  const { companyCode, companyName } = company;
  return companyCode + " / " + companyName;
};

watchEffect(() => setCompanyList(list.value));
requesetSupplierAll("");
</script>

<template>
  <ElSelect
    filterable
    remote
    ref="selectRef"
    :model-value="currentCompany.companyCode"
    :remote-method="requesetSupplierAll"
    style="width: 450px"
    @change="handleChange"
  >
    <ElOption
      class="super-item"
      v-for="c in list"
      :key="c.companyCode"
      :value="c.companyCode"
      :label="getLabel(c)"
    />
    <p class="super-loading" v-if="state.loading">
      <IconifyIconOffline class="animate-spin" icon="Loading" />
      加载中...
    </p>

    <p class="super-no-more" v-if="state.noMore">没有更多数据了...</p>
  </ElSelect>
</template>
<style lang="scss" scoped>
.super-no-more {
  text-align: center;
  color: #999;
  font-size: 14px;
  line-height: 38px;
}

.super-loading {
  display: flex;
  font-size: 14px;
  justify-content: center;
  align-items: center;
  color: #999;
  gap: 10px;
  line-height: 38px;
}
</style>
