<template>
  <el-select v-model="selectValue" :remote-method="methodStaff"
             :style="{width: props.width}" :clearable="props.clearable" filterable
             remote @change="changeStaff" @clear="clear"
             ref="selectRef">
    <el-option v-for="item in staffList" :key="item.code" :label="item.name"
               :value="item.code ">
      <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
      <el-divider direction="vertical"></el-divider>
      <span style="color:#67C23A">{{ item.name }}</span>
      <el-divider direction="vertical"></el-divider>
      <span style="color:#E6A23C">{{ item.deptName }}</span>
      <el-divider direction="vertical"></el-divider>
      <span style="color:#a5673f">{{ item.empTitName }}</span>
      <el-divider direction="vertical"></el-divider>
      <span style="color:#a5673f">{{ item.ybCode }}</span>
    </el-option>
  </el-select>
</template>

<script setup>
import {getRenYuan} from "@/api/public-api";
import {stringNotBlank} from "@/utils/blank-utils";
import store from "@/store";

const props = defineProps({
  modelValue: {
    type: Object,
    default: ''
  },
  name: {
    type: Array,
    default: ['code', 'name']
  },
  width: {
    type: String,
    default: '220px'
  },
  clearable: {
    type: Boolean,
    default: true
  },
  deptCode: {
    type: Boolean,
    default: false
  }
})

const staffList = ref([])
const selectValue = ref()

const modelChange = () => {
  selectValue.value = props.modelValue[props.name[0]]
  if (stringNotBlank(selectValue.value)) {
    for (let i = 0, len = staffList.value.length; i < len; i++) {
      if (selectValue.value === staffList.value[i].code) {
        return
      }
    }
    getRenYuan(selectValue.value).then(res => {
      staffList.value = res
    })
  }
}

onMounted(() => {
  modelChange()
})


watch(() => props.modelValue[props.name[0]], () => {
  modelChange()
})

let deptCode = props.deptCode ? store.state.user.info.deptCode : ''
const methodStaff = (val) => {
  if (val.length === 0) {
    return
  }
  getRenYuan(val, deptCode).then(res => {
    staffList.value = res
  });
}

const selectRef = ref()
const changeStaff = async () => {
  await nextTick()
  props.modelValue[props.name[0]] = selectRef.value?.selected?.value
  props.modelValue[props.name[1]] = selectRef.value?.selected?.currentLabel
}

const clear = () => {
  selectValue.value = ''
  props.modelValue[props.name[0]] = ''
  props.modelValue[props.name[1]] = ''
}

</script>

<style lang="scss" scoped>

</style>
