<script setup lang="ts">
import { useDebounceFn } from "@vueuse/core";
import { ref, onMounted, reactive, onUnmounted, watch } from "vue";
import { httpBusinessList, httpSupplierList } from "/@/api/user";
import { useResponseHandle } from "/@/hooks/core/useAsync";
import { useCompany } from "/@/hooks/core/useCompany";
import { useUserInfo } from "/@/hooks/core/useUser";

const emit = defineEmits(["change", "update:code"]);

const props = withDefaults(
  defineProps<{
    noAll?: boolean;
    noSet?: boolean;
    code?: string;
    isSupplier?: boolean;
    placeholder?: string;
  }>(),
  {
    code: "all"
  }
);

const { setCurrentCompany } = useCompany();
const responseHandle = useResponseHandle();

const { userLevel } = useUserInfo();

const code = ref(props.code);
const selectRef = ref(null);
const list = ref<any[]>([]);

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

let scrollWrapper: HTMLDivElement | null = null;

const debounceScroll = useDebounceFn(handleScroll, 500);
const convert = (list:any[]) => list.map(item => ({ ...item, code: item.code, name: item.name }))

async function requestSupplierAll(name: string, companyNo: string) {
  state.name = name;
  state.page = 1;
  state.noMore = false;
  const isSupplier = userLevel.value === "3" || props.isSupplier;
  const api =
    isSupplier || props.isSupplier ? httpSupplierList : httpBusinessList;

  const { data, message, code } = await api({
    [isSupplier ? "name" : "company_name"]: state.name,
    [isSupplier ? "code" : "companyNo"]: companyNo,
    size:10,
    page: state.page
  });

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

function handleChange(value) {
  const item = list.value.find(({ companyNo }) => companyNo === value);
  if (!props.noSet) {
    setCurrentCompany(item);
  }
  emit("change", item);
}

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 api = httpBusinessList
    const { data, message, code } = await api({
      name: state.name,
      page: state.page,
      size:10,
      noRela: true
    });

    const pushCompany = (_list: any[]) => list.value = [...list.value, ...convert(_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);
      }
    });
  }
}

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

onUnmounted(() => {
  state.loading = false;
  state.noMore = false;
  state.name = "";
  state.page = 1;
  scrollWrapper?.removeEventListener("scroll", debounceScroll);
});

watch(
  () => userLevel.value,
  level => {
    if (level !== "") {
      state.loading = false;
      state.noMore = false;
      state.name = "";
      state.page = 1;
      list.value = [];
      requestSupplierAll(undefined, props.code);
    }
  }
);

const getLabel = company => {
  const { company_name, company_license } = company;
  return company_license + " / " + company_name
};

requestSupplierAll(undefined, props.code);


watch(() => props.code, () => {
  console.log(props.code.length)
}, {
  immediate: true
})

defineExpose({
  selectAll: () => (code.value = "all")
});
</script>

<template>
  <ElSelect
    filterable
    remote
    v-model="code"
    :remote-method="requestSupplierAll"
    @change="handleChange"
    style="width: 450px"
    :placeholder="placeholder"
    ref="selectRef"
  >
    <ElOption label="所有业务公司" value="all" />

    <ElOption
      class="super-item"
      v-for="c in list"
      :key="c.companyNo"
      :value="c.companyNo"
      :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>
