// pages/projects/projects.js
const { apiService } = require('../../services/apiService');
const auth = require('../../utils/auth.js');

Page({
  data: {
    projects: [],
    activeTab: 'all',
    loading: false,
    statusMap: {
      'supervision': '监管中',
      'completed': '已结项',
      'pending': '待监管'
    }
  },

  onLoad() {
    // 检查认证状态
    if (!auth.isAuthenticated()) {
      wx.reLaunch({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.loadProjects();
  },

  onShow() {
    // 检查认证状态
    if (!auth.isAuthenticated()) {
      wx.reLaunch({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.loadProjects();
  },

  // 加载项目数据
  async loadProjects() {
    this.setData({ loading: true });
    
    try {
      const params = {
        page: 1,
        limit: 20,
        status: this.data.activeTab === 'all' ? '' : this.data.activeTab
      };
      
      const response = await apiService.projects.getList(params);
      
      if (response.success) {
        const projects = response.data.projects.map(project => ({
          ...project,
          statusText: this.data.statusMap[project.status] || project.status,
          showDeviceInfo: project.status === 'completed' // 只有已结项的项目显示设备信息
        }));
        
        this.setData({
          projects,
          loading: false
        });
      } else {
        throw new Error(response.message || '获取项目列表失败');
      }
    } catch (error) {
      console.error('加载项目失败:', error);
      
      // 使用模拟数据作为降级处理
      const mockProjects = [
        {
          id: 1,
          farmName: '大数据中心',
          loanOfficer: '1',
          status: 'completed',
          statusText: '已结项',
          supervisionObject: '牛',
          supervisionQuantity: 10,
          supervisionPeriod: '23天',
          supervisionAmount: '10000.00',
          startTime: '2024-02-21',
          endTime: '2024-03-15',
          earTag: 0,
          collar: 0,
          host: 0,
          showDeviceInfo: true
        },
        {
          id: 2,
          farmName: '大数据中心',
          loanOfficer: '1',
          status: 'completed',
          statusText: '已结项',
          supervisionObject: '牛',
          supervisionQuantity: 0,
          supervisionPeriod: '0天',
          supervisionAmount: '0.00',
          startTime: '2024-02-26',
          endTime: '2024-02-27',
          earTag: 0,
          collar: 0,
          host: 0,
          showDeviceInfo: false
        }
      ];
      
      this.setData({
        projects: mockProjects,
        loading: false
      });
      
      wx.showToast({
        title: '使用模拟数据',
        icon: 'none'
      });
    }
  },

  // 切换标签
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
    this.loadProjects();
  },

  // 查看项目详情
  viewProjectDetail(e) {
    const projectId = e.currentTarget.dataset.projectId;
    wx.navigateTo({
      url: `/pages/projects/detail?projectId=${projectId}`
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadProjects().finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 上拉加载更多
  onReachBottom() {
    // 这里可以实现分页加载
    console.log('加载更多项目');
  }
});