<template>
  <view class="container">
    <!-- 搜索区域 -->
    <view class="search-container">
      <view class="search-input-wrapper">
        <uni-icons class="search-icon" type="search" size="20" color="#999"></uni-icons>
        <input 
          class="search-input" 
          placeholder="请输入关键字进行搜索" 
          placeholder-class="placeholder"
          v-model="searchText"
          @input="handleSearchInput"
        />
        <view v-if="searchText" class="clear-icon" @tap="clearSearch">
          <uni-icons type="clear" size="18" color="#999"></uni-icons>
        </view>
      </view>
      <button class="search-btn" @tap="handleSearch">搜索</button>
    </view>

    <!-- 小区列表 -->
    <scroll-view 
      class="community-list" 
      scroll-y
      :scroll-into-view="scrollIntoViewId"
      @scrolltolower="loadMoreData"
      :lower-threshold="100"
    >
      <view 
        v-for="item in displayedCommunities" 
        :key="item.id" 
        class="community-item"
        :id="'item-' + item.id"
        @tap="selectCommunity(item)"
      >
        <view class="community-item-left">
			<image src="/static/首页/小区.png" style="width: 60rpx;height: 60rpx;"></image>
          <!-- <uni-icons class="house-icon" type="home" size="24" color="#666"></uni-icons> -->
          <view class="community-info">
            <text class="community-name">{{ item.name }}</text>
            <!-- <text class="community-address">{{ item.address }}</text> -->
            <!-- <text class="community-id">ID: {{ item.id }}</text> -->
          </view>
        </view>
        <view v-if="selectedItem && selectedItem.id === item.id" class="selected-icon">
          <uni-icons type="checkbox-filled" size="24" color="#007AFF"></uni-icons>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="hasMoreData" class="load-more-container">
        <view v-if="!isLoading" class="load-more-btn" @tap="loadMoreData">
          <text>加载更多</text>
          <uni-icons type="arrow-down" size="16" color="#007AFF"></uni-icons>
        </view>
        <view v-else class="loading-container">
          <uni-icons type="spinner-cycle" size="20" color="#007AFF" class="loading-icon"></uni-icons>
          <text>正在加载...</text>
        </view>
        <!-- <text class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</text> -->
      </view>
      
      <!-- 没有更多数据 -->
      <view v-if="!hasMoreData && displayedCommunities.length > 0" class="no-more-data">
        <text>没有更多数据了</text>
      </view>
      
      <!-- 空状态 -->
      <view v-if="displayedCommunities.length === 0 && !isSearching" class="empty-state">
        <uni-icons type="info" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">暂无小区数据</text>
      </view>
      
      <!-- 搜索无结果 -->
      <view v-if="displayedCommunities.length === 0 && isSearching" class="empty-state">
        <uni-icons type="search" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">未找到相关小区</text>
        <text class="empty-tip">请尝试其他关键词</text>
      </view>
    </scroll-view>

    <!-- 确认按钮 -->
    <view class="confirm-area">
      <button 
        class="confirm-btn" 
        :disabled="!selectedItem"
        :class="{ 'disabled-btn': !selectedItem }"
        @tap="handleConfirm"
      >
        确认选择
      </button>
      <view v-if="selectedItem" class="selected-info">
        已选: {{ selectedItem.name }}
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {getVillageList} from "/pages/api/api.js"

// 响应式数据
const searchText = ref('')
const selectedItem = ref(null)
const scrollIntoViewId = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = 5
const totalCommunities = ref([])
const displayedCommunities = ref([])
const hasMoreData = ref(true)
const isLoading = ref(false)

// 搜索状态
const isSearching = ref(false)
let searchTimeout = null

// 所有小区数据
const allCommunities = ref([
  { id: 1, name: '北境碧桂园小区', address: '北境市光明区碧桂路1号' },
  { id: 2, name: '南湖花园小区', address: '南湖市滨湖区湖滨路28号' },
  { id: 3, name: '东城国际社区', address: '东城市新城区人民路156号' },
  { id: 4, name: '西湖雅苑', address: '西湖市风景区梅灵路88号' },
  { id: 5, name: '北境锦绣家园', address: '北境市朝阳区朝阳路56号' },
  { id: 6, name: '阳光100小区', address: '阳光市高新区创业路100号' },
  { id: 7, name: '绿城玫瑰园', address: '绿城市西湖区学院路188号' },
  { id: 8, name: '金地自在城', address: '金城市江干区金沙大道200号' },
  { id: 9, name: '万科城市花园', address: '万城市余杭区文一西路299号' },
  { id: 10, name: '保利中央公园', address: '保利市拱墅区莫干山路500号' },
  { id: 11, name: '龙湖天街小区', address: '龙湖市滨江区江南大道100号' },
])

// 计算属性
const totalPages = computed(() => {
  return Math.ceil(totalCommunities.value.length / pageSize)
})

// 方法
// 查询小区列表
const getCommunityList = () =>{
	let params = {
		keyword:searchText.value
	}
	getVillageList(params).then(res =>{
		console.log('1111',res)
		if(res.code === 200){
			allCommunities.value = res.data
			uni.showToast({
				title:"查询成功",
				icon:'success'
			})
			
		}else{
			allCommunities.value = []
			uni.showToast({
				title:"查询失败",
				icon:'error'
			})
		}
	})
}

onLoad(() =>{
	// getCommunityList()
})




// 加载分页数据
const loadPageData = (pageNum) => {
  isLoading.value = true
  
  // 模拟网络请求延迟
  setTimeout(() => {
    const startIndex = (pageNum - 1) * pageSize
    const endIndex = startIndex + pageSize
    const pageData = totalCommunities.value.slice(startIndex, endIndex)
    
    if (pageNum === 1) {
      displayedCommunities.value = pageData
    } else {
      displayedCommunities.value = [...displayedCommunities.value, ...pageData]
    }
    
    currentPage.value = pageNum
    hasMoreData.value = displayedCommunities.value.length < totalCommunities.value.length
    isLoading.value = false
    
    // 滚动到新加载的内容
    if (pageNum > 1 && pageData.length > 0) {
      setTimeout(() => {
        scrollIntoViewId.value = 'item-' + pageData[0].id
      }, 100)
    }
  }, 500)
}

// 加载更多数据
const loadMoreData = () => {
  if (isLoading.value || !hasMoreData.value) return
  loadPageData(currentPage.value + 1)
}

// 处理搜索输入
const handleSearchInput = () => {
  // 防抖处理
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  
  searchTimeout = setTimeout(() => {
    handleSearch()
  }, 300)
}

// 处理搜索
const handleSearch = () => {
  const keyword = searchText.value.trim().toLowerCase()
  
  if (!keyword) {
    isSearching.value = false
    totalCommunities.value = [...allCommunities.value]
    loadPageData(1)
    return
  }
  
  isSearching.value = true
  totalCommunities.value = allCommunities.value.filter(community => 
    community.name.toLowerCase().includes(keyword) || 
    community.address.toLowerCase().includes(keyword)
  )
  
  loadPageData(1)
}

// 清空搜索
const clearSearch = () => {
  searchText.value = ''
  isSearching.value = false
  totalCommunities.value = [...allCommunities.value]
  loadPageData(1)
}

// 选择小区
const selectCommunity = (item) => {
  selectedItem.value = item
}

// 确认选择
const handleConfirm = () => {
  if (!selectedItem.value) {
    uni.showToast({
      title: '请先选择小区',
      icon: 'none',
      duration: 2000
    })
    return
  }
  
  uni.showModal({
    title: '确认选择',
    content: `您已选择: ${selectedItem.value.name}\n地址: ${selectedItem.value.address}`,
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '选择成功',
          icon: 'success',
          duration: 1500
        })
        
        // 在实际应用中，这里可以触发回调或页面跳转
       // uni.navigateBack() 或 emit('confirm', selectedItem.value)
        uni.$emit('confirm', selectedItem.value)
        // 模拟2秒后返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    }
  })
}

// 监听搜索文本变化
watch(searchText, (newVal) => {
  if (!newVal.trim()) {
    clearSearch()
  }
})

// 初始化
onMounted(() => {
  // 初始化数据
  totalCommunities.value = [...allCommunities.value]
  loadPageData(1)
  
  // 默认选中第一项
  if (displayedCommunities.value.length > 0) {
    selectedItem.value = displayedCommunities.value[0]
  }
})
</script>

<style scoped>
/* 页面容器 */
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
   padding: 40rpx;
}

/* 搜索区域 */
.search-container {
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 10;
  position: sticky;
  top: 0;
}

.search-input-wrapper {
  flex: 1;
  background-color: #f8f8f8;
  border-radius: 10rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  height: 80rpx;
  margin-right: 20rpx;
}

.search-icon {
  margin-right: 15rpx;
}

.search-input {
  flex: 1;
  height: 100%;
  font-size: 28rpx;
  color: #333;
}

.placeholder {
  color: #999;
  font-size: 28rpx;
}

.clear-icon {
  padding: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-btn {
  background-color: #007AFF;
  color: #fff;
  font-size: 28rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 10rpx;
  padding: 0 30rpx;
  margin: 0;
  white-space: nowrap;
}

/* 小区列表 */
.community-list {
  flex: 1;
  /* padding: 0 30rpx; */
  margin-top: 20rpx;
  margin-bottom: 180rpx;
  
}

.community-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.2s;
}

.community-item:active {
  background-color: #f9f9f9;
  transform: translateY(2rpx);
}

.community-item-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.house-icon {
  margin-right: 20rpx;
}

.community-info {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.community-name {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.community-address {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 5rpx;
}

.community-id {
  font-size: 22rpx;
  color: #ccc;
}

.selected-icon {
  margin-left: 20rpx;
}

/* 加载更多容器 */
.load-more-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
  color: #999;
}

.load-more-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 40rpx;
  background-color: #f8f8f8;
  border-radius: 50rpx;
  color: #007AFF;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.load-more-btn text {
  margin-right: 10rpx;
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 40rpx;
  background-color: #f8f8f8;
  border-radius: 50rpx;
  color: #007AFF;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.loading-icon {
  margin-right: 10rpx;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.page-info {
  font-size: 24rpx;
  color: #999;
}

/* 没有更多数据 */
.no-more-data {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
  margin-top: 20rpx;
  margin-bottom: 10rpx;
}

.empty-tip {
  font-size: 24rpx;
  color: #ccc;
}

/* 确认区域 */
.confirm-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx 40rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.05);
}

.confirm-btn {
  background-color: #007AFF;
  color: #fff;
  height: 100rpx;
  line-height: 100rpx;
  border-radius: 12rpx;
  font-size: 34rpx;
  width: 100%;
  margin: 0;
}

.disabled-btn {
  background-color: #ccc;
  color: #fff;
}

.selected-info {
  text-align: center;
  font-size: 24rpx;
  color: #666;
  margin-top: 20rpx;
  padding: 10rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
}

/* 适配不同屏幕 */
@media (min-width: 768px) {
  .container {
    max-width: 500px;
    margin: 0 auto;
  }
}
</style>
