<template>
  <el-select @change="$emit('input',customer)" v-model="customer" filterable remote
             :remote-method="getCustomerSelectFn" :placeholder="$t('请选择客户名称')">
    <el-option v-for="item in getCustomerList" :label="item.name" :value="Number(item.id)" :key="item.id"></el-option>
  </el-select>
</template>

<script>
import {getCustomerList, getCustomerSelect} from "@/api/ecw/customer";

export default {
  props:{
   value:{
     type:Number,
     default:undefined,
   },
  },
  name: "customerSelect",
  mounted() {
    this.getCustomerSelectFn();
    this.$nextTick(()=>{
      this.customer = this.value;
      if(!(this.customerList.some(i => i.id === this.value)) && this.value !== undefined){
        getCustomerList({ids:this.value}).then(r => {
          this.recommended = r.data;
        })
      }
    })
  },
  computed:{
    getCustomerList(){
      let index = this.customerList.findIndex(item => item.id === this.recommended[0]?.id)
       if(index > -1) return this.customerList
        else return [...this.customerList,...this.recommended]
    }
  },
  data(){
    return {
      customer:'',
      customerList:[],
      recommended:[],
    }
  },
  methods:{
    getCustomerSelectFn(val){
      getCustomerSelect({pageNo:1,pageSize:100,searchKey:val}).then(r => {
        this.customerList = r.data.list;
      })
    }
  },
  watch:{
    value(val){
      this.customer = val;
      if(!(this.customerList.some(i => i.id === val)) && val !== undefined){
        getCustomerList({ids:val}).then(r => {
          this.recommended = r.data;
        })
      }
    }
  }
}
</script>

<style scoped>

</style>
