<script setup lang="ts">
import { onMounted, ref, type Ref } from "vue";
import { debounce } from "lodash";
import { PlusOutlined } from '@ant-design/icons-vue';
import * as companyService from "@/services/company.service";
import type { SelectProps } from "ant-design-vue";
import { CompLog } from "@/libs/log.lib";

const logError = CompLog.logErr("RelationCompanyInput")

const name: Ref<string> = ref('');
const companyId: Ref<number | null> = ref(null);

const props = defineProps({
  id: {
    type: Number,
    required: true,
  }
});

const options = ref<SelectProps['options']>([]);

const selectEl = ref<HTMLInputElement | null>(null);

const newName = ref('');

const visible = ref(false);

const emits = defineEmits<{
  (e: "change", companyId: number): void;
}>();

const fetchCompany = debounce((val) => {
  companyService.query(val, 10).then((companies) => {
    const data = companies.map((company) => ({ value: company.id, label: company.name }));
    options.value = data;
  }).catch(logError);
}, 300);

function onFocus() {
  fetchCompany(name.value);
}

function onChange(val: number) {
  companyId.value = val;
  emits("change", companyId.value);
}

function onModalOk() {
  visible.value = false;
  companyService.create(newName.value).then((company) => {
    name.value = company.name;
    companyId.value = company.id;
    emits("change", companyId.value);
  }).catch(logError);
}

function focus() {
  selectEl.value?.focus();
}

onMounted(() => {
  const id = props.id;
  if (id > 0) {
    companyService.get(id).then((company) => {
      companyId.value = id;
      name.value = company.name;
    }).catch(logError);
  }
});

defineExpose({
  focus
});
</script>

<template>
  <a-row type="flex" style="align-items: center">
    <a-col style="width: 120px; text-align: right;">
      关联企业：
    </a-col>
    <a-col flex="1">
      <a-select
        v-model:value="name"
        show-search
        mode="combobox"
        placeholder="input search text"
        style="width: 100%"
        :default-active-first-option="false"
        :show-arrow="true"
        :filter-option="false"
        :not-found-content="null"
        :options="options"
        @focus="onFocus"
        @search="fetchCompany"
        @change="onChange"
        ref="selectEl"
      >
      </a-select>
    </a-col>
    <a-col>
      <a-button @click="visible = true"><plus-outlined />新增企业</a-button>
    </a-col>
  </a-row>
  <a-modal v-model:visible="visible" title="新增企业名称" @ok="onModalOk">
    <p><a-input v-model:value="newName" placeholder="请输入新企业名称" /></p>
  </a-modal>
</template>