<template>
  <el-select
    v-model="selectedValue"
    placeholder="请选择或搜索订单"
    clearable
    filterable
    remote
    :remote-method="handleRemoteSearch"
    :loading="loading"
    @change="handleSelectChange"
    style="width: 100%"
  >
    <!-- 下拉选项 -->
    <el-option
      v-for="item in orderList"
      :key="item.orderId"
      :label="item.orderCode"
      :value="item.orderId"
    />

    <!-- 无数据提示 -->
    <el-option
      v-if="orderList.length === 0 && !loading"
      value=""
      disabled
    >
      暂无匹配订单
    </el-option>
  </el-select>
</template>

<script>
import { listOrder } from '@/api/wms/order'
import { debounce } from 'lodash' // 引入防抖函数

export default {
  name: 'OrderSelect',
  data() {
    return {
      orderList: [],
      loading: false,
      queryParams: {
        orderCode: undefined,
        pageNum: 1,
        pageSize: 20
      },
      selectedValue: undefined
    }
  },
  created() {
    // 初始化加载订单列表
    this.getList()
    
    // 初始化防抖搜索方法（300ms延迟）
    this.debouncedSearch = debounce(this.getList, 300)
  },
  methods: {
    // 远程搜索方法
    handleRemoteSearch(query) {
      this.queryParams.orderCode = query
      this.queryParams.pageNum = 1 // 重置页码
      this.debouncedSearch() // 使用防抖搜索
    },
    
    // 获取订单列表
    getList() {
      this.loading = true
      listOrder(this.queryParams).then(res => {
        this.orderList = res.rows || []
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.orderList = []
      })
    },
    
    // 选择变化时触发
    handleSelectChange(orderId) {
      // 找到选中的完整订单项
      const selectedItem = this.orderList.find(item => item.orderId === orderId)
      // 通过onchange事件返回完整订单项
      this.$emit('change', selectedItem)
    }
  }
}
</script>
