// pages/farmer/edit/edit.js
Page({
  data: {
    statusBarHeight: 0,
    loading: true,
    farmerId: '',
    
    // 表单数据
    formData: {
      name: '',
      phone: '',
      idCard: '',
      area: '',
      status: '',
      farmName: '',
      farmAddress: '',
      animalCount: '',
      animalType: '',
      email: '',
      emergencyContact: '',
      emergencyPhone: '',
      remark: ''
    },
    
    // 原始数据（用于比较是否有修改）
    originalData: {},
    
    // 选择器数据
    areaList: [
      { id: 1, name: '银川市' },
      { id: 2, name: '石嘴山市' },
      { id: 3, name: '吴忠市' },
      { id: 4, name: '固原市' },
      { id: 5, name: '中卫市' }
    ],
    areaIndex: -1,
    
    statusList: [
      { id: 1, name: '正常' },
      { id: 2, name: '异常' },
      { id: 3, name: '待审核' }
    ],
    statusIndex: -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,
      farmerId: options.id || ''
    });
    
    // 检查登录状态
    this.checkLoginStatus();
    
    // 加载养殖户数据
    if (this.data.farmerId) {
      this.loadFarmerData();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

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

  // 加载养殖户数据
  async loadFarmerData() {
    try {
      wx.showLoading({ title: '加载中...' });
      
      // 模拟API调用
      const farmerData = await this.fetchFarmerData(this.data.farmerId);
      
      // 设置表单数据
      this.setData({
        formData: { ...farmerData },
        originalData: { ...farmerData },
        loading: false
      });
      
      // 设置选择器索引
      this.setPickerIndexes(farmerData);
      
      wx.hideLoading();
      
    } catch (error) {
      console.error('加载养殖户数据失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 模拟获取养殖户数据
  fetchFarmerData(id) {
    return new Promise((resolve) => {
      setTimeout(() => {
        // 模拟数据
        const mockData = {
          id: id,
          name: '张三',
          phone: '13800138000',
          idCard: '640100199001011234',
          area: '银川市',
          status: '正常',
          farmName: '张三养殖场',
          farmAddress: '银川市兴庆区某某村',
          animalCount: '100',
          animalType: '牛',
          email: 'zhangsan@example.com',
          emergencyContact: '李四',
          emergencyPhone: '13900139000',
          remark: '优质养殖户，管理规范'
        };
        resolve(mockData);
      }, 1000);
    });
  },

  // 设置选择器索引
  setPickerIndexes(data) {
    // 设置区域索引
    const areaIndex = this.data.areaList.findIndex(item => item.name === data.area);
    
    // 设置状态索引
    const statusIndex = this.data.statusList.findIndex(item => item.name === data.status);
    
    // 设置养殖类型索引
    const animalTypeIndex = this.data.animalTypeList.findIndex(item => item.name === data.animalType);
    
    this.setData({
      areaIndex: areaIndex >= 0 ? areaIndex : -1,
      statusIndex: statusIndex >= 0 ? statusIndex : -1,
      animalTypeIndex: animalTypeIndex >= 0 ? animalTypeIndex : -1
    });
    
    this.validateForm();
  },

  // 输入框变化处理
  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();
    });
  },

  // 状态选择
  onStatusChange(e) {
    const index = e.detail.value;
    const status = this.data.statusList[index];
    
    this.setData({
      statusIndex: index,
      'formData.status': status ? status.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);
    }
    
    // 检查是否有修改
    const hasChanges = this.hasDataChanged();
    
    this.setData({
      canSubmit: isValid && isPhoneValid && isIdCardValid && isEmailValid && hasChanges
    });
  },

  // 检查数据是否有修改
  hasDataChanged() {
    const { formData, originalData } = this.data;
    
    return Object.keys(formData).some(key => {
      return formData[key] !== originalData[key];
    });
  },

  // 取消操作
  onCancel() {
    // 检查是否有未保存的修改
    if (this.hasDataChanged()) {
      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.updateFarmerData();
      
      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()) {
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(formData.emergencyPhone)) {
        wx.showToast({ title: '紧急联系电话格式不正确', icon: 'none' });
        return false;
      }
    }
    
    return true;
  },

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