<template>
  <el-select
    :value="value"
    filterable
    remote
    clearable
    reserve-keyword
    :placeholder="placeholder"
    :remote-method="searchProducts"
    :loading="loading"
    :style="selectStyle"
    @input="$emit('input', $event)"
    @change="handleChange"
    @clear="handleClear"
  >
    <el-option
      v-for="item in options"
      :key="item.productId"
      :label="item.productName"
      :value="item.productId"
    >
      <span>{{ item.productName }}</span>
      <span style="color: #999; margin-left: 8px">ID:{{ item.productId }}</span>
    </el-option>
  </el-select>
</template>

<script>
import debounce from 'lodash/debounce'

export default {
  name: 'ProductRemoteSelect',
  props: {
    value: {
      type: [Number, String],
      default: ''
    },
    merchantId: {
      type: [Number, String],
      default: '1'
    },
    goodsType: {
      type: String,
      default: '00'
    },
    placeholder: {
      type: String,
      default: '请输入商品名称检索'
    },
    selectStyle: {
      type: String,
      default: 'width: 240px'
    }
  },
  data() {
    return {
      loading: false,
      options: []
    }
  },
  watch: {
    merchantId() {
      this.resetSelection()
    },
    goodsType() {
      this.resetSelection()
    }
  },
  created() {
    this.debouncedSearch = debounce(this.fetchProducts, 300)
  },
  beforeDestroy() {
    if (this.debouncedSearch && this.debouncedSearch.cancel) {
      this.debouncedSearch.cancel()
    }
  },
  methods: {
    clear() {
      if (this.debouncedSearch && this.debouncedSearch.cancel) {
        this.debouncedSearch.cancel()
      }
      this.options = []
      this.loading = false
    },
    resetSelection() {
      this.options = []
      this.$emit('input', '')
      this.$emit('change', null)
    },
    searchProducts(query) {
      if (!query) {
        this.options = []
        return
      }
      this.debouncedSearch(query)
    },
    fetchProducts(query) {
      this.loading = true
      const params = {
        current: 1,
        limit: 20,
        goodsType: this.goodsType
      }
      if (query) {
        params.productName = query
      }
      this.$http({
        url: this.$http.adornUrl('/master/shopProduct/listByPage'),
        method: 'post',
        data: this.$http.adornData(params)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.options = data.result.records || []
        } else {
          this.options = []
        }
        this.loading = false
      }).catch(() => {
        this.options = []
        this.loading = false
      })
    },
    handleChange(productId) {
      const product = this.options.find(item => item.productId === productId) || null
      this.$emit('change', product)
    },
    handleClear() {
      this.options = []
      this.$emit('change', null)
    }
  }
}
</script>
