<template>
  <view>
    <template v-if="list.length">
      <u-list>
        <!-- 表头 -->
        <u-list-item class="table-header">
          <view class="table-row bg-gray-light no-wrap">
            <view class="table-cell header-cell name-cell">小区名称</view>
            <view class="table-cell header-cell">联系电话</view>
            <view class="table-cell header-cell">服务等级</view>
            <view class="table-cell header-cell">物业费单价</view>
          </view>
        </u-list-item>
        <!-- 列表项 -->
        <u-list-item v-for="(item, index) in list" :key="index">
          <view class="table-row" @click="goToDetail(item)">
            <view class="table-cell name-cell">{{ item.name }}</view>
           <view class="table-cell">{{ item.tel || '暂无' }}</view>
            <view class="table-cell">{{ ['一级', '二级', '三级', '四级', '五级'][item.level] || '暂无' }}</view>
            <view class="table-cell">{{ item.feeItem ? item.feeItem + '元/㎡' : '暂无' }}</view>
          </view>
        </u-list-item>
      </u-list>
    </template>
    <u-empty v-else text="暂无小区信息"/>
    <custom-tabbar :current="1"/>
  </view>
</template>

<script>
import CustomTabbar from "@/components/customTabbar.vue";
import {communityListReq} from "@/api/common";

export default {
  name: "CommunityIndex",
  components: {CustomTabbar},
  data() {
    return {
      list: []
    }
  },
  methods: {
    async getList() {
      try {
        const {data} = await communityListReq()
        this.list = data
      } catch (error) {
        console.error('获取小区列表失败:', error)
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        })
      }
    },
    goToDetail(item) {
      console.log('点击详情，item:', item)
      // 检查item和item.id是否存在
      if (!item || !item.id) {
        console.error('缺少小区ID，无法跳转到详情页')
        uni.showToast({
          title: '数据异常，无法查看详情',
          icon: 'none'
        })
        return
      }

      // 跳转到详情页，传递小区ID
      uni.navigateTo({
        url: `/pages/community/detail?id=${item.id}`,
        success: () => {
          console.log('成功跳转到详情页')
        },
        fail: (err) => {
          console.error('跳转详情页失败:', err)
          uni.showToast({
            title: '跳转失败，请重试',
            icon: 'none'
          })
        }
      })
    }
  },
  onLoad() {
    this.getList()
  }
}
</script>

<style scoped>
.table-header {
  background-color: #f5f5f5;
  font-weight: bold;
}

.table-row {
  display: flex;
  flex-direction: row;
  width: 100%;
  padding: 10px 0;
}

.table-cell {
  flex: 1;
  text-align: center;
  padding: 5px;
  font-size: 14px;
}

.name-cell {
  flex: 2; /* 小区名称列宽度是其他列的两倍 */
  text-align: left;
  padding-left: 15px;
}

.header-cell {
  color: #333;
}
.no-wrap{
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

</style>
