import { createVNode as _createVNode, isVNode as _isVNode } from "vue";
import { defineComponent, ref, computed } from "vue";
import Tag from '../../tag';

function _isSlot(s) {
  return typeof s === 'function' || Object.prototype.toString.call(s) === '[object Object]' && !_isVNode(s);
}

export default defineComponent({
  name: 'Selector',
  props: {
    prefixCls: String,
    values: Array,
    searchValue: String,
    multiple: Boolean,
    showArrow: Boolean,
    filterable: Boolean,
    allowClear: Boolean,
    disabled: Boolean,
    placeholder: String,
    inputRef: {
      default: () => ref()
    },
    onSelect: Function,
    onSearch: Function,
    onToggleOpen: Function,
    onFocus: Function,
    onBlur: Function
  },

  setup(props) {
    const hasTextInput = computed(() => {
      var _props$values;

      return !!((_props$values = props.values) !== null && _props$values !== void 0 && _props$values.length) || !!props.searchValue;
    });

    function getLabel(item) {
      if (!item) return item;
      let content;
      if (content === undefined) content = item.label;
      if (content === undefined) content = item.value;
      if (content === undefined) content = item;
      return content;
    }

    function onSelect(item) {
      var _props$onSelect;

      (_props$onSelect = props.onSelect) === null || _props$onSelect === void 0 ? void 0 : _props$onSelect.call(props, item);
    }

    function onClick() {
      props.inputRef.value.focus();
    }

    function onMousedown() {
      props.onToggleOpen();
    }

    function onInputChange(e) {
      props.onToggleOpen(true);
      props.onSearch(e.target.value);
    }

    return () => {
      const {
        prefixCls,
        values = [],
        multiple
      } = props;
      const inputProps = {
        class: `${prefixCls}_search_input`,
        ref: props.inputRef,
        value: props.searchValue,
        readonly: !props.filterable || props.disabled,
        disabled: props.disabled,
        placeholder: !values.length ? props.placeholder : undefined,
        onInput: onInputChange,
        onFocus: props.onFocus,
        onBlur: props.onBlur
      };
      const tagsNode = multiple ? values.map(e => {
        let _slot;

        return _createVNode(Tag, {
          "class": `${prefixCls}_tag`,
          "closable": !props.disabled,
          "onClose": () => onSelect(e)
        }, _isSlot(_slot = getLabel(e)) ? _slot : {
          default: () => [_slot]
        });
      }) : undefined;

      const textNode = _createVNode("span", {
        "class": `${prefixCls}_text`
      }, [!multiple && !props.searchValue ? getLabel(values[0]) : ' ']);

      return _createVNode("div", {
        "class": `${prefixCls}_selector`,
        "onClick": onClick,
        "onMousedown": onMousedown
      }, [tagsNode, _createVNode("div", {
        "class": `${prefixCls}_search`
      }, [_createVNode("input", inputProps, null)]), textNode]);
    };
  }

});