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

<script>
import { getInstitutionalList } from "@/api/institutionalStructure/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 StatusDisplay from "../../components/status-display/status-display.vue";
import { InstitutionalDataFormatter } from "./utils/data-formatter.js";
import { dataManagerMixin } from "./mixins/data-manager.js";
import CommonEnum from "../../enum/common";

export default {
  mixins: [dataManagerMixin],
  components: {
    CustomNavbar,
    TileGrid,
    InstitutionalItem,
    StatusDisplay,
  },
  data() {
    return {
      CommonEnum,
      bgc: {
        backgroundColor: CommonEnum.BASE_COLOR,
      },
      // 动态数据数组
      institutionalData: [],
      pageStatus: "",
    };
  },
  onLoad() {
    // 页面加载时获取数据
    this.getInstitutionalData();
  },
  methods: {
    // 获取建制数据
    async getInstitutionalData() {
      const res = await getInstitutionalList(this.pageStatus);
      const rawData = res.rows;
      this.institutionalData =
        InstitutionalDataFormatter.transformData(rawData);
      try {
        console.log("建制数据已更新, 数量:", this.institutionalData.length);
      } catch (error) {
        console.error("获取建制数据失败:", error);
        uni.showToast({
          title: "获取数据失败",
          icon: "none",
        });
      }
    },

    // 处理查看详细
    handleViewDetail(data) {
      console.log("查看详细:", data.item);
      // 跳转到捐款记录页面，传递建制ID
      uni.navigateTo({
        url: `/pages/institutionalStructure/donationRecord?formedId=${data.item.formedId}`,
        fail: (err) => {
          console.error("跳转失败:", err);
          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;
}
</style>
