<style lang="scss">
.z-schema-select {
  display: inline-block;
}
.z-schema-select__popper {
  padding: 0 !important;
}
.z-schema-select__popper-content {
  padding: 4px;
}
</style>

<template>
  <el-popover class="z-schema-select" popper-class="z-schema-select__popper" v-model="visible" trigger="click" placement="bottom-start" transition="el-zoom-in-top">
    <template #reference>
      <el-input
        class="el-select__input"
        v-model="model"
        :size="selectSize"
        :disabled="selectDisabled"
        prefix-icon="el-icon-search"
        :placeholder="selectPlaceholder"
        @input="debouncedOnInput"
        @focus="onInputFocus"
        @blur="onInputBlur"
        @mouseenter.native="inputHovering = true"
        @mouseleave.native="inputHovering = false"
      >
        <template #suffix>
          <i v-if="showClose" class="el-input__icon el-icon-circle-close" @click="onClear"></i>
          <i v-else class="el-input__icon"></i>
        </template>
      </el-input>
    </template>
    <div class="z-schema-select__popper-content" v-clickoutside="onClickoutside">
      <z-schema-page
        ref="schema"
        :value-table.sync="tableData"
        :value-filter="valueFilter"
        @update:value-filter="e => $emit('update:value-filter', e)"
        :schema="selectSchema"
        :auto="auto"
        :api-search="apiSearch"
      >
        <template v-for="(item, index) in tableColumns" #[`table-cell-${item.prop}`]="{ value }">
          <cell-highlight v-if="highlight" :value="value" :keyword="query" :key="index"></cell-highlight>
          <template v-else>{{ value }}</template>
        </template>
      </z-schema-page>
    </div>
  </el-popover>
</template>

<script>
import debounce from 'throttle-debounce/debounce';
import Clickoutside from 'element-ui/src/utils/clickoutside';

export default {
  name: 'SchemaSelect',
  directives: { Clickoutside },
  components: {
    CellHighlight: {
      functional: true,
      render(h, context) {
        const props = context.props || {};
        const keyword = props.keyword;
        const value = props.value || '';
        const reg = new RegExp(`(${keyword})`, 'g');
        const result = `${value}`.replace(reg, '<font style="color: red;">$1</font>');
        return h('span', { domProps: { innerHTML: result } });
      },
    },
  },
  props: {
    value: String,
    schema: {
      required: true,
      type: Object,
      default() {
        return {};
      },
    },
    auto: {
      type: Boolean,
      default: true,
    },
    // clearable: Boolean,
    clearable: {
      type: Boolean,
      default: true,
    },
    // highlight: Boolean,
    highlight: {
      type: Boolean,
      default: true,
    },
    disabled: Boolean,
    size: String,
    placeholder: String,
    labelKey: {
      type: String,
      default: 'label',
    },
    valueKey: {
      type: String,
      default: 'value',
    },
    'value-filter': {
      type: Object,
      default() {
        return {};
      },
    },
    'api-search': Function,
  },
  inject: {
    elForm: {
      default: undefined,
    },
    elFormItem: {
      default: undefined,
    },
  },
  data() {
    return {
      model: '',
      query: '',
      visible: false,
      inputHovering: false,
      tableData: [],
    };
  },
  created() {
    this.debouncedOnInput = debounce(300, () => {
      this.onInput();
    });
  },
  computed: {
    _elFormItemSize() {
      return (this.elFormItem || {}).elFormItemSize;
    },
    selectSize() {
      return this.size || this._elFormItemSize || (this.elForm || {}).size || (this.$ELEMENT || {}).size;
    },
    selectDisabled() {
      return this.disabled || (this.elForm || {}).disabled;
    },
    selectPlaceholder() {
      return this.selectedLabel || this.placeholder || '请选择';
    },
    selectedLabel() {
      if (this.value) {
        const item = this.tableData.find(item => item[this.valueKey] === this.value) || {};
        return item[this.labelKey];
      }
      return '';
    },
    selectSchema() {
      return {
        filter: false,
        action: false,
        operation: false,
        pagination: false,
        selection: false,
        ...this.schema,
        table: {
          on: {
            'row-click': this.onTableRowClick,
          },
          ...(this.schema.table || {}),
        },
      };
    },
    showClose() {
      let hasValue = this.value !== undefined && this.value !== null && this.value !== '';
      let criteria = this.clearable && !this.selectDisabled && this.inputHovering && hasValue;
      return criteria;
    },
    tableColumns() {
      if (this.schema) {
        return this.schema.items;
      }
      return [];
    },
  },
  methods: {
    // 输入查询
    onInput() {
      this.query = this.model;
      this.$refs.schema.search();
    },
    onInputFocus() {
      this.model = '';
    },
    onInputBlur() {
      if (!this.visible) {
        this.model = this.selectedLabel;
      }
    },
    onClickoutside() {
      if (this.visible) {
        this.model = this.selectedLabel;
      }
    },
    // 点击表格行
    onTableRowClick(row) {
      this.query = '';
      this.model = row.name;
      this.visible = false;
      this.$emit('input', row[this.valueKey]);
      this.$emit('change', row);
    },
    // 清空
    onClear(event) {
      event.stopPropagation();
      this.query = '';
      this.model = '';
      this.visible = false;
      this.$emit('input', '');
      this.$emit('clear');
      this.$emit('change', '');
      this.onInput();
    },
  },
};
</script>
