// pages/farmer/farmer.js
Page({
  data: {
    mode: 'view', // view, edit, add
    farmerId: null,
    farmerInfo: {},
    formData: {},
    animalTypes: ['牛羊混养', '肉牛养殖', '奶牛养殖', '羊养殖', '其他'],
    animalTypeIndex: 0,
    loading: false
  },

  onLoad: function (options) {
    this.checkLoginStatus();
    
    // 根据参数确定页面模式
    if (options.mode === 'add') {
      this.setData({
        mode: 'add'
      });
      this.initFormData();
    } else if (options.id) {
      this.setData({
        mode: 'view',
        farmerId: options.id
      });
      this.loadFarmerInfo(options.id);
    }
  },

  checkLoginStatus: function() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.reLaunch({
        url: '/pages/login/login'
      });
      return false;
    }
    return true;
  },

  // 加载养殖户信息
  loadFarmerInfo: function(farmerId) {
    this.setData({ loading: true });

    // 模拟数据
    const mockFarmer = {
      id: farmerId,
      name: '张三',
      phone: '13800138001',
      address: '宁夏银川市兴庆区某某村123号',
      farmName: '张三养殖场',
      animalCount: 120,
      status: 'active',
      registerTime: '2023-01-15',
      animalType: '牛羊混养',
      farmArea: '500',
      lastCheckTime: '2024-01-15'
    };

    setTimeout(() => {
      this.setData({
        farmerInfo: mockFarmer,
        loading: false
      });
    }, 1000);
  },

  // 初始化表单数据
  initFormData: function() {
    this.setData({
      formData: {
        name: '',
        farmName: '',
        phone: '',
        address: '',
        animalCount: '',
        animalType: '',
        farmArea: ''
      }
    });
  },

  // 返回上一页
  onBack: function() {
    wx.navigateBack();
  },

  // 编辑模式
  onEdit: function() {
    const { farmerInfo } = this.data;
    this.setData({
      mode: 'edit',
      formData: {
        name: farmerInfo.name,
        farmName: farmerInfo.farmName,
        phone: farmerInfo.phone,
        address: farmerInfo.address,
        animalCount: farmerInfo.animalCount.toString(),
        animalType: farmerInfo.animalType,
        farmArea: farmerInfo.farmArea
      },
      animalTypeIndex: this.data.animalTypes.indexOf(farmerInfo.animalType)
    });
  },

  // 输入框变化
  onInputChange: function(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 选择器变化
  onPickerChange: function(e) {
    const field = e.currentTarget.dataset.field;
    const index = e.detail.value;
    const value = this.data.animalTypes[index];
    
    this.setData({
      [`formData.${field}`]: value,
      animalTypeIndex: index
    });
  },

  // 保存数据
  onSave: function() {
    const { formData, mode } = this.data;
    
    // 验证必填字段
    if (!formData.name || !formData.farmName || !formData.phone || !formData.address || !formData.animalCount) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    // 验证手机号
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(formData.phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: mode === 'add' ? '保存中...' : '更新中...'
    });

    // 模拟保存
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: mode === 'add' ? '保存成功' : '更新成功',
        icon: 'success'
      });

      setTimeout(() => {
        if (mode === 'add') {
          wx.navigateBack();
        } else {
          // 更新模式，重新加载数据并切换到查看模式
          this.loadFarmerInfo(this.data.farmerId);
          this.setData({ mode: 'view' });
        }
      }, 1500);
    }, 1000);
  },

  // 取消编辑
  onCancel: function() {
    if (this.data.mode === 'add') {
      wx.navigateBack();
    } else {
      this.setData({ mode: 'view' });
    }
  },

  // 删除养殖户
  onDelete: function() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个养殖户吗？此操作不可恢复。',
      confirmText: '删除',
      confirmColor: '#F44336',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...'
          });

          // 模拟删除
          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });

            setTimeout(() => {
              wx.navigateBack();
            }, 1500);
          }, 1000);
        }
      }
    });
  },

  onShareAppMessage: function() {
    return {
      title: '养殖户详情',
      path: `/pages/farmer/farmer?id=${this.data.farmerId}`
    };
  }
});