<template>
  <el-select :loading="selectLoading" v-model="staffSelected" clearable filterable :filter-method="changeQuery"
             @blur="$emit('input-blur', selectedStaff)" @change="handleChange">
    <el-option v-for="staff in staffList" :key="staff.id" :label="staff.name + ' ' + staff.tel" :value="staff.id"/>
  </el-select>
</template>

<script>

import {getStaffList} from "@/api/company/staff";
import {getUserProfile} from "@/api/system/user";

export default {
  name: "StaffChoose",
  props: {
    value: {
      type: Object,
    },
    isGet: {
      type: String,
      default: '',
      required: false
    },
    roleCode:{
      type: String,
    }
  },
  data() {
    return {
      staffList: [],
      staffSelected: undefined,
      hasRequest: false,
      query: null,
      selectLoading: false,
    }
  },
  computed: {
    selectedStaff() {
      const staff = this.staffList.find(item => item.id === this.staffSelected) || null;
      return staff;
    }
  },
  watch: {
    staffSelected(val) {
      const staff = this.staffList.find(item => item.id === val);
      if (staff) {
        this.$emit("input", staff);
      }
    },
    value(newVal) {
      if (newVal) {
        this.staffSelected = newVal.id
      } else {
        this.staffSelected = null
      }
    },
  },
  mounted() {
    this.listStaff()
    // 只有在需要自动获取当前用户信息时才调用 getNow()
    if (this.isGet && this.isGet !== 'false') {
      this.getNow()
    }
  },
  methods: {
    handleChange(val) {
      if (val) {
        const staff = this.staffList.find(item => item.id === val);
        if (staff) {
          this.$emit("input", staff);
          this.$emit("input-blur", staff);
        }
      } else {
        this.$emit("input", null);
        this.$emit("input-blur", null);
      }
    },
    async listStaff() {
      this.selectLoading = true
      try {
        if (!this.isGet) return;
        if (this.roleCode){
          // todo 暂时先把流程跑通了来
        }else {
          const res = await getStaffList(this.query)
          this.staffList = res.data
          if (this.query){
            const filtered = this.staffList.filter(item => item.tel === this.query);
            if (filtered.length > 0) {
              this.staffSelected = filtered[0].id
            }
            this.query = null
          }
        }
      } finally {
        this.selectLoading = false
      }
    },
    changeQuery(val) {
      this.query = val
      this.listStaff()
    },
    async getNow(){
      // 获取当前登录用户
      const res = await getUserProfile()
      this.changeQuery(res.data.mobile)
    }
  }
}
</script>

<style scoped lang="scss">

</style>