<template>
  <view class="wk-field wk-field-user" @click.stop="handleChooseUser">
    <view v-if="_label" class="wk-field__label">
      <view v-if="field.isNull === 1" class="line" />
      {{ _label }}
    </view>
    <view class="wk-field__body">
      <view class="wk-field__body-core">
        <template v-if="isAvatar && formValue.length > 0">
          <wk-avatar
            v-for="(user, index) in formValue"
            :key="index"
            :avatar="user.img"
            :name="user.realname"
            :size="12"
            class="avatar" />
        </template>
        <template v-else>
          {{ valueStr }}
        </template>
      </view>

      <text class="wk wk-arrow-right icon-right" />
    </view>
  </view>
</template>

<script>
  import mixins from './mixins'
  import { isArray } from '@/utils/types.js'

  export default {
    name: 'WkFieldUser',
    mixins: [mixins],
    props: {
      isAvatar: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        guid: null,
        formValue: []
      }
    },
    computed: {
      valueStr() {
        const arr = this.formValue || []
        return arr.map(o => o.realname).join(',')
      }
    },
    watch: {
      value: {
        handler(val) {
          if (
            !isArray(this.value) &&
            !this.$isEmpty(this.value)
          ) {
            this.formValue = [this.value]
          } else {
            this.formValue = this.value
          }
        },
        deep: true,
        immediate: true
      },
    },
    created() {
      this.guid = this.$guid()
    },
    methods: {
      handleChooseUser() {
        if (this.field.disabled) {
          if (this.config && this.config.disabledMsg) {
            this.$toast(this.config.disabledMsg)
          }
          return
        }
        const bridge = getApp().globalData.selectedValBridge
        bridge.user = {
          guid: this.guid,
          title: '选择' + this.field.name,
          defaultVal: this.formValue || []
        }
        if (this.field.formType === 'single_user') {
          bridge.user.maxlength = 1
        }
        uni.$on('selected-user', this.selectedUser)
        this.$Router.navigateTo('/pages_common/selectList/user')
      },
      /**
       * 选中员工
       * @param {Object} data
       */
      selectedUser(data) {
        if (this.guid === data.guid) {
          this.formValue = data.data
          this.$emit('input', this.formValue)
          this.$emit('change', {
            index: this.index,
            field: this.field,
            value: this.formValue
          })
        }
        uni.$off('selected-user')
      }
    }
  }
</script>

<style scoped lang="scss">
	@import './wkField.scss';
	.wk-field-user {

		.avatar {
			width: 58rpx;
			height: 58rpx;
			margin: 5rpx;
		}
	}
</style>
