<template>
  <el-select
    v-model="selected"
    :placeholder="placeholder"
    :disabled="disabled"
    filterable
    clearable
    @change="onChange"
    style="width: 100%"
    :value-key="'productId'"
  >
    <el-option
      v-for="item in productOptions"
      :key="item.productId"
      :label="`${item.productName}（${item.productCode}）`"
      :value="item.productId"
    >
      <div class="option-label">
        <span class="product-name">{{ item.productName }}</span>
        <span class="product-code">{{ item.productCode }}</span>
      </div>
    </el-option>
  </el-select>
</template>

<script>
import { listProduct } from '@/api/wms/product';

export default {
  name: 'SemiSelect',
  props: {
    value: [String, null],
    disabled: Boolean,
    placeholder: {
      type: String,
      default: '请选择产品'
    }
  },
  data() {
    return {
      productOptions: [],
      selected: this.value
    };
  },
  watch: {
    value(val) {
      this.selected = val;
    },
    selected(val) {
      this.$emit('input', val);
    }
  },
  created() {
    this.getProductOptions();
  },
  methods: {
    getProductOptions() {
      listProduct({ pageNum: 1, pageSize: 1000, type: 'semi' }).then(res => {
        this.productOptions = res.rows || [];
      });
    },
    onChange(val) {
      // 通过val找到item
      const product = this.productOptions.find(p => p.productId === val);
      this.$emit('change', product);
    }
  }
};
</script>

<style scoped>
.option-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.product-name {
  font-size: 14px;
  color: #333;
}
.product-code {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}
</style>
