<template>
  <view class="page-contact">
    <template v-if="contacts.length">
      <view class="c-item" v-for="(item, index) in list" :key="index" @click="handleClick(item)">
        <view class="c-name">{{ item.displayName }}</view>
        <view class="c-mobile">{{item.mobile}}</view>
      </view>
    </template>
  </view>
</template>

<script>
export default {
  name: 'Contact',
  data() {
    return {
      eventChannel: null,
      contacts: [],
      list: [],
    }
  },
  onLoad() {
    this.eventChannel = this.getOpenerEventChannel()
    this.init()
  },
  onShow() {
    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
    this.init()
  },
  methods: {
    init() {
      console.log('进来了')
      const that = this
      try {
        uni.getStorage({
          key: 'm-contact',
          success: function (res) {
            try {
              let data = JSON.parse(res.data)
			  //数据为空的情况
			  data = data.filter(item=>item.phoneNumbers.length>0)

              data.forEach((item) => {
                const { phoneNumbers } = item
                const displayName = item.displayName
                item.firstName = displayName.substring(0, 1)
                let mobile = phoneNumbers[0]['value']
                mobile = mobile.replace(/\s+/g, '')
                item.mobile = mobile
              })
              that.list = data
              that.contacts = data
              uni.hideLoading()
            } catch (err) {
              console.log(err, '处理数据错了')
              uni.hideLoading()
            }
          },
          fail: function (err) {
            console.log(err, '报错了')
          },
          complete: function () {
          },
        })
      } catch (err) {
        console.log(err, '获取通讯录报错')
      }
    },
    handleClick(item) {
      const { displayName, mobile } = item
      const result = {
        linkerName: displayName,
        linkerMobile: mobile,
      }
      this.eventChannel.emit('send', JSON.stringify(result))
      uni.navigateBack()
    },
  },
}
</script>

<style lang="less">
.page-contact {
  height: 100vh;
  width: 100vw;
  box-sizing: border-box;
  padding: 0 30rpx 50rpx;

  .c-item {
    width: 100%;
    height: 80rpx;
    border-bottom: 1rpx solid #dddddd;
    font-size: 28rpx;
    display: flex;
    align-items: center;

    &:last-child {
      border-bottom: none;
    }
  }
}
</style>