// pages/farmer/add/add.js
Page({
  data: {
    statusBarHeight: 0,
    
    // 表单数据
    formData: {
      name: '',
      phone: '',
      idCard: '',
      area: '',
      farmName: '',
      farmAddress: '',
      animalCount: '',
      animalType: '',
      email: '',
      emergencyContact: '',
      emergencyPhone: '',
      remark: ''
    },
    
    // 选择器数据
    areaList: [
      { id: 1, name: '银川市' },
      { id: 2, name: '石嘴山市' },
      { id: 3, name: '吴忠市' },
      { id: 4, name: '固原市' },
      { id: 5, name: '中卫市' }
    ],
    areaIndex: -1,
    
    animalTypeList: [
      { id: 1, name: '牛' },
      { id: 2, name: '羊' },
      { id: 3, name: '猪' },
      { id: 4, name: '鸡' },
      { id: 5, name: '其他' }
    ],
    animalTypeIndex: -1,
    
    // 提交状态
    isSubmitting: false,
    canSubmit: false
  },

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

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

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

  // 区域选择
  onAreaChange(e) {
    const index = e.detail.value;
    const area = this.data.areaList[index];
    
    this.setData({
      areaIndex: index,
      'formData.area': area ? area.name : ''
    }, () => {
      this.validateForm();
    });
  },

  // 养殖类型选择
  onAnimalTypeChange(e) {
    const index = e.detail.value;
    const animalType = this.data.animalTypeList[index];
    
    this.setData({
      animalTypeIndex: index,
      'formData.animalType': animalType ? animalType.name : ''
    }, () => {
      this.validateForm();
    });
  },

  // 表单验证
  validateForm() {
    const { formData } = this.data;
    
    // 必填字段验证
    const requiredFields = ['name', 'phone', 'area', 'farmName'];
    const isValid = requiredFields.every(field => {
      return formData[field] && formData[field].trim() !== '';
    });
    
    // 手机号格式验证
    const phoneRegex = /^1[3-9]\d{9}$/;
    const isPhoneValid = phoneRegex.test(formData.phone);
    
    // 身份证号验证（如果填写了）
    let isIdCardValid = true;
    if (formData.idCard) {
      const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      isIdCardValid = idCardRegex.test(formData.idCard);
    }
    
    // 邮箱验证（如果填写了）
    let isEmailValid = true;
    if (formData.email) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      isEmailValid = emailRegex.test(formData.email);
    }
    
    this.setData({
      canSubmit: isValid && isPhoneValid && isIdCardValid && isEmailValid
    });
  },

  // 取消操作
  onCancel() {
    // 检查是否有未保存的数据
    const hasData = Object.values(this.data.formData).some(value => value && value.trim() !== '');
    
    if (hasData) {
      wx.showModal({
        title: '提示',
        content: '确定要放弃当前编辑的内容吗？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack();
          }
        }
      });
    } else {
      wx.navigateBack();
    }
  },

  // 提交表单
  async onSubmit() {
    if (!this.data.canSubmit || this.data.isSubmitting) {
      return;
    }

    // 最终验证
    if (!this.validateFormData()) {
      return;
    }

    this.setData({ isSubmitting: true });

    try {
      // 模拟API调用
      await this.submitFarmerData();
      
      wx.showToast({
        title: '添加成功',
        icon: 'success'
      });
      
      // 延迟返回，让用户看到成功提示
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      
    } catch (error) {
      console.error('添加养殖户失败:', error);
      wx.showToast({
        title: '添加失败，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ isSubmitting: false });
    }
  },

  // 验证表单数据
  validateFormData() {
    const { formData } = this.data;
    
    if (!formData.name.trim()) {
      wx.showToast({ title: '请输入姓名', icon: 'none' });
      return false;
    }
    
    if (!formData.phone.trim()) {
      wx.showToast({ title: '请输入手机号', icon: 'none' });
      return false;
    }
    
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(formData.phone)) {
      wx.showToast({ title: '手机号格式不正确', icon: 'none' });
      return false;
    }
    
    if (!formData.area.trim()) {
      wx.showToast({ title: '请选择所属区域', icon: 'none' });
      return false;
    }
    
    if (!formData.farmName.trim()) {
      wx.showToast({ title: '请输入养殖场名称', icon: 'none' });
      return false;
    }
    
    // 身份证号验证
    if (formData.idCard && formData.idCard.trim()) {
      const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (!idCardRegex.test(formData.idCard)) {
        wx.showToast({ title: '身份证号格式不正确', icon: 'none' });
        return false;
      }
    }
    
    // 邮箱验证
    if (formData.email && formData.email.trim()) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(formData.email)) {
        wx.showToast({ title: '邮箱格式不正确', icon: 'none' });
        return false;
      }
    }
    
    // 紧急联系电话验证
    if (formData.emergencyPhone && formData.emergencyPhone.trim()) {
      if (!phoneRegex.test(formData.emergencyPhone)) {
        wx.showToast({ title: '紧急联系电话格式不正确', icon: 'none' });
        return false;
      }
    }
    
    return true;
  },

  // 提交养殖户数据
  submitFarmerData() {
    return new Promise((resolve, reject) => {
      // 模拟API请求
      setTimeout(() => {
        // 模拟成功/失败
        const success = Math.random() > 0.1; // 90%成功率
        
        if (success) {
          console.log('提交的数据:', this.data.formData);
          resolve();
        } else {
          reject(new Error('网络错误'));
        }
      }, 2000);
    });
  }
});