<template>
  <el-dialog
    :visible="innerVisible"
    @close="handleClose"
    @open="initData"
    append-to-body
    width="650px"
    center
    title="选择用户"
  >
    <el-transfer
      v-model="selectedValues"
      :data="employees"
      :titles="['未选用户', '已选用户']"
      style="margin-bottom: 20px;"
      @change="onChange"
    ></el-transfer>
    <el-row type="flex" justify="end">
      <el-col :span="4">
        <el-button type="primary" @click="onConfirm">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
export default {
  name: 'PerEmployeeSelector',
  props:{
    showVisible: {
      type: Boolean,
      default: false
    },
    selectedEmployees:{
      type: Array,
      default: () => []
    },
    employeeStatus:{
      type: Number,
      default: null
    },
    multiple:{
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      userInfo: this.$userInfo(),
      innerVisible: this.showVisible,
      employeeList: this.$getEmployeeMap(this.employeeStatus),
      selectedValues:this.selectedTemplate,
    }
  },
  watch: {
    showVisible(val) {
      this.innerVisible = val;
    },
  },
  computed:{
    employees(){
      return this.employeeList.map(e => {
        return {
          key:Number.parseInt(e.id),
          label:e.name
        }
      })
    },
    employeeMap(){
      const map = {};
      this.employeeList.forEach(e => {
        if (!map[e.id]) map[e.id] = e;
      });
      return map;
    }
  },
  methods: {
    handleClose(){
      this.$emit('update:showVisible',false)
    },
    initData(){
      this.selectedValues = this.selectedEmployees.filter(id => Number.isFinite(id)).map(id => Number.parseInt(id));
    },
    onConfirm(){
      let res = this.selectedValues.filter(id => !!this.employeeMap[id]).map(id => {
        return {
          employeeId:Number.parseInt(this.employeeMap[id].id),
          name:this.employeeMap[id].name,
          imgUrl:this.employeeMap[id].img_url,
        }
      });
      this.$emit('confirm',res);
      this.handleClose();
    },
    onChange(values){
      if(!this.multiple && values && values.length > 0) this.selectedValues = [values[values.length - 1]];
    }
  }
}
</script>

<style scoped lang="scss">

</style>
