<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;
  disabled: 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
) {
  console.log(_companyNo);

  const api = httpBusinessList;

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

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

      if (isIntial && !_companyNo) {
        const { companyNo } = list.value[0] || {};
        value.value = companyNo;
        handleChange(companyNo);
      } else { 
        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(value: string) {
  requesetCompanies(undefined, value, true);
}

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

<template>
  <ElSelect
    filterable
    :disabled="disabled"
    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>
