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

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

const props = defineProps<{
  value?: string;
  placeholder?: string;
  isSupplier?: boolean;
}>();

const responseHandle = useResponseHandle();

const { userLevel } = useUserInfo();

const value = shallowRef("");
const list = ref<Record<string, string>[]>([]);

function convertList(list) {
  const isSupplier = userLevel.value === "3" || props.isSupplier;
  if (isSupplier) return list;
  return list.map(item => ({
    ...item,
    code: item.companyNo,
    name: item.company
  }));
}

async function requesetCompanies(
  name: string,
  companyNo: string,
  isIntial?: boolean
) {
  const api = httpBusinessList;

  const { data, message, code } = await api({
    name,
    size: 99999
  });

  responseHandle({
    code,
    message,
    handler: () => {
      list.value = convertList(data);

      if (isIntial) {
        const { companyNo } = list.value[0] || {};
        value.value = companyNo;
        handleChange(companyNo);
      }
    }
  });
}

const handleChange = value => emit("change", value);

watch(
  () => userLevel.value,
  level => {
    if (level !== "") {
      list.value = [];
      requesetCompanies(undefined, props.value);
    }
  }
);

async function intialData() {
  requesetCompanies(undefined, props.value, true);
}

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

<template>
  <ElSelect
    filterable
    v-model="value"
    @change="handleChange"
    style="width: 100%"
    :placeholder="placeholder"
  >
    <ElOption
      v-for="opt in list"
      :key="opt.code"
      :value="opt.code"
      :label="opt.name"
    />
  </ElSelect>
</template>
