<script setup lang="ts">
import { ref, shallowRef, watch } from "vue";
import {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>[]>([]);


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

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

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

      if (isIntial && !_companyNo) {
        const { code } = list.value[0] || {};
        value.value = code;
        handleChange(code);
      } else { 
        value.value = _companyNo
        handleChange(_companyNo);
      }
    }
  });
}

async function filterMethod(name: string) { 
  if (!name) return

  const { data, message, code } = await httpSupplierList({
    name,
    size: 100
  });

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

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"
    :filter-method="filterMethod"
  >
    <ElOption
      v-for="opt in list"
      :key="opt.code"
      :value="opt.code"
      :label="opt.name"
    />
  </ElSelect>
</template>
