<!-- 产品名称 -->
<template>
  <div>
    <base-select v-model="currentValue"
                 :clearable="clearable"
                 :filterable="filterable"
                 :multiple="multiple"
                 :api="api"
                 :options.sync="options"
                 :queryParas="queryParas"
                 :selectedField="selectedField"
                 :reload="reload"
                 :loadList="loadList"
                 @loaded="loaded"
                 @select-changed="selectChanged"
                 v-bind="$attrs"
                 v-on="$listeners">
    </base-select>
  </div>
</template>

<script>
import componentsApi from '@/api/componentsApi'
import components from 'newepoch-components'

export default {
  name: 'SelectProductName',
  inheritAttrs: false,
  components: {
    BaseSelect: components.BaseSelect
  },
  props: {
    // v-model绑定的数据
    value: {
      type: [Array, String],
      default: function () {
        return null
      }
    },
    // 是否可多选
    multiple: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    // 重新加载数据（每次取非即可）
    reload: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    // 是否可搜索
    filterable: {
      type: Boolean,
      default: function () {
        return true
      }
    },
    // 是否可清除
    clearable: {
      type: Boolean,
      default: function () {
        return true
      }
    },
    // 列表查询调用的api字符串
    loadList: {
      type: String,
      default: function () {
        return 'getDefault'
      }
    },
    name: {
      type: String,
      require: false
    },
    tagCode: {
      type: String,
      default: function () {
        return '2'
      }
    }
  },
  data () {
    return {
      // 下拉列表数据
      options: [],
      selectedField: ['keyId', 'projectName'],
      queryParas: {
        productType: this.tagCode
      }
    }
  },
  // 创建后自动加载数据
  created () {
  },
  computed: {
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        return this.value
      },
      set: function (value) {
        this.$emit('input', value)
      }
    },
    api () {
      return componentsApi.productInfoCascade
    }
  },
  methods: {
    selectChanged (val, row) {
      this.$emit('selectChanged', val, this.name, row)
    },
    loaded (val) {
      let $this = this
      let selectItems = null
      const keyId = $this.selectedField[0]
      const { currentValue } = this
      if (val.length > 0) {
        if (!this.multiple) {
          selectItems = val.find(it => currentValue === it[keyId])
        } else {
          selectItems = val.filter(it => currentValue.includes(it[keyId]))
        }
        this.$emit('selectChanged', '', this.name, selectItems)
      }
    }
  },
  watch: {
  }
}
</script>
