<template>
  <el-select v-model="value" :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 name="SelectStaffCode" 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
  }
})

let staffList = $ref([])

let value = $ref()

const modelChange = () => {
  value = props.modelValue[props.name[0]]
  if (stringNotBlank(value)) {
    for (let i = 0, len = staffList.length; i < len; i++) {
      if (value === staffList[i].code) {
        return
      }
    }
    getRenYuan(value).then(res => {
      staffList = 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 = 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 = () => {
  value = ''
  props.modelValue[props.name[0]] = ''
  props.modelValue[props.name[1]] = ''
}

</script>

<style lang="scss" scoped>

</style>
