<template>
  <a-col :span="colSpan ? colSpan : defaultColSpan">
    <a-form-item :label="label" :name="name" :label-col="{ style: { width: !!textWidth ? textWidth : labelWidth } }"
      :wrapper-col="{ style: { flex: 1 } }">
      <paas-page-select v-bind="filteredAttrs" :placeholder="placeholder" :multiple="multiple"
        :disabled="see || disabled" v-model="innerValue" :url="url" :vars="vars" @change="onChange" :style="style" />
    </a-form-item>
  </a-col>
</template>

<script>
export default {
  name: 'FormPageSelect',
  inheritAttrs: false, // 禁用自动继承，手动控制透传
  inject: {
    labelWidth: {
      from: 'labelWidth',
      default: '90px',
    },
    defaultColSpan: {
      from: 'defaultColSpan',
      default: 12
    }
  },
  props: {
    placeholder: String,
    label: String,
    name: String,
    colSpan: { type: Number }, // 单个控件自定义列跨度
    multiple: { type: Boolean, default: false },
    textWidth: { type: String, default: '' },
    disabled: { type: Boolean, default: false },
    modelValue: [String, Array],
    url: { type: String, required: true },
    vars: { type: Object, default: () => ({}) },
    style: { type: String, default: '' },
  },
  data() {
    return {
      innerValue: this.modelValue,
      isInternalUpdate: false, // 防止watch重复触发
    }
  },
  computed: {
    see() {
      return this.$store?.forms?.see
    },
    filteredAttrs() {
      const attrs = { ...this.$attrs };
      Object.keys(attrs).forEach(key => {
        if (key.startsWith('on') || key.startsWith('@') || key.startsWith('on-')) {
          delete attrs[key];
        }
      });
      return attrs;
    },
  },
  watch: {
    modelValue(val) {
      this.isInternalUpdate = true;
      this.innerValue = val;
      this.$nextTick(() => {
        this.isInternalUpdate = false;
      });
    },
  },
  methods: {
    onChange(data) {
      // 防止外部modelValue变化导致的重复触发
      if (this.isInternalUpdate) {
        return;
      }

      let emitValue;
      if (Array.isArray(data)) {
        // 多选模式下，如果数组为空，应返回空字符串或空数组
        if (data.length === 0) {
          emitValue = this.multiple ? '' : undefined;
        } else {
          emitValue = this.multiple ? data.join(',') : data[0];
        }
      } else {
        // 单选模式下，直接使用data值或null
        emitValue = data;
      }

      // 确保空值能正确传递
      this.$emit('update:modelValue', emitValue != null ? emitValue : '');
      this.$emit('change', emitValue != null ? emitValue : '');
    },
  },
}
</script>
