<template>
  <div>
    <el-input 
      :value="text"
      @focus="showDialog = true"
      placeholder="点击选择用户"
      :disabled="disabled"
    />

    <user-dialog 
      :show.sync="showDialog" 
      @confirm="handleConfirm" 
      :selectedIds="value"
      :multiple="multiple"
      :query="query"
      :user-type="userType"
    />
  </div>
</template>

<script>
import UserDialog from '@/components/Business/User/UserDialog.vue';
import { UserType } from '@/utils/enums';
import { isDeepEqual } from '@/utils';
export default {
  components: { UserDialog },
  props: {
    // 选中数据
    value: {
      type: [String, Array],
      default: null
    },
    // 文本
    text: {
      type: String,
      default: null,
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 查询参数
    query: {
      type: Object,
      default: () => ({})
    },
    // 用户类型
    userType: {
      type: String,
      default: UserType.USER
    }
  },
  data() {
    return {
      showDialog: false,
    }
  },
  methods: {
    handleConfirm(selection) {
      let value = null;
      let text = null;
      if (this.multiple) {
        value = selection.map(item => item.userId);
        text = selection.map(item => item.nickName).join(',');
      } else {
        value = selection?.userId;
        text = selection?.nickName;
      }
      // 如果值发生变化，则触发 change 事件
      if (!isDeepEqual(this.value, value)) {
        this.$emit('change', value);
      }
      
      this.$emit('input', value);
      this.$emit('update:text', text);
      this.$emit('confirm', selection);
      
    }
  }
}
</script>