import { ref } from "vue";

export default () => {
  return {
    props: ["modelValue", "label", "hideAll", "filter", "notShow", "url", "optid"],
    setup(props) {
      let options = ref([]);
      let cache = ref([]);

      let url = ref(props.url);
      let label = ref(props.label || "name");
      let optid = ref(props.optid || "id");
      let value = ref(props.modelValue || "");

      return {
        options,
        value,
        url,
        label,
        optid,
        cache,
      };
    },
    watch: {
      value() {
        this.$emit("update:modelValue", this.value);
        this.$emit("update:label", this.getLabel());
      },
      modelValue() {
        this.value = this.modelValue;
      },
    },
    computed: {
      showAll() {
        return this.hideAll !== "" || this.hideAll;
      },
    },
    methods: {
      getLabel() {
        let item = this.options.find((item) => item[this.optid || "id"] == this.value);
        if (item) {
          return item.name;
        } else {
          return "";
        }
      },
    },
    mounted() {
      if (!this.modelValue && this.hideAll === "") {
        if (this.options[0]) {
          this.value = String(this.options[0][this.optid || "id"]).trim();
        }
      }
      this.$emit("update:modelValue", String(this.value));
      this.$emit("update:label", this.getLabel());
    },
  };
};
