<template>
  <el-select
    class="form-select"
    v-bind="$attrs"
    :placeholder="placeholder"
    @change="changeTarget"
    :value="value"
    @input="updateVal($event)"
    clearable
  >
    <el-option
      v-for="option in selectData[selectKey]"
      :label="option[props.label]"
      :value="option[props.value]"
      :key="option[props.value]"
    >
      <slot :row="option"></slot>
    </el-option>
  </el-select>
</template>

<script>
export default {
  name: "CmsFormSelect",
  inheritAttrs: true,
  props: {
    // //此处一定要用value
    value: {
      type: [String, Number, Boolean, Array],
      default: () => {
        return undefined;
      },
    },
    /**
     * 自定义匹配
     */
    matchKey: {
      type: Object,
      default: () => {
        return {};
      },
    },
    /**
     * 下拉框选择
     */
    selectData: {
      type: Object,
      required: true,
      default: () => {
        return {};
      },
    },
    selectKey: {
      type: String,
      required: true,
      default: () => {
        return undefined;
      },
    },
    placeholder: {
      type: String,
      required: true,
      default: () => {
        return "";
      },
    },
    props: {
      type: Object,
      default: () => {
        return {
          label: "label",
          value: "value",
        };
      },
    },
    formModel: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    let { ...listeners } = this.$listeners;
    return {
      listeners: listeners,
      localValue: undefined,
      elFormSelect: {},
    };
  },
  computed: {
    list: {
      get() {
        return this.selectData[this.selectKey];
      },
    },
  },
  created() {
    this.elFormSelect = {
      // minWight: document.getElementsByClassName("")
    };
  },
  mounted() {
    this.$nextTick(() => {
      $(this.$el)
        .find("div.el-select-dropdown")
        .css({
          width: $(this.$el).width() + "px",
        });
    });
    window.onresize = () => {
      $(this.$el)
        .find("div.el-select-dropdown")
        .css({
          width: $(this.$el).width() + "px",
        });
    };
  },
  methods: {
    updateVal(val) {
      this.$emit("input", val); // 通过事件实现组件属性到父组件的传递
    },
    changeTarget(val) {
      const newList = this.list.filter((item) => item[this.props.value] === val);
      const data = newList && newList.length > 0 ? newList[0] : undefined;
      if (data) {
        const matchKey = this.matchKey;
        for (const key in matchKey) {
          this.formModel[key] = data[matchKey[key]];
        }
      }
      this.$emit("select", data || {});
      this.$emit("change", data || {});
    },
  },
};
</script>

<style>
.form-select {
  width: 100%;
}
.el-select-dropdown {
  z-index: 4001 !important;
}
</style>
