<template>
  <el-select
    v-model="selected"
    :placeholder="placeholder"
    filterable
    clearable
    @change="onChange"
    style="width: 100%"
    :value-key="'rawMaterialId'"
  >
    <el-option
      v-for="item in options"
      :key="item.rawMaterialId"
      :label="`${item.rawMaterialName}（${item.rawMaterialCode}）`"
      :value="item.rawMaterialId"
    >
      <div class="option-label">
        <span class="material-name">{{ item.rawMaterialName }}</span>
        <span class="material-code">{{ item.rawMaterialCode }}</span>
      </div>
    </el-option>
  </el-select>
</template>

<script>
import { listRawMaterial } from "@/api/wms/rawMaterial";

export default {
  name: "RawMaterialSelect",
  props: {
    value: [String, null],
    placeholder: {
      type: String,
      default: "请选择原材料"
    }
  },
  data() {
    return {
      options: [],
      selected: this.value
    };
  },
  watch: {
    value(val) {
      this.selected = val;
    },
    selected(val) {
      this.$emit("input", val);
      this.$emit("change", val);
    }
  },
  mounted() {
    this.fetchOptions();
  },
  methods: {
    fetchOptions() {
      listRawMaterial({ pageNum: 1, pageSize: 1000 }).then(res => {
        this.options = res.rows || [];
      });
    },
    onChange(val) {
      this.$emit("input", val);
      this.$emit("change", val);
    }
  }
};
</script>

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