<template>
  <view id="contact" class="page">
    <!-- 顶部搜索栏 -->
    <l-banner v-model="searchText" :placeholder="placeholder" type="search" noSearchButton fill fixed />

    <!-- 树形列表 -->
    <l-organize-tree v-if="type && !searchText" @buttonClick="itemClick" :level="type" :root="root" button />
    <!-- 如果用户输入了搜索关键字，只列出用户 -->
    <view v-else-if="type" class="user-item-list">
      <l-organize-single-item v-for="item of searchList" @buttonClick="itemClick" :key="item.id" :item="item" button />
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      type: null,
      contactList: [],
      searchText: '',
      placeholder: '搜索学校名/部门名/职员姓名',
      root: { type: 'company', id: '0' }
    }
  },

  onBackPress() {
    this.OFF('select-organize')
  },

  onUnload() {
    this.OFF('select-organize')
  },

  async onLoad({ type, rootId, rootType }) {
    await this.init(type, rootId, rootType)
  },

  methods: {
    // 加载页面
    async init(type, rootId, rootType) {
      this.placeholder = {
        user: '搜索职员姓名',
        department: '搜索学校名/部门名',
        company: '搜索学校名/部门名/职员姓名'
      }[type]

      if (rootId && rootId !== 'undefined' && rootId !== 'null') {
        this.root = { id: rootId, type: rootType }
      }
      this.type = type || 'user'

      const selectType = { user: '职员', department: '部门', company: '学校' }[type]
      this.SET_TITLE(`请选择一个${selectType}`)
    },

    // 某一项被点击，触发事件
    itemClick(item) {
      this.EMIT('select-organize', item)
      this.NAV_BACK()
    }
  },

  computed: {
    // 用户输入关键字搜索时的列表
    searchList() {
      if (!this.searchText) {
        return []
      }

      return Object.entries(this.GET_GLOBAL(this.type))
        .filter(([id, item]) => item.name.includes(this.searchText))
        .map(([id, item]) => ({
          ...item,
          type: this.type,
          id
        }))
    }
  }
}
</script>

<style>
page {
  padding-top: 100rpx;
}
</style>
