// pages/farmer/detail/detail.js
Page({
  data: {
    statusBarHeight: 0,
    loading: true,
    farmerId: '',
    farmerInfo: {},
    checkRecords: []
  },

  onLoad(options) {
    // 检查登录状态
    this.checkLoginStatus();
    
    // 获取状态栏高度
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight
    });

    // 获取养殖户ID
    if (options.id) {
      this.setData({
        farmerId: options.id
      });
      this.loadFarmerDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  onShow() {
    // 检查登录状态
    this.checkLoginStatus();
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return false;
    }
    return true;
  },

  // 加载养殖户详情
  async loadFarmerDetail() {
    try {
      this.setData({ loading: true });
      
      // 模拟API调用
      const farmerData = await this.fetchFarmerDetail(this.data.farmerId);
      const checkData = await this.fetchCheckRecords(this.data.farmerId);
      
      this.setData({
        farmerInfo: farmerData,
        checkRecords: checkData,
        loading: false
      });
    } catch (error) {
      console.error('加载养殖户详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
      this.setData({ loading: false });
    }
  },

  // 模拟获取养殖户详情API
  fetchFarmerDetail(farmerId) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockData = {
          id: farmerId,
          name: '张三',
          phone: '13800138000',
          idCard: '610104199001011234',
          area: '西夏区',
          status: 'normal',
          farmName: '张三养殖场',
          farmAddress: '宁夏银川市西夏区兴泾镇',
          animalCount: 120,
          animalType: '肉牛',
          email: 'zhangsan@example.com',
          emergencyContact: '李四 13900139000',
          registerTime: '2023-01-15',
          lastCheckTime: '2024-01-15 14:30',
          remarks: '该养殖户管理规范，牲畜健康状况良好，配合度高。'
        };
        resolve(mockData);
      }, 1000);
    });
  },

  // 模拟获取检查记录API
  fetchCheckRecords(farmerId) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockRecords = [
          {
            id: '1',
            checkTime: '2024-01-15 14:30',
            inspector: '王检查员',
            result: 'normal',
            description: '牲畜健康状况良好，饲料充足，环境卫生达标。'
          },
          {
            id: '2',
            checkTime: '2024-01-10 09:15',
            inspector: '李检查员',
            result: 'warning',
            description: '发现部分牲畜有轻微感冒症状，已建议及时治疗。'
          },
          {
            id: '3',
            checkTime: '2024-01-05 16:20',
            inspector: '张检查员',
            result: 'normal',
            description: '整体情况良好，建议继续保持现有管理水平。'
          },
          {
            id: '4',
            checkTime: '2023-12-28 11:45',
            inspector: '王检查员',
            result: 'error',
            description: '发现饲料存储不当，已要求立即整改。'
          }
        ];
        resolve(mockRecords);
      }, 800);
    });
  },

  // 编辑养殖户信息
  onEdit() {
    wx.navigateTo({
      url: `/pages/farmer/edit/edit?id=${this.data.farmerId}`
    });
  },

  // 拨打电话
  onCall() {
    const phone = this.data.farmerInfo.phone;
    if (!phone) {
      wx.showToast({
        title: '无联系电话',
        icon: 'error'
      });
      return;
    }

    wx.showModal({
      title: '拨打电话',
      content: `确定要拨打 ${phone} 吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: phone,
            fail: (error) => {
              console.error('拨打电话失败:', error);
              wx.showToast({
                title: '拨打失败',
                icon: 'error'
              });
            }
          });
        }
      }
    });
  },

  // 添加检查记录
  onAddCheck() {
    wx.navigateTo({
      url: `/pages/check/add/add?farmerId=${this.data.farmerId}&farmerName=${this.data.farmerInfo.name}`
    });
  },

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