<template>
  <view class="contact-page">
    <u-navbar class="u-navbar" title="通讯录" placeholder @leftClick="leftClick" leftIconColor="#fff"
              bgColor="#00337A" :titleStyle="{ color: '#FFF', fontSize: '32rpx' }"/>
    <!-- 搜索框 -->
    <view class="search-box">
      <view class="search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input
            type="text"
            v-model="searchText"
            placeholder="搜索"
            placeholder-class="placeholder"
        />
      </view>
      <text class="cancel-btn" @tap="onCancel">取消</text>
    </view>

    <!-- 联系人列表 -->
    <scroll-view
        class="contact-list"
        scroll-y
        :scroll-into-view="scrollIntoView"
    >
      <block v-for="letter in Object.keys(showList)" :key="letter">
        <view class="letter-title" :id="'index-'+letter">{{letter}}</view>
        <view
            class="contact-item"
            v-for="item in showList[letter]"
            :key="item.id"
            @tap="selectHandler(item)"
        >
          {{item.name}}
        </view>
      </block>
    </scroll-view>

    <!-- 字母导航 -->
    <view class="index-list">
      <text
          v-for="letter in indexList"
          :key="letter"
          class="index-item"
          @tap="scrollTo(letter)"
      >
        {{letter}}
      </text>
    </view>

    <!-- 加载提示 -->
    <view v-if="loading" class="loading">
      <uni-icons type="spinner-cycle" size="24" color="#999"></uni-icons>
      <text>加载中...</text>
    </view>
  </view>
</template>

<script>
import config from '@/config'
import { pinyin } from "@/api/convertPinyin.js"

export default {
  data() {
    return {
      searchText: '',
      indexList: [],
      txlList: {},
      loading: false,
      scrollIntoView: '',
      type: '',
      value: ''
    }
  },
  onLoad(options) {
    if (options.type) {
      this.type = decodeURIComponent(options.type)
    }
    if (options.value) {
      this.value = decodeURIComponent(options.value)
    }
    console.log('接收到的数据:', { type: this.type, value: this.value })

    // 这里可以根据接收到的 type 和 value 进行进一步的数据处理或页面逻辑
  },
  computed: {
    showList() {
      if (!this.searchText) return this.txlList

      const result = {}
      Object.keys(this.txlList).forEach(letter => {
        const filtered = this.txlList[letter].filter(item =>
            item.name.toLowerCase().includes(this.searchText.toLowerCase()) ||
            item.phone.includes(this.searchText)
        )
        if (filtered.length) {
          result[letter] = filtered
        }
      })
      return result
    }
  },
  onShow() {
    this.indexList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ#".split("")
    this.getAddressList()
  },
  methods: {
    selectHandler(item) {
      uni.makePhoneCall({
        phoneNumber: item.phone,
        success: () => {
          console.log('拨打电话成功')
        },
        fail: () => {
          console.log('拨打电话失败')
        }
      })
    },
    onCancel() {
      this.searchText = ''
    },
    scrollTo(letter) {
      this.scrollIntoView = 'index-' + letter
    },
    getAddressList() {
      this.loading = true

      let param = {
        type: this.type,
        value: this.value
      }

      uni.request({
        url: config.realAppUrl + '/offLine/selectMailContent',
        method: 'post',
        data: JSON.stringify(param),
        header: {
          'content-type': 'application/json',
          Authorization: uni.getStorageSync('realNameToken')
        },
        success: res => {
          if (res.data.code == 200) {
            console.log("res.data:",res.data)
            if (res.data.data.length>0) {
              this.txlList = this.sortContacts(res.data.data, "name")
            }else {
              uni.showToast({
                title: '暂无数据',
                icon: 'none'
              })
            }
          } else {
            uni.showToast({
              title: '获取通讯录失败',
              icon: 'none'
            })
          }
          this.loading = false
        },
        fail: () => {
          uni.showToast({
            title: '获取通讯录失败',
            icon: 'none'
          })
          this.loading = false
        }
      })
    },
    sortContacts(arrList, char = "name") {
      if (!String.prototype.localeCompare) return null
      const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ#".split("")
      const result = {}

      // 初始化所有字母分组
      letters.forEach(letter => {
        result[letter] = []
      })

      // 对数据进行分组
      arrList.forEach((item, index) => {
        const initial = item[char].trim().charAt(0)
        const firstLetter = pinyin.getFullChars(initial).charAt(0).toUpperCase()

        item.id = index
        if (letters.includes(firstLetter)) {
          result[firstLetter].push(item)
        } else {
          result['#'].push(item)
        }
      })

      // 删除空数组
      Object.keys(result).forEach(key => {
        if (result[key].length === 0) {
          delete result[key]
        }
      })

      return result
    },
    // 返回
    leftClick() {
      console.log('返回')
      uni.navigateBack({
        delta: 1 // 返回
      });
    },
  }
}
</script>

<style lang="scss">
.contact-page {
  min-height: 100vh;
  background-color: #fff;
  position: relative;

  .search-box {
    padding: 10px 15px;
    background-color: #fff;
    display: flex;
    align-items: center;
    position: sticky;
    top: 0;
    z-index: 100;

    .search-input {
      flex: 1;
      height: 36px;
      background: #f5f5f5;
      border-radius: 18px;
      display: flex;
      align-items: center;
      padding: 0 12px;

      input {
        flex: 1;
        margin-left: 8px;
        font-size: 14px;
      }

      .placeholder {
        color: #999;
      }
    }

    .cancel-btn {
      padding-left: 15px;
      font-size: 14px;
      color: #007AFF;
    }
  }

  .contact-list {
    height: calc(100vh - 56px);

    .letter-title {
      padding: 4px 15px;
      background-color: #f5f5f5;
      color: #666;
      font-size: 14px;
    }

    .contact-item {
      padding: 12px 15px;
      border-bottom: 1px solid #f5f5f5;
      font-size: 16px;
      color: #333;
    }
  }

  .index-list {
    position: fixed;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    padding: 10px 4px;
    background-color: transparent;
    display: flex;
    flex-direction: column;

    .index-item {
      padding: 2px 4px;
      font-size: 12px;
      color: #007AFF;
    }
  }
}
</style>