const app = getApp<IAppOption>()

Page({
  data: {
    imageUrl: '',
    resultData: null as any,
    envTemp: '28.0', // 默认温度
    envHum: '85.0'   // 默认湿度
  },

  inputTemp(e: any) { this.setData({ envTemp: e.detail.value }) },
  inputHum(e: any) { this.setData({ envHum: e.detail.value }) },

  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({
          imageUrl: tempFilePath,
          resultData: null
        });
        this.uploadForPAD(tempFilePath);
      }
    });
  },

  uploadForPAD(filePath: string) {
    wx.showLoading({ title: 'AI引擎全速分析中...', mask: true });
    
    // 之前报错是因为带了 /PAD_predict，现在直接请求根目录 /api/detect/
    wx.uploadFile({
      url: `${app.globalData.baseUrl}/api/detect/`, 
      filePath: filePath,
      name: 'image',
      formData: {
        'user_id': (app.globalData.userInfo && app.globalData.userInfo.user_id) || '',
        'temp': this.data.envTemp,
        'hum': this.data.envHum
      },
      success: (res) => {
        wx.hideLoading();
        const data = JSON.parse(res.data);
        if (data.code === 200) {
          this.setData({
            imageUrl: data.data.image_base64,
            resultData: data.data
          });
          wx.showToast({ title: '诊断出炉', icon: 'success' });
        } else {
          wx.showToast({ title: data.msg, icon: 'none' });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error(err);
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      }
    });
  }
})