<template>
  <el-select
    v-model="innerValue"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    :filterable="filterable"
    @change="onChange"
  >
    <el-option
      v-for="item in categoryOptions"
      :key="item.categoryId"
      :label="item.categoryName"
      :value="item.categoryId"
    />
  </el-select>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  name: 'CategorySelect',
  props: {
    value: {
      type: [Number, String, null],
      default: null
    },
    categoryType: {
      type: String,
      required: true,
      validator: v => [
        'base_material',
        'surface_treatment',
        'customer_req',
        'spec_packaging'
      ].includes(v)
    },
    placeholder: {
      type: String,
      default: '请选择分类'
    },
    clearable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    filterable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      innerValue: this.value
    };
  },
  computed: {
    ...mapState('category', ['categoryList']),
    categoryOptions() {
      return this.categoryList.filter(
        item => item.categoryType === this.categoryType && item.isEnabled === 1
      );
    }
  },
  watch: {
    value(val) {
      this.innerValue = val;
    }
  },
  created() {
    if (!this.categoryList || this.categoryList.length === 0) {
      this.getCategoryList();
    }
  },
  methods: {
    ...mapActions('category', ['getCategoryList']),
    onChange(val) {
      this.$emit('input', val);
      this.$emit('change', val);
    }
  }
};
</script>

<style scoped>
</style>
