<template>
  <Page name="select-contact">
    <template #header>
      <u-search v-model="query" placeholder="请输入搜索关键词" :show-action="false" @change="onSearch" />
    </template>
    <template #content>
      <template v-if="list.length > 0">
        <template v-for="(item, index) in list">
          <u-cell :key="index" :title="item.name || ' '" :value="item.mobile" is-link @click="onSelect(item)">
            <template #icon>
              <view class="contact-avatar">{{ item.name | firstLetter }}</view>
            </template>
          </u-cell>
        </template>
      </template>
      <template v-else>
        <u-empty text="暂无数据" />
      </template>
    </template>
  </Page>
</template>

<script>
import debounce from '@/utils/debounce';

export default {
  data() {
    return {
      query: '',
      list: [],
    };
  },
  filters: {
    firstLetter(value) {
      return `${value || ''}`.substring(0, 1);
    },
  },
  onLoad() {
    this.loadData();
  },
  methods: {
    onSearch(query) {
      debounce(() => this.loadData(query), 500);
    },
    loadData(query) {
      uni.$u.api.contact.select({ query }).then(response => {
        this.list = response.result || [];
      });
    },
    onSelect(item) {
      uni.$emit('select-contact', item);
      uni.navigateBack();
    },
  },
}
</script>

<style lang="scss">
.page-select-contact {
  box-sizing: border-box;
  box-sizing: border-box;
  &__content {
    .u-cell {
      background-color: $color-white;
      &__title {
        color: $color-text;
      }
      &__value {
        color: $color-text-minor;
        font-size: $font-md;
      }
    }
    .contact-avatar {
      background-color: rgba($color-primary, 0.8);
      color: $color-white;
      height: $padding-lg * 1.5;
      min-width: $padding-lg * 1.5;
      width: $padding-lg * 1.5;
      border-radius: 50%;
      line-height: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: $padding-md;
    }
  }
}
</style>