<template>
  <el-select 
    v-model="selectValue" 
    :placeholder="placeholder"
    clearable
    filterable
    :disabled="disabled"
    :multiple="multiple"
    @change="handleChange"
    style="width: 100%;"
    @focus="handleFocus"
  >
    <div v-if="multiple" class="select-footer">
      <el-button size="mini" type="text" @click.stop="handleSelectAll">
        {{ isAllSelected ? '取消全选' : '全选' }}
      </el-button>
    </div>
    <el-option
      v-for="item in filterList"
      :key="item.userId"
      :label="item.nickName"
      :value="item.userId"
    />
  </el-select>
</template>

<script>
import { listAllUser } from "@/api/system/user";

export default {
  name: "UserSelect",
  props: {
    value: {
      type: [String, Array],
      default: null
    },
    placeholder: {
      type: String,
      default: "请选择用户"
    },
    disabled: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    // 过滤方法
    filterMethod: {
      type: Function,
      default: (data) => {
        return data;
      }
    }
  },
  data() {
    return {
      list: [],
      filterList: []
    };
  },
  computed: {
    selectValue: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      }
    },
    // 是否全选
    isAllSelected() {
      return this.multiple && this.filterList.length > 0 && Array.isArray(this.value) && this.value.length === this.filterList.length;
    }
  },
  created() {
    this.getList();
  },
  methods: {
    handleFocus() {
      this.filterList = this.filterMethod(this.list);
    },
    getList() {
      listAllUser().then(response => {
        this.list = response.data;
        this.filterList = response.data;
      });
    },
    // 全选
    handleSelectAll() {
      if (this.isAllSelected) {
        this.$emit("input", []);
      } else {
        const allUserIds = this.filterList.map(item => item.userId);
        this.$emit("input", allUserIds);
      }
    },
    handleChange(val) {
      if (this.multiple) {
        let userList = this.list.filter(item => val.includes(item.userId));
        this.$emit("change", userList);
      } else {
        let user = this.list.find(item => val === item.userId);
        this.$emit("change", user);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.select-footer {
  padding: 5px 12px;
  border-bottom: 1px solid #EBEEF5;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>