<template>
  <div style="max-width: 350px">
    <div v-if="mode === 'DESIGN'">
      <a-button type="primary" size="small" shape="round" disabled>选择人员</a-button>
      <span class="placeholder">{{ placeholder }}</span>
    </div>
    <div v-else>
      <template v-if="!readerMode">
        <a-button
          type="primary"
          size="small"
          shape="round"
          @click="orgPickerRef && orgPickerRef.show()"
        >
          选择人员
        </a-button>
        <OrgPicker
          ref="orgPickerRef"
          :title="pickerTitle"
          :multiple="true"
          :type="orgPickerType"
          :selected="orgPickerSelected"
          @confirm="handleSelect"
        />
        <span class="placeholder">{{ placeholder }}</span>
        <div style="margin-top: 5px">
          <a-tag
            v-for="(dept, i) in innerValue"
            :key="i"
            size="small"
            closable
            @close="delDept(i)"
            style="margin: 5px"
          >
            {{ dept.name }}
          </a-tag>
        </div>
      </template>
      <template v-else>
        <div>
          <a-tag
            v-for="(dept, i) in innerValue"
            :key="i"
            size="small"
            style="margin: 5px"
          >
            {{ dept.name }}
          </a-tag>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import OrgPicker from '@comp/OrgPicker/OrgPicker.vue';

export default {
  name: 'UserPicker',
  components: {
    OrgPicker,
  },
  props: {
    mode: {
      type: String,
      default: 'DESIGN',
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '请选择人员',
    },
    readerMode: {
      type: Boolean,
      default: false,
    },
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      innerValue: this.value.slice(),
      orgPickerType: 'user',
      orgPickerRef: null,
      orgPickerSelected: [],
    };
  },
  computed: {
    pickerTitle() {
      switch (this.orgPickerType) {
        case 'user':
          return '请选择人员';
        case 'role':
          return '请选择系统角色';
        default:
          return '-';
      }
    },
  },
  watch: {
    value(val) {
      this.innerValue = val.slice();
    },
    innerValue(val) {
      this.$emit('update:value', val);
    },
  },
  methods: {
    delDept(index) {
      this.innerValue.splice(index, 1);
    },
    handleSelect(values) {
      this.innerValue = values;
    },
  },
  mounted() {
    this.orgPickerRef = this.$refs.orgPickerRef;
  },
};
</script>

<style scoped>
.placeholder {
  margin-left: 10px;
  color: #adabab;
  font-size: 12px;
}
.a-button {
  padding: 0 20px;
  font-size: 12px;
  color: #ffffff;
}
</style>
