<template>
  <el-select
    v-if="dictData.length > 0"
    v-model="innerValue"
    :placeholder="placeholder"
    :clearable="clearable"
    :filterable="filterable"
    :disabled="disabled"
    @change="handleChange"
    @clear="handleClear"
  >
    <el-option
      v-for="(item, index) in dictData"
      :key="`${componentId}-${index}-${item[valueKey]}`"
      :label="item[labelKey]"
      :value="item[valueKey]"
    />
  </el-select>
</template>

<script>
import request from '@/utils/request'
import { loadDictData } from '@/utils/dictUtil'

let componentIdCounter = 0

export default {
  name: 'CommonDictSelect',
  props: {
    value: { type: [String, Number], default: '' },
    dictUrl: { type: String, required: true },
    // 新增：动态参数（用于联动，如仓库ID）
    dictParams: {
      type: Object,
      default: () => ({})
    },
    valueKey: { type: String, default: 'id' },
    labelKey: { type: String, default: 'name' },
    placeholder: { type: String, default: '请选择' },
    clearable: { type: Boolean, default: true },
    filterable: { type: Boolean, default: true },
    disabled: { type: Boolean, default: false },
    loadingText: { type: String, default: '加载中...' }
  },
  data() {
    return {
      dictData: [],
      componentId: `dict-select-${componentIdCounter++}`,
      innerValue: this.value
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.innerValue = newVal
      },
      immediate: true
    },
    innerValue(newVal) {
      this.$emit('input', newVal)
    },
    // 监听联动参数变化，重新加载字典
    dictParams: {
      handler() {
        this.loadDict()
      },
      deep: true, // 深度监听对象变化
      immediate: true
    }
  },
  async created() {
    this.loadDict()
  },
  methods: {
    // 封装加载字典方法（支持动态参数）
    async loadDict() {
      const rawData = await loadDictData(
        this.dictUrl,
        request,
        this.dictParams // 传递联动参数
      )
      this.dictData = this.uniqueDictData(rawData, this.valueKey)
      this.$emit('loaded', this.dictData)
    },
    // 对外暴露：手动更新字典数据（可选）
    updateDictData(params) {
      this.dictParams = params
      this.innerValue = '' // 清空当前选择
      this.$emit('input', '') // 同步到父组件
    },
    uniqueDictData(data, key) {
      if (!Array.isArray(data)) return []
      const valueMap = new Map()
      return data.filter(item => {
        if (!item || item[key] === undefined || item[key] === null) return false
        const valueStr = String(item[key]).trim()
        if (!valueMap.has(valueStr)) {
          valueMap.set(valueStr, true)
          return true
        }
        return false
      })
    },
    handleChange(val) {
      this.$emit('change', val)
    },
    handleClear() {
      this.$emit('clear')
      this.$emit('input', '')
    }
  }
}
</script>

<style scoped>
:deep(.el-select) {
  width: 100%;
}
</style>
