<template>
  <el-select
    v-model="selected"
    filterable
    remote
    reserve-keyword
    placeholder="请输入关键字"
    :remote-method="remoteMethod"
    :loading="loading"
    v-bind="$attrs"
    @change="change"
    @remove-tag="removeTag"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.code"
      :value="item.code"
      @click.native="select(item)"
    >
      <el-row :gutter="20">
        <el-col :span="12">{{ item.code }}</el-col>
        <el-col :span="12" class="text-right">{{ item.name }}</el-col>
      </el-row>
    </el-option>

  </el-select>
</template>

<script>
import { getMaterialList } from '@/api/wms/base/material'
export default {
  props: {
    value: {
      type: [String, Number, Array],
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      options: [],
      copiedOptions: [],
      codeList: [],
      selectFlag: false
    }
  },
  computed: {
    selected: {
      get() {
        return this.value
      },
      set(v) {
        this.$emit('input', v)
      }
    }
  },
  methods: {
    remoteMethod(keyWorld) {
      this.loading = true
      const params = {
        keyWorld
      }
      getMaterialList(params).then(response => {
        this.options = response.data || []
      }).finally(() => {
        this.loading = false
      })
    },
    select(v) {
      // const index = this.copiedOptions.findIndex(item => item.code === v.code)
      // if (index === -1) {
      //   this.copiedOptions.push(v)
      // } else {
      //   this.copiedOptions.splice(index, 1)
      // }
    },
    change(v) {
      const index = this.copiedOptions.findIndex(item => !(v.includes(item.code)))
      if (index > -1) {
        this.copiedOptions.splice(index, 1)
      } else {
        const codes = this.copiedOptions.map(item => {
          const { code } = item
          return code
        })
        const rightCodes = v.filter(item => !(codes.includes(item)))
        const addList = this.options.filter(item => rightCodes.includes(item.code))
        this.copiedOptions.push(...addList)
      }

      const isArr = Object.prototype.toString.call(v) === '[object Array]'
      if (isArr) {
        this.$emit('change', this.copiedOptions, v)
      } else {
        const item = this.options.find(i => i.code === v)
        this.$emit('change', item)
      }
    },
    removeTag(v) {
      const index = this.copiedOptions.findIndex(item => item.code === v)
      if (index > -1) {
        this.copiedOptions.splice(index, 1)
      }
    }
  }
}
</script>

  <style>

  </style>

