<template>
  <div :class="$style.xmselinput">
    <a-input v-model="defaultValue" v-bind="$attrs" @blur="setinputvalue" />
    <a-button type="primary" @click="selectUser">选择</a-button>
  </div>
</template>

<script>
import pickValues from '@/common/services/pick-values'
import sdUserPicker from '@/common/components/sd-user-picker.vue'
import components from './_import-components/xm-inputselectuser-render-import'

export default {
  name: 'XmInputselectuserRender',
  metaInfo: {
    title: 'XmInputselectuserRender',
  },
  components,
  props: {
    userIdField: {
      type: String,
      default: '',
    },
    userAccountField: {
      type: String,
      default: '',
    },
    userNameField: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      defaultValue: '',
    }
  },
  inject: {
    SdFormContext: { default: () => {} },
  },
  mounted() {
    const name = this.SdFormContext.getFieldValue(this.userNameField)
    if (name) {
      this.defaultValue = name
    }
  },
  methods: {
    selectUser() {
      pickValues(
        sdUserPicker, // 第一个参数：使用的选择器组件
        // 第二个参数：传递给选择器的props。默认选中的值、是否单选等，都可以传递
        {
          single: false,
        }
      )
        // 用户选择完成后，promise返回选中的值。用户取消返回undefined
        .then((values) => {
          let ids = '' // 人员id
          let accounts = '' // 人员account
          let names = '' // 人员name
          values?.forEach((item) => {
            // 人员id
            if (ids === '') {
              ids = item.code
            } else {
              ids = ids + ',' + item.code
            }
            // 人员account
            if (accounts === '') {
              accounts = item.code
            } else {
              accounts = accounts + ',' + item.code
            }
            // 人员name
            if (names === '') {
              names = item.name
            } else {
              names = names + ',' + item.name
            }
          })
          this.SdFormContext.setFieldValue(this.userIdField, ids)
          this.SdFormContext.setFieldValue(this.userAccountField, accounts)
          this.SdFormContext.setFieldValue(this.userNameField, names)
          this.defaultValue = names
          this.$emit('input', names)
        })
    },
    setinputvalue(val) {
      if (this.defaultValue) {
        this.SdFormContext.setFieldValue(this.userIdField, '')
        this.SdFormContext.setFieldValue(this.userAccountField, '')
        this.SdFormContext.setFieldValue(this.userNameField, this.defaultValue)
        this.$emit('input', this.defaultValue)
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.xmselinput {
  :global .ant-input {
    width: 70%;
    margin-right: 10px;
  }
  :global .ant-btn {
    width: auto;
    padding: 0 10px;
  }
}
</style>
