<template>
  <view class="page">
    <custom-navbar title="建制" />
    <tile-grid :tile-image="tilesImageEnum.TILE" />
    <view class="header">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      <!-- 空数据提示 -->
      <view v-else-if="institutionalData.length === 0" class="empty">
        <text>暂无数据</text>
      </view>
      <!-- 数据列表 -->
      <institutional-item 
        v-else 
        v-for="(item, index) in institutionalData" 
        :key="index"
        :item="item"
        :index="index"
        @view-detail="handleViewDetail"
      />
    </view>
	
  </view>
</template>

<script>
import { tilesImageEnum } from '@/enum/institutionalStructure.js';
import { getInstitutionalList } from '@/api/institutionalStructure.js';
import CustomNavbar from "../../components/custom-navbar/custom-navbar.vue";
import TileGrid from "../../components/tile-grid/tile-grid.vue";
import InstitutionalItem from "./components/institutional-item.vue";
import CommonEnum from "../../enum/common";

export default {
  components: {
    CustomNavbar,
    TileGrid,
    InstitutionalItem
  },
  data() {
    return {
      CommonEnum,
      bgc: {
        backgroundColor: CommonEnum.BASE_COLOR,
      },
      tilesImageEnum,
      // 动态数据数组
      institutionalData: [],
      // 加载状态
      loading: false,
      pageNum: 1,
      pageSize: 10,
      hasMore: true // 是否还有更多数据
    }
  },
  onLoad() {
    // 页面加载时获取数据
    this.getInstitutionalData()
  },
  methods: {
    // 获取建制数据
    async getInstitutionalData(isLoadMore = false) {
      this.loading = true
      try {
        if (isLoadMore) {
          this.pageNum++
        } else {
          this.pageNum = 1
        }
        
        // 调用API
        const response = await getInstitutionalList({
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
        
        if (response.code === 200) {
          // 将后端数据转换为前端需要的格式
          const newData = response.rows.map(item => ({
            topLeft: this.formatTopLeft(item.startYear, item.proName),
            topRight: this.getStatusText(item.state),
            bottomLeft: `建造金额：${this.formatAmount(item.totalAmount)}`,
            bottomRight: `捐赠人数：${item.donorCount}人`
          })) || []
          
          if (isLoadMore) {
            this.institutionalData = [...this.institutionalData, ...newData]
          } else {
            this.institutionalData = newData
          }
          
          // 判断是否还有更多数据
          this.hasMore = response.rows.length === this.pageSize
        } else {
          uni.showToast({
            title: response.msg || '获取数据失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取建制数据失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 格式化金额
    formatAmount(amount) {
      if (!amount) return '不详'
      if (amount >= 100000000) {
        return `${(amount / 100000000).toFixed(1)}亿`
      } else if (amount >= 10000) {
        return `${(amount / 10000).toFixed(1)}万`
      } else {
        return `${amount.toLocaleString()}`
      }
    },
    
    // 格式化左上角内容
    formatTopLeft(year, projectName) {
      if (!year || !projectName) return '暂无数据'
      return `${year}年 ${projectName}`
    },
    
    // 获取状态文本
    getStatusText(state) {
      switch (state) {
        case '1':
          return '规划'
        case '2':
          return '进行中'
        case '3':
          return '已完成'
        case '4':
          return '已取消'
        default:
          return '未知状态'
      }
    },
    
    // 刷新数据
    refreshData() {
      this.getInstitutionalData()
    },
    
    // 处理查看详细
    handleViewDetail(data) {
      console.log('查看详细:', data.item)
      // 这里可以添加跳转到详情页面的逻辑
      uni.showToast({
        title: '查看详细功能开发中',
        icon: 'none'
      })
    }
  }
}
</script>

<style lang="scss">
page {
  background: #F5F0E7;
}
.header {
  width: 100%;
  min-height: 100vh;
  display: flex;
  align-items: flex-start;
  flex-direction: column;
  background-color: #FFFBF5;
  padding: 0 15rpx;
  padding-bottom: 40rpx;
}


.loading, .empty {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
  font-size: 28rpx;
  background-color: #FFFBF5;
}
</style>