// 养殖场列表页面
const app = getApp();

Page({
  data: {
    farmList: [],
    loading: true,
    refreshing: false,
    hasMore: true,
    cursor: null,
    searchKeyword: '',
    filterStatus: 'all',
    statusOptions: [
      { value: 'all', label: '全部状态' },
      { value: 'active', label: '正常运营' },
      { value: 'pending', label: '待审核' },
      { value: 'suspended', label: '暂停运营' }
    ]
  },

  onLoad() {
    this.checkLogin();
  },

  onShow() {
    if (app.globalData.userInfo) {
      this.loadFarmList(true);
    }
  },

  onPullDownRefresh() {
    this.setData({ refreshing: true });
    this.loadFarmList(true).finally(() => {
      this.setData({ refreshing: false });
      wx.stopPullDownRefresh();
    });
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadFarmList();
    }
  },

  // 检查登录状态
  checkLogin() {
    if (!app.globalData.userInfo) {
      wx.navigateTo({
        url: '/pages/auth/login'
      });
      return;
    }
    this.loadFarmList(true);
  },

  // 加载养殖场列表
  async loadFarmList(refresh = false) {
    if (this.data.loading && !refresh) return;

    try {
      this.setData({ loading: true });

      if (refresh) {
        this.setData({
          farmList: [],
          cursor: null,
          hasMore: true
        });
      }

      const params = {
        limit: 20,
        cursor: this.data.cursor
      };

      // 添加搜索条件
      if (this.data.searchKeyword) {
        params.keyword = this.data.searchKeyword;
      }

      // 添加状态筛选
      if (this.data.filterStatus !== 'all') {
        params.status = this.data.filterStatus;
      }

      const res = await app.request({
        url: '/farms',
        method: 'GET',
        data: params
      });

      const { list, has_more, next_cursor } = res.data;

      this.setData({
        farmList: refresh ? list : [...this.data.farmList, ...list],
        hasMore: has_more,
        cursor: next_cursor
      });

    } catch (error) {
      console.error('加载养殖场列表失败：', error);
      app.showError('加载失败，请重试');
    } finally {
      this.setData({ loading: false });
    }
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索确认
  onSearchConfirm() {
    this.loadFarmList(true);
  },

  // 清除搜索
  onSearchClear() {
    this.setData({
      searchKeyword: ''
    });
    this.loadFarmList(true);
  },

  // 状态筛选
  onStatusFilter() {
    wx.showActionSheet({
      itemList: this.data.statusOptions.map(item => item.label),
      success: (res) => {
        const selectedStatus = this.data.statusOptions[res.tapIndex];
        this.setData({
          filterStatus: selectedStatus.value
        });
        this.loadFarmList(true);
      }
    });
  },

  // 点击养殖场项
  onFarmTap(e) {
    const { farm } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/farm/detail?id=${farm.id}`
    });
  },

  // 编辑养殖场
  onEditFarm(e) {
    e.stopPropagation();
    const { farm } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/farm/edit?id=${farm.id}`
    });
  },

  // 删除养殖场
  onDeleteFarm(e) {
    e.stopPropagation();
    const { farm } = e.currentTarget.dataset;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除养殖场"${farm.name}"吗？此操作不可恢复。`,
      confirmText: '删除',
      confirmColor: '#dc3545',
      success: async (res) => {
        if (res.confirm) {
          await this.deleteFarm(farm.id);
        }
      }
    });
  },

  // 执行删除
  async deleteFarm(farmId) {
    try {
      app.showLoading('删除中...');
      
      await app.request({
        url: `/farms/${farmId}`,
        method: 'DELETE'
      });
      
      app.showSuccess('删除成功');
      this.loadFarmList(true);
      
    } catch (error) {
      console.error('删除养殖场失败：', error);
      app.showError('删除失败，请重试');
    } finally {
      app.hideLoading();
    }
  },

  // 添加养殖场
  onAddFarm() {
    wx.navigateTo({
      url: '/pages/farm/add'
    });
  },

  // 查看统计
  onViewStatistics(e) {
    e.stopPropagation();
    const { farm } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/statistics/farm?farmId=${farm.id}`
    });
  },

  // 格式化状态
  formatStatus(status) {
    const statusMap = {
      'active': { text: '正常运营', class: 'status-success' },
      'pending': { text: '待审核', class: 'status-warning' },
      'suspended': { text: '暂停运营', class: 'status-danger' },
      'inactive': { text: '已停用', class: 'status-info' }
    };
    return statusMap[status] || { text: '未知状态', class: 'status-info' };
  },

  // 格式化面积
  formatArea(area) {
    if (area >= 10000) {
      return (area / 10000).toFixed(1) + '万㎡';
    }
    return area + '㎡';
  },

  // 格式化数值
  formatNumber(num) {
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + '万';
    }
    return num.toString();
  }
});