<template>
  <div>
    <el-select v-model="innerValue" placeholder="请选择" v-if="orderId" clearable>
      <el-option
        v-for="item in options"
        :key="item.itemId"
        :label="item.materialTypeCode + '[' + item.specification + ']'"
        :value="item.itemId"
      />
    </el-select>
    <!-- <div v-else-if="loading" style="border: 1px solid #828991; padding: 1px;">
      加载中...
    </div> -->
    <div v-else v-loading="loading" style="border: 1px solid #828991; padding: 1px;">请先选择订单后再选择明细</div>
  </div>
</template>

<script>
import { listPurchaseOrderItem } from '@/api/erp/purchase'

export default {
  props: {
    orderId: {
      type: String,
      default: () => ''
    },
    value: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      options: [],
      loading: false
    }
  },
  computed: {
    innerValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  methods: {
    loadItems() {
      if (!this.orderId) {
        return
      }
      this.loading = true
      listPurchaseOrderItem({
        orderId: this.orderId,
        pageSize: 9999,
      }).then(res => {
        this.loading = false
        if (res.code === 200) {
          this.options = res.rows || []
        }
      }).catch(error => {
        this.loading = false
        console.error('订单明细搜索失败:', error)
      })
    }
  },
  watch: {
    orderId: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.loadItems()
        }
      },
      immediate: true
    }
  }
}
</script>