<template>
  <el-select filterable v-model="_customerId" remote :remote-method="remoteSearchCustomer" :style="style" :loading="customerLoading" placeholder="请选择客户">
    <el-option v-for="item in customerList" :key="item[bindField]" :label="item.companyName" :value="item[bindField]" />
  </el-select>
</template>

<script>
  import { listCustomer } from '@/api/crm/customer';

  export default {
    name: 'CustomerSelect',
    props: {
      value: {
        type: String,
        default: ''
      },
      bindField: {
        type: String,
        default: 'customerId'
      },
      style: {
        type: Object,
        default: () => ({})
      }
    },
    computed: {
      _customerId: {
        get() {
          return this.value;
        },
        set(value) {
          this.$emit('input', value);
          // 找到对应的客户信息
          const customer = this.customerList.find(item => item[this.bindField] === value);
          // 触发 change 事件，传递客户信息
          if (customer) {
            this.$emit('change', customer);
          }
        }
      }
    },
    data() {
      return {
        customerList: [],
        customerLoading: false
      }
    },
    mounted() {
      this.remoteSearchCustomer('');
    },
    methods: {
      remoteSearchCustomer(query) {
        this.customerLoading = true;
        listCustomer({ companyName: query, pageNum: 1, pageSize: 10 }).then(response => {
          this.customerList = response.rows;
        }).finally(() => {
          this.customerLoading = false;
        });
      }
    }
  }
</script>