<template>
  <el-select
    v-model="selectedValue"
    :style="`width: ${width}`"
    :placeholder="placeholder"
    :disabled="disabled"
    :clearable="clearable"
    :multiple="multiple"
    :filterable="filterable"
    :value-key="valueKey"
    :loading="loading"
    @change="handleChange"
    @clear="handleClear"
  >
    <el-option
      v-for="item in items"
      :key="item.id"
      :label="item.code"
      :value="getOptionValue(item)"
    >
      <span>{{ item.code }}</span>
      <span>{{ item.name }}</span>
    </el-option>
  </el-select>
</template>

<script>
import curdArea from '@/api/area'
import CRUD from '@crud/crud'

export default {
  name: 'AreaSelect',
  props: {
    value: {
      type: [String, Number, Boolean, Array, Object],
      default: () => null
    },
    width: {
      type: String,
      default: '200px'
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    disabled: Boolean,
    clearable: {
      type: Boolean,
      default: true
    },
    multiple: Boolean,
    filterable: {
      type: Boolean,
      default: true
    },
    valueKey: {
      type: String,
      default: 'id'
    },
    isEnabled: {
      type: Boolean,
      default: true
    },
    bexb: {
      type: Boolean,
      default: true
    },
    returnType: {
      type: String,
      default: 'object',
      validator: value => ['object', 'value'].includes(value)
    },
    returnValueKey: {//返回列字段
      type: String,
      default: 'id'
    }
  },

  data() {
    return {
      items: [],
      loading: false
    }
  },

  computed: {
    selectedValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },

  created() {
    this.initData()
  },

  methods: {
    async initData() {
      this.loading = true
      try {
        const res = await curdArea.queryAreaList({
          enabled: this.isEnabled,
          bexb: this.bexb
        })
        this.items = res || []
      } catch (error) {
        this.crud.notify('获取数据失败', CRUD.NOTIFICATION_TYPE.ERROR)
        this.items = []
      } finally {
        this.loading = false
      }
    },

    getOptionValue(item) {
      return this.returnType === 'object' ? item : item[this.returnValueKey]
    },

    handleChange(val) {
      this.$emit('change', val)
    },

    handleClear() {
      this.$emit('clear')
    }
  }
}
</script>
