<template>
  <div>
    <a-select
      v-model="selectedValue"
      :placeholder="placeholder"
      class="x-select"
      :class="wrapperClassObject()"
      :allowClear="true"
      :showSearch="true"
      :filter-option="filterOption"
      @change="handleChange"
    >
      <a-select-option v-for="(item, index) in data" :key="index" :value="item.value">
        {{ item.label }}
      </a-select-option>
    </a-select>
  </div>
</template>

<script>
import { runLogic } from '@vue2-client/services/api/common'

export default {
  name: 'XSelect',
  props: {
    queryParamsName: {
      type: [String, Object],
      default: null
    }
  },
  data () {
    return {
      data: [],
      selectedValue: undefined,
      placeholder: ''
    }
  },
  created () {
    this.getData(this.queryParamsName)
  },
  methods: {
    async getData (config) {
      try {
        const res = await runLogic(config, {}, 'af-his')
        this.data = res.data || []
        if (res.placeholder) {
          this.placeholder = res.placeholder
        }
        this.selectedValue = undefined
      } catch (error) {
        console.error('获取数据失败：', error)
      }
    },
    handleChange (value) {
      this.selectedValue = value === '' ? undefined : value
      this.$emit('change', this.selectedValue)
    },
    filterOption (input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    wrapperClassObject () {
      const attrs = this.$attrs || {}
      const classes = {}
      const booleanStyleKeys = [
        'x-select4'
      ]
      booleanStyleKeys.forEach(key => {
        const val = attrs[key]
        const truthy = val === true || val === '' || val === 'true'
        if (truthy) classes[`x-select-${key}`] = true
      })
      return classes
    },
  },
  watch: {
    selectedValue (val) {
    }
  }
}
</script>

<style scoped lang="less">
.x-select {
  min-width: 150px;
}

.x-select-x-select4 {
  width: 100%;
  min-width: auto;
}
</style>
