<template>
  <el-select
    v-model="index"
    filterable
    clearable
    remote
    reserve-keyword
    :placeholder="$t('请输入商品关键词')"
    :disabled="disabled"
    :remote-method="remoteMethod"
    :loading="loading"
    @focus="onFocus"
    @clear="onClear"
  >
    <el-option
      v-for="(item, index) in list"
      :key="item.id"
      :label="item[title]"
      :value="index"
    />
  </el-select>
</template>
<script>
import { getProduct, getProductPage } from '@/api/data'

export default {
  props: {
    productType: [String, Number],
    value: [String, Number],
    disabled: Boolean,
    title: {
      type: String,
      default: 'titleZh'
    }
  },
  data() {
    return {
      index: null,
      list: [],
      loading: false
    }
  },
  watch: {
    index(val) {
      const productId = val !== '' && val !== null ? this.list[val].id : null
      this.$emit('input', productId)
      this.$emit('change', val !== '' && val !== null ? this.list[val] : null)
      // 0 != ''  是 false
    },
    value() {
      this.init()
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      if (!this.value) {
        this.index = null
        return
      }
      const index = this.list.findIndex(item => item.id == this.value)
      console.log(index)
      if (index < 0) {
        getProduct(this.value).then(res => {
          this.list.unshift(res.data)
          this.index = 0
        })
      } else this.index = index
    },
    onFocus() {
      if (!this.list.length) {
        this.remoteMethod()
      }
      // this.remoteMethod()
    },
    onClear() {
      this.list = []
    },
    remoteMethod(keyword) {
      const params = {
        pageSize: keyword ? 100000 : 10
      }
      if (this.productType) {
        params.typeId = this.productType
      }
      params.titleZh = keyword
      this.loading = true
      getProductPage(params)
        .then(res => this.list = res.data.list)
        .finally(() => this.loading = false)
    }
  }
}
</script>