<template>
  <el-popover
    v-model="showList"
    placement="top-start"
    width="400"
    :disabled="readonly"
    trigger="click">
      <VehicleList ref="list" :firstLoadAble="showList" :custId="custId" :multiple="multiple" :height="380" :pageSize="6" @change="handleCustChange"></VehicleList>
      <el-button v-if="multiple" class="list-confirm" type="primary" size="mini" @click="handleConfirm">确定</el-button>
      <slot slot="reference">
        <el-input v-if="type === 'input'" :style="{width: width}" v-model="inputVal" :placeholder="placeholder" :readonly="readonly" clearable @input="inputChange" @clear="inputChange('')"></el-input>
        <MySelectButton v-else :style="{width: width}" :value="label" :placeholder="placeholder" :readonly="readonly" @change="clear"></MySelectButton>
      </slot>
  </el-popover>
</template>

<script>
import VehicleList from '@/views/tm/components/VehicleList';
export default {
  name: 'VehicleInput',
  components: {
    VehicleList,
  },
  props: {
    type: {
      type: String,
      default: 'select',
    },
    // 值
    value: {
      type: String | Number,
      default: null,
    },
    // 显示的名称
    label: {
      type: String,
      default: null,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '请选择车辆',
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    width: null,
    custId: {
      type: [String, Number],
      default: null
    },
  },
  data() {
    return {
      showList: false,
      inputVal: '',
      selection: [],
    }
  },
  watch: {
    value: {
      handler(val) {
        this.inputVal = val;
      },
      immediate: true,
    }
  },
  methods: {
    inputChange(val) {
      this.$emit('change', [{
        driverId: '',
        driverName: val,
      }]);
      if (!val) {
        this.$refs.list.clearSelection();
      }
    },
    clear() {
      this.$emit('change', '');
      this.$refs.list.clearSelection();
    },
    handleCustChange(custs) {
      this.selection = custs || [];
      if (!this.multiple) {
        this.showList = false;
      }
      this.$emit('change', custs);
    },
    handleConfirm() {
      this.showList = false;
      this.$emit('confirm', this.selection || []);
    }
  }
}
</script>

<style scoped>
  .list-confirm {
    position: absolute;
    bottom: 13px;
    right: 10px;
  }
</style>