<template>
  <div>
    <el-input :value="multiple ? (realValue.length > 0 ? `(${realValue.length})${showValue}` : null): showValue"
              @focus="openDialog"
              :size="size"
              readonly
              :placeholder="placeholder"></el-input>

    <sm-user-dialog :show.sync="dialogShow"
                       :search="search"
                       :multiple="multiple"
                       :init-select="realValue"
                       @select="onSubmit"
                       :title="title"></sm-user-dialog>
  </div>
</template>

<script>

import SmUserDialog from "@/components/Business/SmUser/smUserDialog.vue";

export default {
  name: 'smUserSelect',
  components: {SmUserDialog},
  props:{
    size: {
      type: String,
      default: "medium"
    },
    placeholder: {
      type: String,
      default: "点击选择用户",
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 双向绑定的值(为id)
    value: {
      type: [Array, String, Number],
      default: () => {
        return []
      }
    },
    // 查询条件
    search: {
      type: Object,
      default: () => ({})
    },
    // 标题
    title: {
      type: String,
      default: "选择用户"
    },
    beforeOpen: {
      type: Function,
      default: () => {
        return true;
      }
    },
    beforeClose: {
      type: Function,
      default: () => {
        return true;
      }
    },
    // 展示值
    showValue: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      realValue: [],  // 真实的值
      dialogShow: false,  // 展示对话框
    }
  },
  methods: {
    // 修改值
    inputValue(val){
      this.$emit('input', val);
    },
    // 确定
    onSubmit(selected){
      if (this.multiple) {
        this.realValue = selected;
        this.inputValue(selected.map(item => item.userId));
      } else {
        this.realValue = [selected];
        this.inputValue(selected.userId);
      }
      this.$emit('submit', selected);
      this.closeDialog();
    },
    closeDialog() {
      if (this.beforeClose()) {
        this.dialogShow = false;
      }
    },
    // 打开对话框
    openDialog(){
      if (this.beforeOpen()) {
        this.dialogShow =  true;
      }
    }
  }
}
</script>
