// 养殖场详情页面
const app = getApp();

Page({
  data: {
    farmId: null,
    farmInfo: null,
    animalList: [],
    statistics: null,
    weatherInfo: null,
    loading: true,
    refreshing: false,
    activeTab: 'overview', // overview, animals, statistics
    tabs: [
      { key: 'overview', name: '概览' },
      { key: 'animals', name: '动物' },
      { key: 'statistics', name: '统计' }
    ]
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ farmId: options.id });
      this.loadFarmDetail();
    } else {
      app.showError('参数错误');
      wx.navigateBack();
    }
  },

  onShow() {
    if (this.data.farmId) {
      this.loadFarmDetail();
    }
  },

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

  // 加载养殖场详情
  async loadFarmDetail() {
    try {
      this.setData({ loading: true });
      
      await Promise.all([
        this.loadFarmInfo(),
        this.loadFarmStatistics(),
        this.loadAnimalList(),
        this.loadWeatherInfo()
      ]);
      
    } catch (error) {
      console.error('加载养殖场详情失败：', error);
      app.showError('加载失败，请重试');
    } finally {
      this.setData({ loading: false });
    }
  },

  // 加载养殖场基本信息
  async loadFarmInfo() {
    try {
      const res = await app.request({
        url: `/farms/${this.data.farmId}`,
        method: 'GET'
      });
      
      this.setData({
        farmInfo: res.data
      });
      
      // 设置页面标题
      wx.setNavigationBarTitle({
        title: res.data.name
      });
      
    } catch (error) {
      console.error('加载养殖场信息失败：', error);
      throw error;
    }
  },

  // 加载统计数据
  async loadFarmStatistics() {
    try {
      const res = await app.request({
        url: `/farms/${this.data.farmId}/statistics`,
        method: 'GET'
      });
      
      this.setData({
        statistics: res.data
      });
      
    } catch (error) {
      console.error('加载统计数据失败：', error);
    }
  },

  // 加载动物列表
  async loadAnimalList() {
    try {
      const res = await app.request({
        url: '/animals',
        method: 'GET',
        data: {
          farm_id: this.data.farmId,
          limit: 10
        }
      });
      
      this.setData({
        animalList: res.data.list || []
      });
      
    } catch (error) {
      console.error('加载动物列表失败：', error);
    }
  },

  // 加载天气信息
  async loadWeatherInfo() {
    try {
      // 这里应该根据养殖场位置获取天气信息
      // 暂时使用模拟数据
      this.setData({
        weatherInfo: {
          temperature: 15,
          humidity: 65,
          weather: '晴',
          wind: '微风',
          updated_at: new Date().toLocaleString()
        }
      });
    } catch (error) {
      console.error('加载天气信息失败：', error);
    }
  },

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

  // 编辑养殖场
  onEditFarm() {
    wx.navigateTo({
      url: `/pages/farm/edit?id=${this.data.farmId}`
    });
  },

  // 添加动物
  onAddAnimal() {
    wx.navigateTo({
      url: `/pages/animal/add?farmId=${this.data.farmId}`
    });
  },

  // 查看所有动物
  onViewAllAnimals() {
    wx.navigateTo({
      url: `/pages/animal/list?farmId=${this.data.farmId}`
    });
  },

  // 查看动物详情
  onAnimalTap(e) {
    const { animal } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/animal/detail?id=${animal.id}`
    });
  },

  // 查看位置
  onViewLocation() {
    const { farmInfo } = this.data;
    if (farmInfo.longitude && farmInfo.latitude) {
      wx.openLocation({
        latitude: farmInfo.latitude,
        longitude: farmInfo.longitude,
        name: farmInfo.name,
        address: farmInfo.address
      });
    } else {
      app.showError('位置信息不完整');
    }
  },

  // 拨打电话
  onCallPhone() {
    const { farmInfo } = this.data;
    if (farmInfo.contact_phone) {
      wx.makePhoneCall({
        phoneNumber: farmInfo.contact_phone
      });
    } else {
      app.showError('联系电话不存在');
    }
  },

  // 分享养殖场
  onShareAppMessage() {
    const { farmInfo } = this.data;
    return {
      title: `${farmInfo.name} - 智慧养殖管理`,
      path: `/pages/farm/detail?id=${this.data.farmId}`,
      imageUrl: farmInfo.cover_image || '/images/share-farm.png'
    };
  },

  // 格式化状态
  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();
  },

  // 格式化金额
  formatMoney(amount) {
    if (amount >= 10000) {
      return '¥' + (amount / 10000).toFixed(1) + '万';
    }
    return '¥' + amount.toFixed(2);
  }
});