<template>
  <div id="userInput" class="ta-user-input">
    <ta-auto-complete
      placeholder="请选择人员"
      option-label-prop="text"
      :value="autoValue"
      :filter-option="filterOption"
      @select="onSelect"
      @search="handleSearch"
      class="ta-user-input-complete"
    >
      <template slot="dataSource">
        <ta-select-option key="title" disabled>
          姓名<ta-divider type="vertical" />账号
        </ta-select-option>
        <ta-select-option v-for="user in userDataSource" :key="user.userId" :text="user.name">
          {{ user.name }}<ta-divider type="vertical" />{{ user.loginId }}
        </ta-select-option>
        <ta-select-option key="all" disabled>
          <a @click="handleToShowSelect">
            更多查询
          </a>
        </ta-select-option>
      </template>
      <ta-input @blur="handleBlurInput" />
    </ta-auto-complete>
    <ta-icon type="user" class="pos-show-select" @click="handleToShowSelect" />

    <ta-user-select
      id="userSelect"
      :title="selectTitle"
      width="800px"
      :is-show="isUserShow"
      :load="orgLoadFn"
      :pagination="true"
      :user-list-data="userListData"
      :props="selectUserProps"
      :is-multi="false"
      @queryUserList="handleQueryUserList"
      @getUserListResult="handleGetUserListResult"
      @close="handleHideUserSelect"
    />
  </div>
</template>
<script>
export default {
  name: 'TaUserInput',
  props: {
    value: {
      type: String,
    },
    selectTitle: {
      type: String,
      default: '人员选择',
    },
    orgLoadFn: {
      type: Function,
    },
    userLoadFn: {
      type: Function,
    },
    userSelectCall: {
      type: Function,
    },
  },
  data () {
    return {
      userDataSource: [],
      // 显示值
      autoValuePrev: '',
      autoValue: '',
      // 当前选择
      curUserId: '',

      searchValuePrev: '', // 记录上一次的搜索

      // 人员选择
      isUserShow: false,
      userListData: [],
      selectUserProps: {
        treeNodeKey: 'value', // 每个树节点用来作为唯一标识的属性，整棵树应该是唯一的
        treeLabel: 'label', // 树节点的属性名称
        treeChildren: 'children', // 树子节点对象的属性名称
        listKey: 'userId', // 每条用户信息的唯一标识（默认：userId）
        listTitle: 'name', // 用户信息第一行显示内容
        listSubTitle: 'mobile', // 用户信息第二行显示内容
        listDescription: 'namePath', // 用户信息鼠标移上去显示描述信息
      },
      userPageSize: 5,
    }
  },
  watch: {
    value: {
      handler (val) {
        if (this.curUserId != val) {
          this.curUserId = ''
          this.autoValue = this.autoValuePrev = ''
          this.loadUserSelectData(null, val, true)
        } else {
          if (val == null || val == undefined || val.trim() == '') {
            this.curUserId = ''
            this.autoValue = this.autoValuePrev = ''
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    loadUserSelectData (searchValue, value, isSelect) {
      const resolve = (userData) => {
        this.userDataSource = userData || []
        if (isSelect && this.userDataSource.length == 1) {
          this.curUserId = this.userDataSource[0].userId
          this.autoValue = this.autoValuePrev = this.userDataSource[0].name
          this.userSelectCall(this.userDataSource[0])
        }
      }
      this.userLoadFn({orgId: null, userId: value, includeChild: true, pageSize: 10, pageNum: 1, searchVal: searchValue}, resolve)
    },
    onSelect (value) {
      let data = this.userDataSource.find(item => item.userId == value) || {}
      this.curUserId = value
      this.autoValue = this.autoValuePrev = data.name || ''

      this.userSelectCall(data)
      this.triggerChange()
    },
    handleSearch (value) {
      this.autoValue = value
      if (value == '' || typeof value == 'undefined') {
        this.autoValuePrev = ''
        this.curUserId = ''
        this.triggerChange()
      }
      if (this.searchValuePrev != value) {
        this.searchValuePrev = value
        this.loadUserSelectData(value, null, false)
      }
    },
    handleToShowSelect () {
      this.isUserShow = true
    },
    handleHideUserSelect () {
      this.isUserShow = false
    },
    handleQueryUserList (id, includeChild, pageNum, searchType, searchParam) {
      const resolve = (userData) => {
        this.userListData = userData
      }
      let pageSize = this.userPageSize
      this.userLoadFn({orgId: id, userId: null, includeChild, pageSize, pageNum, searchType, searchParam}, resolve)
    },
    handleGetUserListResult (data) {
      let dataObj = data.length ? data[0] : []
      this.curUserId = dataObj.userId
      this.autoValue = this.autoValuePrev = dataObj.name || ''
      this.triggerChange()
      this.userSelectCall(dataObj)
    },
    handleBlurInput () {
      this.autoValue = this.autoValuePrev
    },
    triggerChange  () {
      let changeValue = this.curUserId
      this.$emit('change', changeValue)
    },
    filterOption (input, option) {
      if (!option.componentOptions.children[0].text) {
        return false
      }
      return option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
    },
  },
}
</script>

<style scoped>
  #userInput >>> .ant-input {
    padding-right: 30px;
  }
  #userInput { position: relative; }
  .pos-show-select { position: absolute; padding: 0 12px 0 4px; right: 0; top: 50%; transform: translateY(-50%); line-height: 24px; z-index: 1; cursor: pointer; }
</style>
