<template>
  <el-select
    v-model="selected"
    :placeholder="placeholder"
    filterable
    clearable
    remote
    :remote-method="debouncedRemoteMethod"
    :loading="loading"
    @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";

function debounce(fn, delay) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

export default {
  name: "RawMaterialSelect",
  props: {
    value: [String, null],
    placeholder: {
      type: String,
      default: "请选择原材料"
    }
  },
  data() {
    return {
      options: [],
      selected: this.value,
      loading: false
    };
  },
  watch: {
    value(val) {
      this.selected = val;
    },
    selected(val) {
      this.$emit("input", val);
      this.$emit("change", val);
    }
  },
  mounted() {
    this.fetchOptions("");
  },
  methods: {
    fetchOptions(keyword) {
      this.loading = true;
      listRawMaterial({ pageNum: 1, pageSize: 10, rawMaterialName: keyword }).then(res => {
        this.options = res.rows || [];
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    remoteMethod(keyword) {
      this.fetchOptions(keyword);
    },
    debouncedRemoteMethod: debounce(function(keyword) {
      this.remoteMethod(keyword);
    }, 400),
    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>
